How Real Time Bidding Fills an Ad Slot From Request to Win Notice

15 min read

The problem

A news page loads with an empty 300x250 box near the top. Somewhere out there are thousands of advertisers who might pay to fill it, and each of them values this particular reader differently. The publisher wants the highest price. The advertisers want to pay as little as they can. Nobody wants the reader to stare at a blank box.

For years the industry answered this with a queue: ask one buyer, and if they pass, ask the next. Today much of it runs as an auction that happens inside a single page load, using a shared JSON format called OpenRTB. This part walks through that auction from the request that leaves the page to the price that gets written into a win notice. At the end there is a small Python simulator, run on this VM, that does the whole thing with three fake buyers.

Three ways to sell one slot

The waterfall

In a waterfall, the publisher's ad server ranks demand partners in a fixed order, usually by their average past price. It calls the first one. If that partner has nothing at the required floor price, the request falls to the next partner, and so on down the list. Prebid's own explainer puts the weakness plainly: partners are called one after another, which limits yield and is slow.

Partner number four might value this reader far more than partner number one, but it never gets asked if partner one says yes at a lower price.

Real-time bidding

Real-time bidding (RTB) flips the queue into an auction. An exchange sends the same bid request to many buyers at once, waits a fixed time for answers, and picks a winner by price. OpenRTB is the format most of those requests use. It started in November 2010 as a pilot between three demand-side platforms (DataXu, MediaMath and Turn) and three supply-side platforms (Admeld, PubMatic and Rubicon Project), shipped version 2.0 in June 2011, and became an IAB Tech Lab standard with 2.1 in January 2012.

Header bidding

Even with RTB, the publisher's ad server often still gave its own exchange a head start. Header bidding fixes that by running an auction in the page (or on a server) before the ad server is called, then handing the best outside bids to the ad server so they compete with everything else. OpenRTB 2.5 added support for exactly this flow, and the spec's source.fd field even uses header bidding as its example of an upstream decision.

flowchart LR
  subgraph W[Waterfall]
    W1[Partner A] ==>|pass| W2[Partner B]
    W2 ==>|pass| W3[Partner C]
    W3 ==>|pass| W4[House ad]
  end
  subgraph H[Header bidding plus RTB]
    P[Page] ==> A1[Bidder A]
    P ==> A2[Bidder B]
    P ==> A3[Bidder C]
    A1 ==> S[Best bid per slot]
    A2 ==> S
    A3 ==> S
    S ==> G[Ad server picks final winner]
  end

Who does what: SSP, exchange, DSP

Three kinds of systems show up in almost every programmatic sale.

  • SSP (supply-side platform). Works for the publisher. It packages each impression into a bid request, applies the publisher's floors and blocks, and sells to many buyers.
  • Ad exchange. The marketplace where the auction actually runs. In practice most SSPs run their own exchange, which is why the two terms blur.
  • DSP (demand-side platform). Works for the advertiser. It receives bid requests, decides in milliseconds whether this impression is worth buying and at what price, and answers with a bid and the ad markup.
sequenceDiagram
  participant B as Browser
  participant S as SSP / exchange
  participant D1 as DSP 1
  participant D2 as DSP 2
  B->>S: Ad request for slot (page, device, consent)
  S->>D1: BidRequest (OpenRTB JSON, tmax)
  S->>D2: BidRequest (same impression)
  D1->>S: BidResponse: price 1.00, adm, nurl
  D2->>S: HTTP 204 (no bid)
  S->>S: Drop bids under floor, pick winner, set clearing price
  S->>D1: Win notice: nurl with ${AUCTION_PRICE} filled in
  S->>B: Winning ad markup

The OpenRTB 2.6 bid request

The spec lives on GitHub at InteractiveAdvertisingBureau/openrtb2.x. Since the 2.6-202211 release, the version number only changes for breaking changes, so new fields arrive as dated updates to 2.6 rather than as 2.7.

Transport is plain HTTP. The exchange sends a POST with Content-Type: application/json and the required header x-openrtb-version: 2.6. A buyer answers 200 with a bid, 204 for no bid, or 400 if the request was invalid. Enumerated values (device types, creative attributes and so on) are defined in a companion spec called AdCOM 1.0.

