Real-Time Bidding Ad Exchange at 1M QPS

Medium · System Design · Backend Engineer · Onsite

Prompt

Design the backend architecture for a real-time bidding (RTB) video ad exchange that sits between streaming-TV publishers and external Demand-Side Platforms (DSPs). Whenever a viewer enters an ad break, the publisher sends an opportunity to your exchange, which solicits bids from matching buyers and returns a winning ad creative.

Your design must satisfy the following functional and operational targets:

  • Inbound & outbound protocol flow: Ingest HTTP or gRPC ad-slot calls carrying viewer attributes, device identifiers, and program metadata; filter external buyers by targeting rules; and fan out bid requests to eligible DSPs.
  • Auction clearing & accounting: Determine the winner and clearing price via a second-price auction, and capture both auction telemetry and financial settlement logs for downstream batch/stream processing.
  • Throughput & latency SLA: Sustain 1,000,000 inbound requests per second (1M QPS) while keeping end-to-end exchange turnaround strictly below 50 ms.
  • Resilience: Maintain high availability and degrade cleanly whenever individual DSPs respond late, return errors, or go offline.

Scope & Expectations

  • Wire contracts & time budget: Specify the request/response payloads across publishers, the exchange, and DSPs, and break down how every millisecond of the 50 ms budget is allocated.
  • Service topology & profile enrichment: Show how stateless auction handlers, geographic routing, and sub-millisecond user-segment / frequency-cap lookups fit together at 1M QPS (plus outbound fan-out).
  • Hot state vs. durable ledgers: Contrast in-memory operational state with high-volume auction event streams and zero-loss financial billing storage.
  • Straggler & fault isolation: Detail concrete deadline enforcement, throttling, and circuit-breaking mechanisms so a degraded DSP never jeopardizes publisher tail latency.

Step-by-step walkthrough

  1. Clarify requirements, ad-tech terms, and scope

    When a viewer watching a free movie on an ad-supported connected-TV app reaches a commercial break, the app asks our ad exchange to fill that 30-second video slot in real-time bidding (RTB)—a live automated auction that finishes before the video player stutters. Let us define the core actors in plain English first:

    • Publisher: The streaming app or channel selling ad space.
    • DSP (Demand-Side Platform): An automated buying server representing advertisers (such as major retail or automotive brands) that decides in milliseconds whether to bid on an ad slot and how much to offer.
    • CPM (Cost Per Mille): The standard ad price unit, meaning dollars per 1,000 ad views (so a $15.00 CPM bid pays $0.015 for one play).

    Functional requirements

    • Ingest ad-opportunity calls over HTTP/2 or gRPC (a fast binary RPC protocol) carrying viewer attributes, connected-TV device IDs, and program metadata.
    • Filter ~50 integrated DSPs down to the eligible buyers whose targeting rules match the request, and fan out bid requests in parallel.
    • Run a second-price auction (highest bidder wins, paying $0.01 above the second-highest valid bid, floored at the publisher's minimum price).
    • Log auction analytics and exact billing records for offline processing without slowing down the response.

    Non-functional requirements and scope assumptions

    • Strict tail latency: Total exchange round-trip time < 50 ms at p99 (measured from first request byte entering our regional load balancer to last response byte leaving it).
    • Throughput: 1,000,000 requests/second (1M QPS) at evening prime-time peak (~600,000 QPS daily average).
    • Graceful degradation: If a DSP slows down or crashes, or if our internal user-profile store hiccups, auctions continue within 50 ms without cascading failures.
    • Billing trigger: Advertisers pay when the video ad actually begins playing on the TV (impression), not merely when the auction is won, because viewers sometimes close the app before the ad starts.
    • Privacy compliance: If a device sets lmt = 1 (Limit Ad Tracking) or lacks consent, we skip profile lookup and strip device IDs before calling DSPs.
  2. Back-of-the-envelope scale and the 50 ms latency budget

    At 1M QPS, small multipliers create massive network and concurrency numbers. Let us size outbound fan-out, in-flight connections, RAM, and logs first.

    Traffic & fan-out (at 1M QPS peak)
      Inbound publisher requests:   1,000,000 /s
      Matched DSPs per request:     ~8 out of ~50 integrated DSPs
      Outbound DSP bid calls:       8,000,000 /s  (8x fan-out!)
      Positive bids returned (~20%): 1,600,000 /s (other 80% return empty HTTP 204 No Content)
      Auctions won (30% fill rate):   300,000 /s  (~180,000 /s daily average)
    
    Concurrent calls in flight (Little's Law: Concurrency = Rate x Time)
      Publisher requests in flight: 1,000,000/s x 0.045 s =  45,000 open requests
      Outbound DSP calls in flight: 8,000,000/s x 0.030 s = 240,000 open calls!
        -> One OS thread per call is impossible; requires event-loop async I/O + warm connection pools
    
    Network bandwidth
      Inbound from publishers (2 KB JSON/Protobuf): 1M/s x 2 KB   =  2.0 GB/s =  16 Gbps
      Outbound to DSPs (2 KB x 8M/s):               8M/s x 2 KB   = 16.0 GB/s = 128 Gbps  <- #1 cost!
      Inbound from DSPs (1.6M x 3 KB + 6.4M x 100B):              =  5.4 GB/s =  43 Gbps
    
    Compute fleet (~1 ms total CPU time per auction across parsing + 8 outbound calls)
      Busy CPU cores needed:        1,000,000/s x 0.001 s = 1,000 CPU cores
      Fleet across 4 regions:       100 stateless 32-core servers = 3,200 total cores
        -> Runs at ~31% CPU at peak (~10,000 QPS/node), so if an entire region fails over to its
           neighbor, surviving nodes run at ~62% CPU (safely below the 80% queueing cliff)
    
    User profile store (300M active Connected TV / streaming devices)
      Record size:                  ~400 B (audience segments + frequency-cap counters)
      Dataset footprint:            300M x 400 B = ~120 GB (~240 GB RAM per region with 2x replication)
        -> Easily fits 100% in RAM in every region!
    
    Daily log volume (~600k QPS daily average, 86,400 s/day)
      Auction records (~600 B binary): 600k/s x 600 B = 360 MB/s avg (600 MB/s peak) -> ~31 TB/day raw
                                       (~5 TB/day compressed Parquet)
      Impression billing (~300 B):     180k/s x 300 B =  54 MB/s avg ( 90 MB/s peak) -> ~4.7 TB/day
                                       (retained 100%, zero sampling)
    

    Where every millisecond of the 50 ms p99 budget goes

    Elapsed (ms)   Pipeline Stage                                                    Budget
    ---------------------------------------------------------------------------------------
    0 - 1 ms       Parse HTTP/2 or gRPC BidRequest, auth publisher, load floor rules   1 ms
    1 - 3 ms       Parallel: Aerospike profile read (hard 2 ms timeout), in-memory     2 ms
                   Geo-IP lookup, and in-memory pre-bid fraud checks
    3 - 4 ms       Evaluate 64-bit DSP targeting bitmasks, rate limits, & breakers     1 ms
    4 - 40 ms      Scatter async calls to ~8 DSPs (advertise tmax = 35 ms;             36 ms
                   hard gavel slam at t = 40 ms—late replies cancelled)
    40 - 42 ms     Run second-price auction, wrap VAST XML, serialize response         2 ms
    42 - 50 ms     Headroom for OS scheduling, garbage-collection pauses, & jitter     8 ms
    ---------------------------------------------------------------------------------------
    Total exchange round-trip ceiling                                                 50 ms
    

    Notice the golden rule revealed by this timeline: waiting on external DSPs consumes 36 ms of our 50 ms budget, leaving only 6 ms for all internal exchange work combined. Every internal step must live in local process RAM—except a single parallelized 2 ms read to an in-memory profile store.

  3. API design: OpenRTB, VAST, and impression billing

    Rather than inventing proprietary schemas that force every advertiser to write custom code, we speak OpenRTB 2.6 (the open industry standard for real-time ad auctions) over HTTP/2 keep-alive JSON or Protobuf/gRPC, and wrap winning video ads in VAST 4.0 (Video Ad Serving Template, an XML snippet telling the TV video player where to fetch the video file and which tracking URLs to ping when playback starts).

    1. Publisher -> Exchange: POST /openrtb2/auction (or gRPC Exchange.Auction)
    {
      "id": "auc-9b4e",
      "tmax": 50,
      "imp": [{
        "id": "1",
        "video": { "mimes": ["video/mp4"], "minduration": 15, "maxduration": 30, "w": 1920, "h": 1080 },
        "bidfloor": 10.00, "bidfloorcur": "USD"
      }],
      "app": { "bundle": "tv.example.cinema", "publisher": { "id": "pub-42" },
               "content": { "genre": "Drama", "contentrating": "TV-14", "livestream": 0 } },
      "device": { "ifa": "ctv-8a14...", "lmt": 0, "ip": "203.0.113.7", "geo": { "country": "USA" } }
    }
    
    2. Exchange -> Eligible DSPs (same schema, scrubbed per DSP):
       - Sets "tmax": 35 and "at": 2 (announces second-price auction)
       - Attaches only the audience segments this specific DSP is licensed to see
       - Strips "device.ifa" when Limit Ad Tracking ("lmt": 1) is enabled
    
    3. DSP -> Exchange:
       - Either HTTP 204 No Content (~80% of calls: zero body, near-zero CPU to parse)
       - Or HTTP 200 OK with bid:
         { "id": "auc-9b4e", "seatbid": [{ "seat": "dsp-9", "bid": [{
             "id": "b1", "impid": "1", "price": 16.40, "crid": "cr-881",
             "adomain": ["automaker.example"], "adm": "<VAST version=\"4.0\">...</VAST>",
             "burl": "https://dsp9.example/win?p=${AUCTION_PRICE}"
           }]}] }
    
    4. Exchange -> Publisher:
       - HTTP 200 OK wrapping the winner's VAST inside our Exchange VAST Wrapper containing
         our signed impression pixel: https://imp.exchange.example/v1/imp?aid=auc-9b4e&p=1326&sig=...
       - Or HTTP 204 No Content if no valid bid met the $10.00 floor
    

    Why separate auction win from impression ping? When the TV player actually starts playing frame 1 of the ad seconds later, it requests our <Impression> URL (carrying an HMAC cryptographic signature over auction_id and clearing_price_cents so no client can forge prices, and requiring zero database reads at ping time!). Our impression collector records the billable event and fires the winning DSP's burl (billing URL) with ${AUCTION_PRICE} substituted (13.26).

  4. Data model: hot-path memory vs. offline logs

    To hit < 50 ms at 1M QPS, we split storage strictly by access latency:

    1. In-process Node RAM (pushed every 30 s as immutable snapshots from Config Service; ~0 ns lookup)
       - dsp_configs:      dsp_id, regional_endpoint, qps_cap, protocol, targeting rules, status
       - placement_rules:  publisher_id, floor_cents_by_geo, blocked_categories, blocked_domains
       - targeting_index:  attribute_value -> 64-bit integer bitmask of matching DSPs
       - fraud_blocklists: bad IP CIDRs, spoofed user-agents, unauthorized (app, seller) pairs
    
    2. Regional In-Memory KV Store (Aerospike / Redis Cluster; < 1 ms single-hop read, 30-day TTL)
       - Key:              SHA-256(device_advertising_id)
       - Value (~400 B):   { segment_ids: int32[],
                             freq_caps:   map<line_item_id, {count: uint16, window_start_ts: uint32}> }
    
    3. Streaming & Analytical Storage (100% off the critical request path)
       - Kafka `auctions`:     ~600 B Protobuf per auction -> compacted to hourly S3/GCS Parquet (13 months)
                               + rolled up into ClickHouse/Druid for real-time partner dashboards
       - Kafka `impressions`:  3x replicated (`acks=all`), zero sampling -> deduplicated stream job
       - PostgreSQL `ledger`:  Hourly `(hour_utc, dsp_id, publisher_id)` exact financial settlement rows
    

    Notice the static stability rule for configuration: bid-handler nodes never query PostgreSQL or a config microservice during an auction. If the central Config Service goes completely offline, all 100 auction nodes keep running normally off their last in-memory snapshot.

  5. High-level regional cell architecture

    A single packet traveling from New York to California and back takes ~65 ms at the speed of light in fiber—already exceeding our entire 50 ms budget! Therefore, we deploy 4 independent regional cells (for example, US-East, US-Central, US-West, and EU-West) co-located in the same cloud regions / data centers where DSPs host their bidding servers.

    Streaming TV Apps / Publisher SSAI Servers
           |  (GeoDNS / Anycast routes to geographically nearest region)
           v
    +------------------------ REGIONAL CELL (e.g., US-East, ~25 nodes) ------------------------+
    |  [ L4 Load Balancers ]                                                                   |
    |         |                                                                                |
    |         v                                                                                |
    |  [ Stateless Exchange Node (Gateway + Auctioneer in ONE process, ~10k QPS/node) ]        |
    |    |-- 1. Parse, auth, in-memory Geo-IP & fraud pre-check                                |
    |    |-- 2. Async single-key read (2 ms timeout) ---> [ Regional Aerospike RAM Cluster ]   |
    |    |-- 3. 64-bit bitmask targeting + AIMD throttle + per-DSP circuit breaker             |
    |    |-- 4. Scatter parallel OpenRTB calls (tmax=35 ms) ===> [ Co-located DSP Bidders ]    |
    |    |-- 5. Hard close at t=40 ms -> 2nd-price auction -> VAST wrapper -> Reply (< 50 ms)  |
    |    +-- 6. Non-blocking write to in-RAM ring buffer                                       |
    |                  | (background flush every 20 ms)                                        |
    |                  v                                                                       |
    |         [ Regional Kafka ] ---> [ Stream Processors: freq-cap updates, fraud, rollups ]  |
    |                            ---> [ S3 Parquet Lake + ClickHouse Real-Time Analytics ]     |
    +------------------------------------------------------------------------------------------+
           ^                                                        |
           | (30s config snapshots + 10s budget leases)             v (TV plays video ad)
    [ Global Config & Pacing Control Plane ]              [ Regional Impression Collectors ]
                                                                    | (acks=all, deduped)
                                                                    v
                                                          [ Global Billing Ledger (PostgreSQL) ]
    

    Why combine API Gateway and Auctioneer into a single binary? Splitting "Gateway" and "Auctioneer" into separate microservices would add an extra internal network hop, serialize and deserialize 2 GB/s of JSON/Protobuf a second time, and burn 1–2 precious milliseconds out of our 6 ms internal budget—for zero scaling benefit, because both scale linearly with inbound QPS.

  6. Deep dive: 50 ms deadline, async scatter-gather, and DSP circuit breakers

    Preventing a slow or dead DSP from hurting the exchange requires four coordinated defenses:

    1. Clock-driven scatter-gather (asynchronous bidding): All ~8 outbound DSP requests launch simultaneously on an event loop over pre-warmed HTTP/2 or HTTP/1.1 keep-alive connection pools (a fresh TLS handshake takes 10–30 ms, which would ruin the budget!). A single 36 ms timer governs the entire fan-out (t = 4 ms to t = 40 ms). At t = 40 ms, we immediately cancel pending tasks and run the auction on whatever bids arrived in time.
    2. 64-bit bitmask targeting in nanoseconds: With ~50 DSPs, each DSP gets one bit position (0..49) in a 64-bit integer. At config-load time, we precompute a 64-bit mask for each country, device type, format, and publisher. Intersecting four integers with bitwise & selects eligible DSPs in a few CPU clock cycles!
    3. AIMD adaptive throttling before tripping: Most slow DSPs are simply overloaded. Before cutting a DSP off completely, each node tracks its 10-second timeout rate: if timeouts exceed 5%, we multiply its send rate by 0.8 (Multiplicative Decrease), and nudge it back up +2% per healthy window (Additive Increase), plus smart traffic shaping (using a lightweight logistic model to send a DSP only the auctions it is most likely to bid high on when its QPS cap is lower than eligible traffic).
    4. Local per-node circuit breakers: If a DSP crashes outright (> 20% errors/timeouts across the last 1,000 calls), the node's local circuit breaker trips Open for 30 seconds—skipping that DSP in 0 ns without wasting sockets. After 30 seconds, it enters Half-Open, letting 1% of requests probe the DSP: if probes succeed, it closes; if more than 10 probes fail (already guaranteeing > 20% failure on a 50-probe trial), it snaps back to Open immediately. Keeping breaker state local per node (each node sees ~400 QPS per DSP—plenty of statistical signal within 2 seconds!) avoids adding any shared Redis lock to the hot path.
    import asyncio
    from collections import deque
    
    
    async def gather_dsp_bids(dsp_coroutines: dict, timeout_sec: float = 0.036) -> tuple:
        """Fan out DSP calls concurrently and slam the gavel at `timeout_sec` (36 ms)."""
        if not dsp_coroutines:
            return [], []
    
        # Map each non-blocking asyncio Task back to its dsp_id.
        task_to_dsp = {
            asyncio.create_task(coro): dsp_id
            for dsp_id, coro in dsp_coroutines.items()
        }
    
        done, pending = await asyncio.wait(task_to_dsp.keys(), timeout=timeout_sec)
    
        # Cancel stragglers immediately so slow DSPs never delay the 50 ms publisher deadline.
        timed_out_dsps = []
        for task in pending:
            task.cancel()
            timed_out_dsps.append(task_to_dsp[task])
    
        valid_bids = []
        for task in done:
            if not task.cancelled() and task.exception() is None:
                bid = task.result()
                if bid is not None:
                    valid_bids.append(bid)
    
        return valid_bids, timed_out_dsps
    
    
    class DspCircuitBreaker:
        """Lock-free local circuit breaker isolating an unhealthy DSP on one exchange node."""
    
        def __init__(
            self,
            window_size: int = 1000,
            min_calls: int = 100,
            max_fail_rate: float = 0.20,
            cooldown_sec: float = 30.0,
            probe_rate: float = 0.01,
            probe_batch: int = 50,
        ):
            self.window_size = window_size
            self.min_calls = min_calls
            self.max_fail_rate = max_fail_rate
            self.cooldown_sec = cooldown_sec
            self.probe_rate = probe_rate
            self.probe_batch = probe_batch
            self.outcomes = deque()  # sliding window of booleans (True = timeout/5xx failure)
            self.fail_count = 0
            self.state = "closed"    # "closed" (healthy) | "open" (blocked) | "half_open" (probing)
            self.opened_at = 0.0
    
        def allow_request(self, now: float, rand_0_to_1: float) -> bool:
            """Decide in O(1) memory time whether to send an auction request to this DSP."""
            if self.state == "open":
                if now - self.opened_at < self.cooldown_sec:
                    return False
                # Cooldown elapsed: transition to half_open and test with 1% probe traffic.
                self.state = "half_open"
                self.outcomes.clear()
                self.fail_count = 0
    
            if self.state == "half_open":
                return rand_0_to_1 < self.probe_rate
            return True
    
        def record_outcome(self, failed: bool, now: float) -> None:
            """Update sliding failure count and transition breaker state."""
            self.outcomes.append(failed)
            if failed:
                self.fail_count += 1
            if len(self.outcomes) > self.window_size:
                if self.outcomes.popleft():
                    self.fail_count -= 1
    
            if self.state == "closed":
                if len(self.outcomes) >= self.min_calls:
                    if (self.fail_count / len(self.outcomes)) > self.max_fail_rate:
                        self.state = "open"
                        self.opened_at = now
            elif self.state == "half_open":
                # Fast-fail as soon as failures exceed the allowed count for the 50-probe trial!
                max_allowed_probe_fails = int(self.max_fail_rate * self.probe_batch)
                if self.fail_count > max_allowed_probe_fails:
                    self.state = "open"
                    self.opened_at = now
                elif len(self.outcomes) >= self.probe_batch:
                    self.state = "closed"
    
  7. Deep dive: sub-millisecond profile lookups and frequency capping

    To enrich bid requests with audience segments (such as "sports_fan") and enforce frequency caps ("show Deal #881 at most 3 times per TV per 24 hours"), we cannot make multiple database trips.

    • Single co-located record: Hashing the device's resettable connected-TV advertising ID (IFA) points to a single ~400-byte record in a regional Aerospike (or Redis Cluster) deployment running in RAM/NVMe inside the exact same availability zone. Sub-millisecond p99 reads (~0.5–0.8 ms) run concurrently with Geo-IP and fraud checks under a strict 2 ms timeout.
    • Fail-open vs. fail-closed on timeout: If a profile read exceeds 2 ms, we do not abort the auction! Instead, we exclude exchange-managed frequency-capped deals (fail closed so we never break an advertiser's frequency cap promise) while letting uncapped open-market auctions proceed without audience segments (fail open so the publisher still earns ad revenue).
    • Lock-free frequency updates: Acquiring a distributed lock per device at 1M QPS would add latency and contention. Instead, we check the counter during the 2 ms read, prevent duplicate winners inside multi-slot ad breaks (ad pods) in memory, and increment the counter asynchronously right upon winning the auction (300k writes/s across the cluster). Counting wins rather than impressions slightly under-delivers when a viewer exits before playback, which safely errs on the side of respecting the viewer's frequency cap.
    def is_under_frequency_cap(
        freq_map: dict,
        line_item_id: str,
        max_exposures: int,
        window_sec: int,
        now_ts: int,
    ) -> bool:
        """Check in O(1) whether a device has seen `line_item_id` fewer than `max_exposures` times."""
        entry = freq_map.get(line_item_id)
        if entry is None:
            return True
        count, window_start_ts = entry
        # If the rolling window has expired, the old count no longer blocks bidding.
        if now_ts - window_start_ts >= window_sec:
            return True
        return count < max_exposures
    
  8. Deep dive: exact second-price auction and two-tier logging

    Validation and integer-cent second-price math. Before entering the auction, every returned bid is checked against the publisher's floor price, currency, blocked advertiser domains/categories, and pre-approved creative IDs. In a second-price auction, the highest valid bidder wins and pays one cent ($0.01) above the second-highest valid bid—floored at the publisher's bidfloor and capped at the winner's own bid. Let us trace all three cases (with a $10.00 floor):

    Case 1 (Normal competition):  DSP A bids $16.40, DSP B bids $13.25 -> A wins, pays $13.26 ($13.25 + $0.01)
    Case 2 (Single valid bidder): DSP A bids $16.40 alone              -> A wins, pays $10.00 (the floor)
    Case 3 (Exact tie at top):    DSP A bids $16.40, DSP B bids $16.40 -> Seeded random tie-break picks winner;
                                  min($16.40 + $0.01, $16.40) = $16.40 (never charge $16.41 > winner's bid!)
    

    In production, we compute all prices in integer cents (or integer micro-dollars, 1 USD = 1,000,000 micros) rather than floating-point numbers so binary rounding (0.1 + 0.2 = 0.30000000000000004) never creates penny discrepancies across billions of daily auctions:

    import random
    from dataclasses import dataclass
    
    
    @dataclass
    class ValidatedBid:
        dsp_id: str
        price_cents: int  # e.g., $16.40 CPM = 1640 cents
    
    
    def run_second_price_auction(
        bids: list,
        floor_cents: int,
        auction_id: str,
        increment_cents: int = 1,
    ) -> tuple:
        """Run an exact integer-cent second-price auction; returns (winner_bid, clearing_cents)."""
        eligible = [b for b in bids if b.price_cents >= floor_cents]
        if not eligible:
            return None, 0
    
        # Shuffle with deterministic seed `auction_id` so ties are fair AND reproducible from logs!
        rng = random.Random(auction_id)
        rng.shuffle(eligible)
    
        winner = eligible[0]
        runner_up_cents = None
    
        for bid in eligible[1:]:
            if bid.price_cents > winner.price_cents:
                runner_up_cents = winner.price_cents
                winner = bid
            elif runner_up_cents is None or bid.price_cents > runner_up_cents:
                runner_up_cents = bid.price_cents
    
        if runner_up_cents is None:
            clearing_cents = floor_cents
        else:
            clearing_cents = max(floor_cents, runner_up_cents + increment_cents)
    
        # Critical cap: on an exact tie (or $0.00 gap), never charge more than the winner's own bid!
        clearing_cents = min(clearing_cents, winner.price_cents)
        return winner, clearing_cents
    

    Two-tier storage: loss-tolerant analytics vs. zero-loss billing

    1. Analytics path (1M auctions/s, 8M DSP calls/s): Exchange nodes append ~600-byte auction summaries to a lock-free in-memory ring buffer, flushed asynchronously to regional Kafka every 20 ms and compacted to hourly Parquet in object storage + ClickHouse rollups. Raw per-DSP call logs (8M/s) are aggregated in-stream and sampled at 1%; if Kafka ever backs up past local disk spill, raw analytics drop before auction latency is ever touched.
    2. Financial billing path (300k impressions/s): Impression collectors write signed playback pings to a dedicated 3× replicated Kafka topic (acks=all). A stateful Flink/Spark streaming job deduplicates retried TV pings over a 24-hour (auction_id, imp_id) window, filters invalid bot traffic, fires DSP burl webhooks, and writes idempotent hourly totals (INSERT ... ON CONFLICT (hour_utc, dsp_id, publisher_id) DO UPDATE SET spend_micros = EXCLUDED.spend_micros) to PostgreSQL so replaying a failed batch overwrites with the exact same total instead of double-charging.
  9. Global distribution, scaling bottlenecks, and failure handling

    Geographic partitioning. GeoDNS (or Anycast routing) directs every streaming TV or SSAI (Server-Side Ad Insertion, a server that stitches ad video segments directly into the live stream) request to its closest regional cell. Because living-room TVs stay in one home, > 99% of a device's requests naturally hit the same regional Aerospike cluster; background cross-region replication syncs segments for traveling devices.

    Key bottlenecks & mitigations

    • 128 Gbps outbound DSP egress: Mitigate via model-driven traffic shaping, Protobuf/gRPC or gzip compression with high-volume DSPs, and private data-center cross-connects rather than public internet egress fees.
    • JVM/Go garbage-collection pauses at p99: Reuse pre-allocated request/buffer pools (sync.Pool / off-heap buffers) so 10,000 QPS per node generates minimal heap churn inside our 8 ms jitter margin.
    Failure Scenario Blast Radius Automated Mitigation
    Single DSP latency spike That DSP's late bids Cut off at t = 40 ms; AIMD reduces its QPS; local circuit breaker trips at > 20% failure
    Aerospike node crash 1/N shard failover Replica serves within < 1 ms; any > 2 ms timeout skips capped deals and runs open auction
    Kafka cluster stall Local log backlog Ring buffer spills to local NVMe; analytics shed if full; billing uses isolated acks=all cluster
    Whole US-East region outage Regional traffic GeoDNS shifts traffic to US-Central (fleet sized at ~31% peak CPU absorbs partner region at ~62% CPU)

Intuition & how it works

Think of a real-time ad exchange like a live wholesale fish auction run with a strict 50-millisecond stopwatch. Every time a viewer's streaming TV show hits a commercial break—1,000,000 times per second—the app asks the auctioneer to sell that 30-second video slot. The auctioneer cannot call 50 buyers one by one, look up thick paper folders in a distant warehouse, or wait politely for a slow buyer stuck on hold. Instead, it glances at a single index card kept in local memory for that TV (< 1 ms), shouts the offer simultaneously to the ~8 buyers interested in that audience, slams the gavel down at exactly 40 milliseconds, awards the slot to the highest bidder at one cent above the second-highest bid (so buyers bid their honest value without guessing games), hands back the winning video link before 50 milliseconds, and drops the receipt into an outbox tray for accounting to tally in the background.

A naive backend architecture fails at 1M QPS and 50 ms for three physical reasons. First, calling DSPs (Demand-Side Platforms, automated advertiser servers) sequentially—or waiting for the slowest DSP without a hard auction cutoff—lets one lagging partner ruin latency for everyone. Second, each request fans out to ~8 DSPs (8,000,000 outbound calls/second, or 240,000 calls simultaneously in flight!), which instantly exhausts thread-per-request servers or fresh TCP/TLS handshakes, while a single cross-country database hop (~65 ms NY-to-CA round trip) blows the entire 50 ms budget by itself. Third, writing 31 TB/day of auction logs synchronously or billing on unverified auction wins either stalls the hot path or mischarges advertisers.

Let us trace one commercial-break request (auc-9b4e, publisher floor $10.00 CPM, meaning $10.00 per 1,000 views) from t = 0 ms to t = 42 ms:

  1. t = 0–3 ms (Ingest & enrich): GeoDNS routes the TV to a nearby US-East exchange node. The node parses the OpenRTB (open real-time bidding standard) request in 1 ms and fires a single 0.8 ms read to the local Aerospike in-memory store (key = hash(device_id)), retrieving the viewer's audience segments and frequency-cap counters.
  2. t = 3–4 ms (Filter buyers): Intersecting four 64-bit integer bitmasks (country & device_type & format & publisher) narrows 50 DSPs down to 9 matches, and one local circuit breaker skips DSP-4 because it has been timing out, leaving 8 healthy DSPs.
  3. t = 4–40 ms (Parallel scatter-gather): Eight non-blocking HTTP/2 calls go out at once with tmax = 35 ms. Five DSPs reply 204 No Content, DSP-A bids $16.40 at 22 ms, DSP-B bids $13.25 at 31 ms, and DSP-H stalls. At t = 40 ms sharp, the node cancels DSP-H.
  4. t = 40–42 ms (Second-price gavel & async log): DSP-A wins and clears at $13.26 CPM ($13.25 + $0.01). The node wraps DSP-A's VAST (XML video ad tag) with our signed impression-tracking URL, replies to the TV app at 42 ms, and appends the auction record to an in-RAM ring buffer—billing only after the TV player actually starts playing the ad and pings our impression collector.

Key trade-offs

  • Hard 40 ms auction cutoff vs. waiting for every DSP. Cancelling unfinished DSP calls at t = 40 ms occasionally throws away a lucrative $25 bid arriving at 41 ms, costing a tiny slice of fill revenue. In exchange, publisher p99 latency stays rock-solid under 50 ms and one degraded DSP can never drag down the rest of the exchange.
  • Per-node local circuit breakers & throttles vs. centralized cluster state. Tracking DSP timeout rates and AIMD (Additive Increase, Multiplicative Decrease, gently trimming send rates before tripping an all-or-nothing circuit breaker) inside each node's own RAM means each of the 25 regional nodes learns about a dead DSP independently over ~1–2 seconds rather than instantaneously. Avoiding a shared Redis/ZooKeeper call on 8M outbound calls/second removes an entire failure point and ~1 ms of hot-path latency.
  • Co-located Gateway + Auctioneer process vs. separate microservices. Combining request parsing, targeting, and auction execution into one stateless binary couples releases between those modules, but eliminates an internal network hop and double serialization of 2 GB/s of request payloads—saving 1–2 ms out of our tight 6 ms internal budget.
  • Single denormalized RAM profile record vs. normalized database lookups. Packing audience segment IDs and frequency-cap counters into one ~400-byte Aerospike/Redis value per device (~120 GB globally, replicated in RAM per region) caps profile richness, but guarantees a single < 1 ms lookup—with a crisp fail-closed rule for capped deals and fail-open rule for open auctions whenever the 2 ms timeout triggers.
  • Incrementing frequency caps at win time vs. impression time. Updating a device's exposure count asynchronously the millisecond an auction is won (rather than seconds later when the video plays) slightly over-counts when viewers close the app mid-break, trading minor under-delivery for closing the race window where rapid back-to-back requests could exceed an advertiser's cap.
  • Loss-tolerant analytics pipeline vs. replicated idempotent billing pipeline. Sampling 8M/s raw DSP call logs and buffering 31 TB/day of auction records in memory saves huge storage cost and protects latency under load, whereas separating the 300k/s impression pings onto a 3x replicated (acks=all), 24-hour deduplicated stream with idempotent hourly PostgreSQL upserts guarantees exact financial settlement.
  • Independent regional cells vs. a single global deployment. Running self-contained regional stacks (handlers, Aerospike, Kafka, co-located DSP endpoints) duplicates ~240 GB of profile RAM per region and allows rare cross-region counter lag for traveling devices, because physics forbids spending 65 ms on cross-continent network round trips inside a 50 ms SLA.

Common mistakes

  • Setting per-DSP socket timeouts without a global auction timer, or spawning one thread/connection per outbound call, which either lets tail latency drift past 50 ms or crashes servers under 240,000 simultaneous in-flight DSP calls and TLS handshakes.
  • Designing for 1M inbound QPS while forgetting the 8× outbound fan-out, under-provisioning network NICs and egress bandwidth for 8,000,000 outbound requests/second (128 Gbps).
  • Putting synchronous central counters, SQL reads, or Kafka acks=all writes on the 50 ms request path, turning hot keys and broker hiccups into immediate SLA violations.
  • Getting second-price auction edge cases or floating-point math wrong: charging $0.00 instead of the publisher floor when only one DSP bids, charging $16.41 when two DSPs tie at $16.40 (violating the winner's maximum bid!), or using IEEE-754 floats instead of integer cents/micro-dollars.
  • Billing advertisers on auction wins rather than verified video impressions, overcharging buyers whenever users exit an app before the commercial break plays.
  • Sending hedged (duplicate backup) requests to slow DSPs, doubling traffic onto a partner server that is typically slow precisely because its CPU queue is already overloaded.

Follow-up questions

  • How can distributed auction nodes enforce campaign budget pacing accurately without a central hot-path lock? Running distributed consensus (Paxos/Raft) or a central atomic decrement on 300,000 wins/second across regions is far too slow and creates massive hot-key contention on popular campaigns. Instead, a central Pacing Service hands each auctioneer node short budget leases—small pre-allocated dollar allowances valid for ~10 seconds (across a $50,000/day campaign spending ~$0.58/s, the whole 100-node fleet holds only ~$5.80 in active leases at once, or ~0.01% of the daily budget). Nodes deduct clearing_price / 1000 locally in memory with zero network calls, stop bidding on that campaign if their slice runs dry, renew asynchronously, and shrink lease sizes automatically as remaining daily budget approaches zero so campaigns never overspend while a 1-minute PID controller adjusts bid-participation probability to match the target hourly spend curve.
  • Suppose inbound ad-break traffic jumps 5x during a major live broadcast—how should the exchange shed load and scale? Because auto-scaling new VMs and warming connection pools takes 2–5 minutes—and our 100-node fleet sized at ~31% CPU maxes out around ~2.5× (~2.5M QPS)—the system must survive the first minutes via fast, revenue-aware load shedding (returning HTTP 204 No Content in 0.05 ms rather than timing out 5M auctions at 50 ms). First, per-publisher token buckets at the load balancer block any single broken app SDK retry storm from starving healthy publishers. Second, whenever a node's internal queue delay exceeds 3 ms, it sheds lowest-expected-CPM placements first and degrades mid-tier auctions into "lite mode" (skipping the Aerospike profile read and fanning out to only the top 3 highest-value DSPs instead of 8, cutting CPU and egress by > 60%) while pre-warmed standby instances spin up—keeping per-DSP QPS caps strictly enforced so our surge never DDoSes downstream DSPs.
  • How do you catch invalid or spoofed ad traffic before clearing an auction while staying inside the 50 ms SLA? Split fraud defense into three latency tiers so only sub-millisecond RAM lookups touch the hot path. Tier 1 (pre-bid, < 0.5 ms in process RAM): reject known data-center/proxy IP ranges, bot user-agents, unauthorized (app_bundle, publisher_id) pairs via cached app-ads.txt / sellers.json tables, mismatched device claims (such as a Smart TV bundle sending a mobile browser header), and per-IP / per-device QPS bursts tracked via a tiny in-memory Count-Min Sketch. Tier 2 (near-real-time, ~30–60 s lag): a streaming job over Kafka auction and impression logs scores 1-to-15-minute behavioral windows (such as unnatural 100% ad-completion rates or one IP cycling thousands of fake device IDs) and pushes updated blocklists to every node's RAM snapshot every 30 seconds. Tier 3 (post-bid pre-billing, hourly/daily): graph clustering catches sophisticated SSAI (Server-Side Ad Insertion) spoofing rings and strips flagged IVT (Invalid Traffic) impressions before the PostgreSQL billing ledger invoices advertisers.

Follow-up questions

Similar questions

More Roku interview questions

All 8 Roku questions →