The top level: BidRequest

Only two fields are required: id and imp (at least one impression). The rest describe the context and the rules of the sale.

FieldWhat it means
idUnique ID for this request. Echoed back in the response.
impArray of impressions on offer.
site or appWhere the ad will show. A request carries one or the other, never both.
device, userWho and what is on the other end (see below).
atAuction type. Default 2. In the spec's words, "1 = First Price, 2 = Second Price Plus". Values 500 and up are exchange specific.
tmax"Maximum time in milliseconds the exchange allows for bids to be received including Internet latency to avoid timeout."
curAllowed bid currencies, as ISO 4217 codes.
bcat, badvBlocked content categories and blocked advertiser domains.
regsPrivacy and legal signals.
sourceWhere the request came from, including the supply chain.

imp and its media objects

Each imp has a required id, plus exactly the media types the slot accepts:

  • banner: sizes go in format as a list of {w, h} pairs, plus pos, blocked attributes battr, and supported apis.
  • video: mimes is required. Also min and max duration, protocols, plcmt (the placement field that replaced the deprecated placement in the 2.6-202303 update) and, new in 2.6, ad pod fields such as podid, poddur and slotinpod for connected TV breaks.
  • native: a single required request string that holds a native ad request.

Price rules sit on the impression: bidfloor is the minimum CPM (default 0) and bidfloorcur its currency (default USD). secure: 1 means the creative must load over HTTPS.

device and user

device carries the user agent (ua, with structured sua preferred since 2.6), ip, devicetype, os, geo, language, connectiontype and the mobile advertising ID ifa. user carries the exchange's user id, the buyer's own ID for this user (buyeruid), a consent string from the IAB Transparency and Consent Framework, and eids: an array of extended IDs, each with a source and a list of uids.

regs: GDPR, US privacy and GPP

regs is where legal signals travel. coppa flags child-directed traffic. gdpr is 0 or 1. us_privacy holds the older US Privacy string. gpp holds a Global Privacy Platform string, and gpp_sid lists which GPP sections apply. Buyers are expected to read these before using any personal data in their bid.

source.schain

source.schain is the SupplyChain object. It lists every company that touched this impression on its way to the buyer, as nodes. Each node has asi (the company's domain, the same domain that appears in ads.txt), sid (the seller account ID, at most 64 characters), and hp (1 if that company handles payment). complete: 1 claims the chain goes all the way back to the publisher.

The bid response

The response mirrors the request. id must match the request ID. Bids are grouped into seatbid entries, one per buyer seat, and each holds a bid array.

A bid needs only three fields: id, impid (which impression it is for) and price (CPM, in the response cur, default USD). In practice it also carries:

  • adm: the ad markup itself, HTML for a banner, VAST XML for video.
  • nurl: the win notice URL. The spec says it is called on a win but is not necessarily billable.
  • burl: the billing notice URL, called when the impression is billable. The spec says firing it server-side is best practice.
  • lurl: the loss notice URL.
  • adomain: the advertiser's domain, so the exchange can enforce badv.
  • crid: the creative ID, used for creative review and reporting.
  • mtype: the markup type (1 banner, 2 video, 3 audio, 4 native).

A minimal real request and response

Here is a request for one 300x250 banner with a $0.85 floor, first-price auction, a 300 ms tmax, one blocked category, one blocked advertiser, privacy signals and a one-node supply chain. All values are fictional.

json
{
  "id": "80ce30c53c16e6ede735f123ef6e32361bfc7b22",
  "at": 1,
  "tmax": 300,
  "cur": ["USD"],
  "bcat": ["IAB25"],
  "badv": ["blocked-brand.example"],
  "imp": [
    {
      "id": "1",
      "tagid": "article-top",
      "banner": { "format": [{ "w": 300, "h": 250 }] },
      "bidfloor": 0.85,
      "bidfloorcur": "USD",
      "secure": 1
    }
  ],
  "site": {
    "id": "102855",
    "domain": "news.example",
    "page": "https://news.example/story",
    "publisher": { "id": "pub-123", "name": "News Example" }
  },
  "device": {
    "ua": "Mozilla/5.0 (Linux; Android 14) AppleWebKit/537.36",
    "ip": "203.0.113.7",
    "devicetype": 4,
    "language": "en"
  },
  "user": { "id": "55816b39711f9b5acf3b90e313ed29e51665623f" },
  "regs": { "coppa": 0, "gdpr": 0, "us_privacy": "1YNN" },
  "source": {
    "tid": "tx-001",
    "schain": {
      "ver": "1.1",
      "complete": 1,
      "nodes": [{ "asi": "ssp.example", "sid": "pub-123", "hp": 1 }]
    }
  }
}

And one buyer's answer:

json
{
  "id": "80ce30c53c16e6ede735f123ef6e32361bfc7b22",
  "cur": "USD",
  "seatbid": [
    {
      "seat": "dsp-alpha",
      "bid": [
        {
          "id": "bid-1",
          "impid": "1",
          "price": 1.00,
          "adm": "<a href=\"https://alpha-shoes.example\"><img src=\"https://cdn.alpha-shoes.example/300x250.png\"></a>",
          "adomain": ["alpha-shoes.example"],
          "crid": "alpha-cr9",
          "w": 300,
          "h": 250,
          "mtype": 1,
          "nurl": "https://dsp-alpha.example/win?auction=${AUCTION_ID}&price=${AUCTION_PRICE}",
          "burl": "https://dsp-alpha.example/bill?auction=${AUCTION_ID}&price=${AUCTION_PRICE}"
        }
      ]
    }
  ]
}

We saved both as files on this VM and ran a short check against the required fields in the 2.6 object tables (request id and imp, each imp.id, no site and app together, response id matching, each bid with id, impid and price, impid pointing at a real impression, price at or above the floor). This is a field check, not a full schema validator:

python
import json

req = json.load(open("minimal_request.json"))
resp = json.load(open("minimal_response.json"))

assert req["id"] and len(req["imp"]) >= 1
assert all("id" in imp for imp in req["imp"])
assert not ("site" in req and "app" in req), "site and app are exclusive"
assert resp["id"] == req["id"]
imp_ids = {imp["id"] for imp in req["imp"]}
for sb in resp["seatbid"]:
    for b in sb["bid"]:
        assert {"id", "impid", "price"} <= b.keys()
        assert b["impid"] in imp_ids
        assert b["price"] >= req["imp"][0]["bidfloor"]
print("request ok:", len(req["imp"]), "imp, at =", req["at"], ", tmax =", req["tmax"], "ms")
print("response ok:", sum(len(sb["bid"]) for sb in resp["seatbid"]), "bid, price =", resp["seatbid"][0]["bid"][0]["price"])

Output:

text
request ok: 1 imp, at = 1 , tmax = 300 ms
response ok: 1 bid, price = 1.0

The 300 ms tmax is a value chosen for this example, not a figure from the spec. The spec only says the field is in milliseconds.

Win notices and the ${AUCTION_PRICE} macro

The buyer does not know the final price when it bids. So it puts placeholders in its URLs and markup, and the exchange swaps in real values before calling them. The spec defines these macros:

MacroReplaced with
${AUCTION_ID}The bid request id
${AUCTION_BID_ID}The response bidid
${AUCTION_IMP_ID}The impression id
${AUCTION_PRICE}The clearing price, in the bid's currency and units
${AUCTION_LOSS}A loss reason code (for lurl)
${AUCTION_MIN_TO_WIN}The price that would have been needed to win

If a value is unknown, the exchange substitutes an empty string. A suffix can request encoding, as in ${AUCTION_PRICE:B64}.

The spec's own worked example uses a $0.85 floor and a winning bid of $1.00 against a runner-up at $0.90. Under first price, ${AUCTION_PRICE} is 1.00 (the winner pays its bid). Under second price, the winner pays the second-best bid plus $0.01, so the macro becomes 0.91.

OpenRTB 3.0 and AdCOM, briefly

OpenRTB 3.0 splits the protocol into layers: transport, format, transaction and domain. The domain layer is AdCOM, which describes ads, placements, users and devices separately from the auction messages. The root object becomes openrtb, imp becomes item, and billing and loss events get their own structure. It also folds in ads.cert for signed requests. The 3.0 document on GitHub is dated March 2022, but active updates still land in the 2.x line, so 2.6 is what most examples look like.

ads.txt, sellers.json and schain: who is allowed to sell

An auction is only as honest as its inventory. If anyone can claim to sell ads on a well known news site, buyers can be tricked into paying for fake impressions. Three IAB Tech Lab files close that gap together (the glossary entry is ads.txt and sellers.json).

  • ads.txt sits at /ads.txt on the publisher's domain as plain text, an idea borrowed from robots.txt. Version 1.0 came out on June 27, 2017. Each line names an ad system domain, the publisher's account ID in that system, whether the relationship is DIRECT or RESELLER, and an optional certification authority ID. Version 1.1 (July 2022) added OWNERDOMAIN and MANAGERDOMAIN variables.
  • sellers.json (version 1.0, July 2019) sits at /sellers.json on the ad system's own domain. It lists each seller_id the system works with, the seller_type (PUBLISHER, INTERMEDIARY or BOTH), and whether the entry is confidential.
  • schain in the bid request lists each hop. A buyer can check that every node's asi and sid appear in the publisher's ads.txt and in that system's sellers.json.
text
ads.txt line         ssp.example, pub-123, DIRECT
sellers.json entry   {"seller_id": "pub-123", "seller_type": "PUBLISHER", "domain": "news.example"}
schain node          {"asi": "ssp.example", "sid": "pub-123", "hp": 1}

The same pub-123 should appear in all three. If it does not, the buyer has a reason to distrust the request.

Prebid.js: header bidding in the page

Prebid.js is the open source library most publishers use to run header bidding in the browser. The flow, taken from Prebid's own basic example, looks like this:

  1. Tell Google Publisher Tag not to load ads yet (googletag.pubads().disableInitialLoad()).
  2. Define adUnits: each has a code (the ad slot), the sizes it accepts, and a bids array listing each bidder adapter and its parameters.
  3. Call pbjs.requestBids({ bidsBackHandler }). Prebid sends requests to all bidders in parallel.
  4. When bids come back, or the timeout hits, bidsBackHandler runs pbjs.setTargetingForGPTAsync() and then googletag.pubads().refresh().
  5. A separate failsafe setTimeout calls the ad server anyway if Prebid never answers.
javascript
const PREBID_TIMEOUT = 700; // value used in Prebid's own example page

const adUnits = [{
  code: '/19968336/header-bid-tag-1',
  mediaTypes: { banner: { sizes: [[300, 250]] } },
  bids: [{ bidder: 'msft', params: { placement_id: 13144370 } }]
}];

pbjs.que.push(() => {
  pbjs.addAdUnits(adUnits);
  pbjs.requestBids({
    timeout: PREBID_TIMEOUT,
    bidsBackHandler: () => {
      pbjs.setTargetingForGPTAsync();
      googletag.pubads().refresh();
    }
  });
});

This snippet follows the structure of Prebid's documented example and was not run here, because it needs a browser, GPT and live bidders.

Timeouts

The default bidderTimeout in the Prebid.js source (src/config.ts) is 3000 ms. Prebid's FAQ recommends "1,000 milliseconds or less for the internal auction timeout" and "3,000 milliseconds or less for the Prebid tag's overall failsafe timeout". The setConfig docs note that the browser timer can fire late, and the auction is closed if it runs more than 200 ms past the limit.

Targeting keys and GAM

Once the auction ends, Prebid writes key-values onto each ad slot. For the winning bid that includes hb_bidder, hb_adid, hb_pb, hb_size and hb_format. Because enableSendAllBids is on by default, it also sets one hb_pb_<bidder> key per bidder. Prebid's GAM setup guide notes that GAM caps key names at 20 characters, so the per-bidder keys stay short.

hb_pb is not the raw price. It is the bid rounded down into a price bucket, so the ad server only needs one line item per bucket rather than one per possible cent. Prebid ships five built-in granularities:

GranularityBuckets
low$0.50 steps, capped at $5
medium (default)$0.10 steps, capped at $20
high$0.01 steps, capped at $20
auto$0.05 to $5, $0.10 to $10, $0.50 to $20
dense$0.01 to $3, $0.05 to $8, $0.50 to $20

What hb_pb becomes for five sample bids under each Prebid granularity

We computed that table on this VM by applying the documented rules. The $1.87 auto result (1.85) matches the example in Prebid's docs.

On the GAM side, Prebid's step-by-step guide sets up Price priority line items, one per bucket, each targeting a value of hb_pb. An order can hold up to 450 line items. When GPT calls GAM, those Prebid line items compete with GAM's own demand and direct deals, and the highest one serves. Google moved Ad Manager to a unified first-price auction in 2019, and it says no buyer's bid is shared with another buyer before that buyer bids.

Prebid Server: the same auction, off the page

Every extra bidder in the browser costs network requests on the reader's device. Prebid Server moves the auction to a server: the page (or app) sends one request to the Prebid Server endpoint /openrtb2/auction, and the server fans out to bidders using OpenRTB. Prebid describes it as open source server-to-server header bidding with more than 230 bidder adapters. It validates requests, can fill in stored request data, enforces privacy rules, converts currencies, applies price granularity, and caches video VAST in Prebid Cache.

Prebid's timeouts page recommends setting the server-side timeout (s2sConfig.timeout) to 50 to 75% of the client auction timeout. That value is sent to Prebid Server as tmax. The prebidServer module docs give the default as "75% of bidderTimeout or 750ms, whichever is lesser". Prebid's FAQ suggests keeping roughly 1 to 5 demand partners client-side and moving the rest to the server.

Running an auction on this VM

To see the moving parts together, we wrote a short Python script (standard library only) and ran it on this VM. It builds an OpenRTB 2.6 request, asks three fake DSPs for bids, drops any bid below the $0.85 floor or from a blocked advertiser, picks a winner under at=1 and at=2, and fills the macros in the winner's nurl. The prices match the spec's macro example so the result can be checked against it.

python
#!/usr/bin/env python3
import json
from decimal import Decimal, ROUND_DOWN

FLOOR = Decimal("0.85")  # CPM, same floor the OpenRTB 2.6 macro examples use

def build_request(at):
    return {
        "id": "req-7f3a", "at": at, "tmax": 300, "cur": ["USD"],
        "bcat": ["IAB25", "IAB26"], "badv": ["blocked-brand.example"],
        "imp": [{"id": "1", "tagid": "article-top",
                 "banner": {"format": [{"w": 300, "h": 250}]},
                 "bidfloor": float(FLOOR), "bidfloorcur": "USD", "secure": 1}],
        "site": {"id": "s1", "domain": "news.example",
                 "page": "https://news.example/story",
                 "publisher": {"id": "pub-123"}},
        "device": {"ua": "Mozilla/5.0", "ip": "203.0.113.7",
                   "devicetype": 2, "language": "en"},
        "user": {"id": "u-anon-42"},
        "regs": {"coppa": 0, "gdpr": 0, "us_privacy": "1YNN",
                 "gpp": "", "gpp_sid": []},
        "source": {"tid": "tx-001", "schain": {
            "ver": "1.1", "complete": 1,
            "nodes": [{"asi": "ssp.example", "sid": "pub-123", "hp": 1}]}},
    }

# Each fake DSP returns a fixed CPM. A real DSP would score the request.
DSPS = [("dsp-alpha", Decimal("1.00"), "alpha-shoes.example"),
        ("dsp-beta",  Decimal("0.90"), "beta-phones.example"),
        ("dsp-gamma", Decimal("0.60"), "gamma-tea.example")]

def dsp_respond(req, seat, cpm, adomain):
    imp = req["imp"][0]
    return {"id": req["id"], "cur": "USD", "seatbid": [{"seat": seat, "bid": [{
        "id": f"{seat}-b1", "impid": imp["id"], "price": float(cpm),
        "adm": f"<a href='https://{adomain}'><img src='https://cdn.{adomain}/300x250.png'></a>",
        "adomain": [adomain], "crid": f"{seat}-cr9", "w": 300, "h": 250, "mtype": 1,
        "nurl": (f"https://{seat}.example/win?auction=${{AUCTION_ID}}"
                 f"&imp=${{AUCTION_IMP_ID}}&price=${{AUCTION_PRICE}}"),
    }]}]}

def collect(req):
    bids = []
    for seat, cpm, adomain in DSPS:
        resp = dsp_respond(req, seat, cpm, adomain)
        for sb in resp["seatbid"]:
            for b in sb["bid"]:
                b["_seat"] = sb["seat"]
                bids.append(b)
    return bids

def run(at):
    req = build_request(at)
    bids = collect(req)
    print(f"== auction at={at} ({'first price' if at == 1 else 'second price'}) floor={FLOOR} ==")
    for b in bids:
        print(f"  {b['_seat']:<10} bid {b['price']:.2f}")
    valid = [b for b in bids
             if Decimal(str(b["price"])) >= FLOOR
             and not set(b["adomain"]) & set(req["badv"])]
    dropped = [b["_seat"] for b in bids if b not in valid]
    print(f"  dropped under floor or blocked: {dropped}")
    valid.sort(key=lambda b: b["price"], reverse=True)
    if not valid:
        print("  no winner, return 204 No Content")
        return
    win = valid[0]
    top = Decimal(str(win["price"]))
    if at == 1:
        clear = top
    else:
        runner_up = Decimal(str(valid[1]["price"])) if len(valid) > 1 else FLOOR
        clear = min(top, max(runner_up + Decimal("0.01"), FLOOR))
    clear = clear.quantize(Decimal("0.01"), rounding=ROUND_DOWN)
    nurl = (win["nurl"].replace("${AUCTION_ID}", req["id"])
                       .replace("${AUCTION_IMP_ID}", win["impid"])
                       .replace("${AUCTION_PRICE}", str(clear)))
    print(f"  winner {win['_seat']} crid={win['crid']} pays {clear} CPM")
    print(f"  win notice: {nurl}")

if __name__ == "__main__":
    req = build_request(1)
    print("bid request bytes:", len(json.dumps(req)))
    run(1)
    run(2)

Run with Python 3.12.3:

text
bid request bytes: 713
== auction at=1 (first price) floor=0.85 ==
  dsp-alpha  bid 1.00
  dsp-beta   bid 0.90
  dsp-gamma  bid 0.60
  dropped under floor or blocked: ['dsp-gamma']
  winner dsp-alpha crid=dsp-alpha-cr9 pays 1.00 CPM
  win notice: https://dsp-alpha.example/win?auction=req-7f3a&imp=1&price=1.00
== auction at=2 (second price) floor=0.85 ==
  dsp-alpha  bid 1.00
  dsp-beta   bid 0.90
  dsp-gamma  bid 0.60
  dropped under floor or blocked: ['dsp-gamma']
  winner dsp-alpha crid=dsp-alpha-cr9 pays 0.91 CPM
  win notice: https://dsp-alpha.example/win?auction=req-7f3a&imp=1&price=0.91

Three bids against a $0.85 floor, clearing at 1.00 under first price and 0.91 under second price

The same three bids produce two different prices. Under first price, dsp-alpha pays its full $1.00 CPM. Under second price, it pays $0.91: the runner-up's $0.90 plus one cent. dsp-gamma never enters either auction because $0.60 is under the floor. Both results match the spec's macro example.

What the script leaves out: no network, no real tmax timer, no consent logic, no burl or lurl, and the DSPs bid fixed numbers instead of predicting value. It shows the selection rules and macro substitution, nothing more.

What's next

RTB is the open market: many sellers, many buyers, one shared protocol. The biggest ad businesses mostly do not work like that. They own the users, the inventory and the data, and run their own auctions inside. Next up: how Meta, Amazon and The Trade Desk ads differ from Google.

Sources