Low-Latency Ad Serving Platform with A/B Experimentation

Medium · System Design · Software Engineer · Technical Screen

Prompt

Design a real-time ad selection and delivery platform with built-in A/B experimentation. Web pages and mobile apps request ads for specific UI slots (such as top banners or sidebar cards), and the backend must filter eligible campaigns, rank candidate creatives, and return rendering metadata plus tracking endpoints within tens of milliseconds across millions to hundreds of millions of daily requests.

Your design should support the following core capabilities and operational guarantees:

  • Campaign & creative onboarding: Manage advertiser flight windows, daily/lifetime budgets, pricing bids, and creative asset metadata.
  • Contextual & audience targeting: Filter eligible ads by country, device class, placement slot, and optional consent-gated user segments.
  • Ad selection & delivery guardrails: Rank eligible creatives per placement while enforcing budget pacing, per-user frequency caps, and deduplication across slots and retried beacons.
  • Event telemetry: Record rendered impressions and user clicks reliably.
  • Online experimentation: Deterministically bucket users into concurrent experiments modifying ranking logic, pacing rules, or creative rotation; record exposures and outcomes; and protect live traffic with automated guardrails.
  • Latency, availability & reporting accuracy: Serve ad decisions in tens of milliseconds without ever stalling host app rendering on failures, and clearly separate fast approximate operational counters from exact billing and statistical reporting.

Scope & Expectations

  • System architecture & storage layout: Specify control-plane databases, in-memory serving snapshots/caches, low-latency user state stores, and high-volume event streaming and analytical storage.
  • Sub-50 ms decision flow & caching: Walk through request -> targeting -> pacing/frequency-cap filtering -> ranking -> response, detailing what belongs in CDN or server RAM versus what must never be cached.
  • Telemetry pipeline & reconciliation: Contrast near-real-time streaming metrics (budget pacing, live dashboards, safety guardrails) against deduplicated, bot-filtered batch accounting for advertiser invoices.
  • Experimentation rigor & graceful degradation: Cover deterministic orthogonal layer hashing, unbiased exposure logging, shared-budget interference across test arms, statistical validation, and fallback behavior under dependency outages.

Step-by-step walkthrough

  1. Clarify requirements, core terms, and scope

    An ad request sits on the critical rendering path of a host app or website, so our server must decide in tens of milliseconds, and the host app must never hang or crash if ads fail. At the same time, real money and scientific conclusions depend on our logs: advertiser budgets, billing invoices, and A/B test readouts all flow from impression and click events.

    Start by defining four core ad-serving terms simply and locking down scope with the interviewer:

    • Placement: A specific ad slot on a screen (such as home_banner_top at 728x90 pixels).
    • Creative: The actual ad asset metadata (image/video URL, dimensions, and destination click URL) belonging to an advertiser's campaign.
    • CPM (Cost Per Mille) vs. CPC (Cost Per Click): Pricing models where the advertiser pays either per 1,000 rendered impressions (CPM) or per user click (CPC).
    • Pacing and Frequency Capping: Delivery controls ensuring a campaign spends its daily budget smoothly across the day (pacing) and does not show the same ad to the same person too many times (frequency capping, e.g., <= 3 views per 24 hours).

    Functional requirements

    • Campaign & creative management: Ad operations create campaigns (flight dates, daily/lifetime budget, CPM/CPC bid, targeting rules, frequency cap) and upload creatives.
    • Targeting: Filter eligible campaigns by country, device_type, placement_id, and (when the user has granted privacy consent) user_segments (e.g., "sports_fans", excluding "existing_subscribers").
    • Real-time ad selection: Choose the highest-value eligible creative per requested placement, deduplicating across multiple placements on the same page.
    • Tracking: Record rendered impressions and clicks reliably.
    • A/B experimentation: Deterministically assign users into mutually exclusive or orthogonal experiments (testing ranking models, pacing formulas, or creatives), log exposures and outcomes, and enforce real-time safety guardrails.

    Clarifying assumptions agreed up front

    • Direct-sold inventory (no external RTB exchanges): All campaigns live in our own system (no 100 ms external Real-Time Bidding fan-out to third-party ad exchanges).
    • User identity & privacy: Use user_id when signed in, falling back to app/browser device_id. Without personalized_ads consent, segment targeting is disabled and only contextual rules (country, device, placement) apply.
    • Billable impression definition: An impression counts only when the client actually renders the creative and fires the impression beacon — never merely when the server returns a decision.
    • Real-time vs. batch accuracy: Pacing, frequency caps, and experiment safety guardrails update within seconds to 1 minute (approximate); advertiser invoices and final experiment statistics run daily (exact, deduplicated, bot-filtered).

    Non-functional targets

    • Latency: Server-side ad decision p99 <= 50 ms; client SDK enforces a 300 ms hard timeout and collapses the slot cleanly on timeout.
    • Throughput & availability: Design for 50,000 placement requests/s at 99.9%+ availability.
    • Budget accuracy: Keep daily campaign overspend < 0.1%.
  2. Back-of-the-envelope numbers

    Derive memory, storage, network QPS, and fleet size from first principles:

    1. Traffic & funnel
       Placement requests/day:     500,000,000  (a page with 2 slots sends 1 batched HTTP call for 2 placements)
       Request rate:               500M / 86,400 s = ~5,800/s average, ~23,000/s prime-time peak (4x)
                                   ==> Provision serving fleet for 50,000 placements/s
       Fill rate (80%):            400M ads served/day (~360M–390M rendered impressions/day)
       CTR (Click-Through Rate, 0.2%): 400M x 0.002 = ~800,000 clicks/day
    
    2. Campaign & experiment snapshot size (in RAM on EVERY ad server!)
       Active campaigns:           20,000 x ~2 KB (targeting, bid, caps, pacing)  = ~40 MB
       Approved creatives:        100,000 x ~0.5 KB (dimensions, CDN URL, landing)= ~50 MB
       Experiment layers/configs:    ~200 x ~2 KB                                 = < 1 MB
       Total serving snapshot:                                                    = ~90 MB RAM!
    
    3. Regional User Store (segments + sliding-window frequency caps)
       Monthly active users:      100,000,000
       Per user: ~50 segment IDs (200 B) + ~20 capped campaign timestamp lists (320 B) + overhead ≈ 1 KB
       Total RAM/SSD per region:  100M x 1 KB = ~100 GB per region (<= 23,000 batched reads/s at peak)
    
    4. Event pipeline volume
       Decision logs:             500M/day x ~1.0 KB = ~500 GB/day
       Impression beacons:        400M/day x ~0.5 KB = ~200 GB/day
       Click beacons:             0.8M/day x ~0.5 KB = ~0.4 GB/day
       Total raw stream:          ~700 GB/day (~41,500 events/s, ~32 MB/s at peak into Kafka)
       7-day Kafka retention (3x replication): 700 GB x 7 x 3 ≈ 15 TB disk across brokers
    
    5. Stateless ad-server fleet
       At ~2,000 placements/s per server -> 25 servers minimum for 50,000/s
       Deploy 14 servers x 3 regions = 42 servers (even if 1 entire region fails, 28 servers = 56,000/s!)
    

    Three architectural insights fall straight out of this math:

    • 90 MB fits inside every server's RAM: We never query a campaign database or remote targeting cache on an ad request! Every ad server keeps the entire ~90 MB active snapshot in local memory, leaving just one in-region network call (reading the 1 KB user record).
    • Events (700 GB/day) dwarf campaign state (90 MB): PostgreSQL easily handles campaign CRUD, while impressions and decisions belong in a partitioned Kafka log + columnar data lake.
    • Per-campaign spend/s is small enough for asynchronous pacing: Even a large campaign spends pennies per second, so adjusting a local serve probability every 10 seconds keeps overspend well below 0.1% without locking a global counter on every request.
  3. API design

    Batch all placements on a screen into a single request, and embed signed metadata inside tracking URLs so impression/click collectors stay completely stateless.

    1. Client SDK -> Ad Server
    POST /v1/ad-requests
      Body: {
        "request_id": "req_91a2",
        "page_view_id": "pv_81f",
        "placements": [
          {"placement_id": "home_banner_top", "sizes": ["728x90", "320x50"]},
          {"placement_id": "home_tile_side",  "sizes": ["300x250"]}
        ],
        "user": {"user_id": "u_123", "device_id": "d_9a1"},
        "context": {"app": "ios", "device_type": "phone"},   // country derived from edge IP geo-lookup
        "consent": {"personalized_ads": true}
      }
      200 OK: {
        "ads": [{
          "placement_id": "home_banner_top",
          "impression_id": "imp_4c2e",
          "creative": {
            "creative_id": "cr_77", "format": "image", "width": 728, "height": 90,
            "asset_url": "https://cdn.example/creatives/cr_77_3f9a.webp"
          },
          "impression_url": "https://track.example/v1/i?t=<hmac_signed_token>",
          "click_url":      "https://track.example/v1/c?t=<hmac_signed_token>"
        }],
        "ttl_ms": 60000
      }
      204 No Content: (no eligible ad — SDK cleanly hides empty slot)
    
    2. Client SDK -> Stateless Tracking Collectors
    GET  /v1/i?t=<hmac_signed_token>       Logs rendered impression -> 204 No Content (also POST /v1/i:batch)
    GET  /v1/c?t=<hmac_signed_token>       Logs click -> 302 Redirect to creative's stored landing_url
    
    3. Control Plane (Ad Ops & Experimentation)
    POST   /v1/campaigns                   Create campaign (dates, budget, CPM/CPC bid, targeting, freq_cap)
    PATCH  /v1/campaigns/{id}              Optimistic update via If-Match: <version>
    POST   /v1/campaigns/{id}/creatives    Upload asset -> moderation -> CDN content-hashed URL
    POST   /v1/experiments                 Define layer, bucket ranges, variant params, guardrail thresholds
    POST   /v1/experiments/{id}:stop       Emergency kill switch -> pushes config delta in seconds
    

    Why each endpoint is designed this way:

    • One batched call per screen: Fetching home_banner_top and home_tile_side together cuts client round trips and User Store reads in half, and lets the server guarantee the same campaign never appears twice on one screen.
    • HMAC-signed tracking tokens: An HMAC (Hash-based Message Authentication Code) is a cryptographic signature computed with a secret server key so clients cannot forge or tamper with the token's payload (impression_id, request_id, campaign_id, creative_id, price_micros, serve_ts, user_key, and experiment_variants). Tracking collectors verify the signature in microseconds and write straight to Kafka with zero database lookups, and clicks/impressions already carry their exact experiment variant!
    • Safe click redirects: GET /v1/c looks up landing_url from creative_id (or reads it from inside the HMAC-signed token), never from an unsigned ?redirect=https://evil.site query parameter (which would create an open-redirect phishing vulnerability).
  4. Data model and storage choices

    Split storage cleanly across four workloads: transactional config, in-memory serving snapshots, low-latency user state, and high-volume event logs.

    1. Control Plane: PostgreSQL (low QPS, strict relational integrity and optimistic locking):

    campaigns     id PK, advertiser_id, status (ACTIVE|PAUSED|ENDED), start_at, end_at,
                  budget_daily_micros, budget_total_micros, pricing (CPM|CPC), bid_micros,
                  pacing_mode (EVEN|ASAP), freq_cap_count, freq_cap_window_s, priority_tier, version
    targeting     campaign_id PK, countries[], device_types[], placement_ids[],
                  segments_include[], segments_exclude[]
    creatives     id PK, campaign_id, format, width, height, asset_url, landing_url, status, weight
    layers        id PK, name (ranking | creative | ad_load), hash_salt
    experiments   id PK, layer_id, status, start_at, end_at, guardrails JSONB
    variants      experiment_id, name (control | treatment_a), bucket_start, bucket_end, params JSONB
    

    (Prices and budgets use integer micros — units of $0.000001 — so $10.00 CPM is 10_000_000 micros and $0.01 per impression is 10_000 micros, avoiding floating-point rounding bugs.)

    2. In-memory Serving Snapshot (~90 MB immutable blob + fast Kafka deltas): Every 60 seconds, a Snapshot Builder compiles active PostgreSQL rows + current pacing probabilities into an indexed binary snapshot on S3 (keyed by placement_id -> inverted bitsets for country/device -> candidate campaigns). Urgent actions (campaign paused, daily budget hit, experiment auto-stopped) also publish tiny messages on a config-deltas Kafka topic consumed by all ad servers within 1–2 seconds.

    3. Regional User Store: Redis Cluster or Aerospike (sharded by user_key, replicated per region):

    user:{user_key} -> {
      segments: [1032, 88, 419],                  // refreshed daily/hourly by data platform
      fc: { "camp_55": [1732981012, 1732989400] } // last N serve timestamps per frequency-capped campaign
    }
    

    Storing only the last freq_cap_count timestamps per campaign enforces an exact sliding window (e.g., "at most 3 serves in the past 86,400 seconds") in a few hundred bytes!

    4. Event logs: Kafka (Protobuf) -> S3 Parquet Data Lake + ClickHouse/Druid OLAP: - ad-decisions (partitioned by request_id), ad-impressions and ad-clicks (both partitioned by impression_id so duplicate beacons for the same impression always hit the exact same stream processor task!). - OLAP store (ClickHouse or Apache Druid — a column-oriented analytical database built for sub-second GROUP BY queries over billions of rows) powers near-real-time ops and advertiser dashboards, while hourly Parquet files on S3 power exact daily Spark billing and experiment readouts.

  5. High-level architecture

     CONTROL PLANE
     Ad Ops / Exp UI ─► Campaign & Exp API ─► PostgreSQL ─► Snapshot Builder ─► S3 (full 90 MB, every 60s)
                                                  └───────────────────────────► Kafka: config-deltas (1-2s)
     Creative Upload ─► Malware/Policy Scan ─► Object Store ─► Global CDN (immutable content-hashed URLs)
    
     REAL-TIME SERVING PLANE (deployed in 3 active regions)
     Client SDK ──► GeoDNS / ALB ──► Stateless Ad Server (90 MB snapshot + pacing map in local RAM)
         │                              ├── 1. Read user:{key} (5 ms timeout) ──► Regional User Store
         │                              ├── 2. Hash user_key -> experiment variants (local CPU, < 0.05 ms)
         │                              ├── 3. Filter, pace, rank & mint HMAC URLs (local CPU, ~3-5 ms)
         │                              ├── 4. Async append serve timestamp ────► Regional User Store
         │                              └── 5. Async emit decision + exposures ─► Kafka (ad-decisions)
         ├──► Global CDN (fetches cached creative image/video)
         └──► Stateless Tracking Collectors (verify HMAC) ──────────────────────► Kafka (impressions, clicks)
    
     STREAMING & BATCH EVENT PIPELINE
     Kafka ──┬─► Apache Flink (24h impression_id dedup, 10s campaign spend, 1m variant guardrails)
             │       ├──► Pacing Controller (updates serve probabilities every 10s + stop deltas)
             │       └──► Experiment Guardrail Service (auto-stops broken variants via config-deltas)
             ├─► ClickHouse / Druid (near-real-time ops & "preliminary" advertiser reporting)
             └─► S3 Data Lake (Parquet) ──► Daily Spark Batch (IVT bot filter, exact invoices, A/B stats)
    

    End-to-end flow of one request: 1. Client SDK calls POST /v1/ad-requests with all placements on the screen. 2. Ad server reads user:{key} from the regional User Store (~2 ms), computes experiment variants locally, filters and scores candidates from its 90 MB in-memory snapshot, and returns creative metadata + HMAC tracking URLs in ~12 ms. 3. Ad server asynchronously records the serve timestamp in the User Store and logs the decision event (including active experiment exposures) to Kafka. 4. Client SDK downloads the creative image from the CDN and, once ≥50% of pixels render on screen, fires impression_url to a Tracking Collector. 5. Flink deduplicates beacons to update 10-second pacing probabilities and 1-minute experiment guardrails; nightly Spark computes exact advertiser bills and A/B test p-values.

  6. Deep dive 1: sub-50 ms serving path, ranking, and caching

    Server-side latency budget (p99 <= 50 ms):

    Load balancer + TLS termination + JSON/Protobuf parse:   ~2.0 ms
    In-region User Store read (typical 1–2 ms, hard cap):    <= 5.0 ms
    Deterministic experiment hashing (SHA-256 per layer):    ~0.1 ms
    In-memory candidate lookup + targeting/cap/pacing check: ~1.5 ms
    Ranking (eCPM scoring across ~20–50 eligible ads):       ~2.0 ms
    Response serialization + HMAC token signing:             ~1.0 ms
    ------------------------------------------------------------------
    Typical total: ~8–12 ms (leaves ~38 ms headroom for GC/network tail inside 50 ms p99!)
    

    To avoid garbage-collection or lock stalls during 60-second snapshot refreshes, a background thread deserializes the new ~90 MB snapshot off to the side and performs an atomic pointer swap (current_snapshot = new_snapshot); in-flight requests finish cleanly on the previous snapshot reference.

    Selection & ranking logic across all placements on a page:

    def select_ad_for_placement(placement, req, user, snapshot, variant, rng, used_campaigns):
        """Pick the highest-scoring eligible (campaign, creative) for one slot, or None."""
        # Respect privacy consent: never use behavioral segments if personalized_ads is False.
        allow_segments = req.personalized_ads
        best_pair = None
        best_score = -1.0
    
        candidates = snapshot.lookup(placement.id, req.country, req.device_type)
        for campaign in candidates:
            # 1. Page-level deduplication: never show the same campaign twice on one screen.
            if campaign.id in used_campaigns:
                continue
            if not campaign.is_live(req.now_ts):
                continue
    
            # 2. Segment targeting (inclusion AND exclusion) gated by user privacy consent.
            if campaign.segments_include:
                if not allow_segments or not user.has_any_segment(campaign.segments_include):
                    continue
            if campaign.segments_exclude and allow_segments:
                if user.has_any_segment(campaign.segments_exclude):
                    continue
    
            # 3. Probabilistic budget pacing throttle in (0.0, 1.0].
            if rng.random() >= snapshot.serve_probability(campaign.id):
                continue
    
            # 4. Sliding-window frequency cap check on user's recent serve timestamps.
            if campaign.freq_cap_count is not None:
                recent = user.count_serves_since(campaign.id, req.now_ts - campaign.freq_cap_window_s)
                if recent >= campaign.freq_cap_count:
                    continue
    
            # 5. Pick a size-matching creative (deterministic per user if running a creative A/B test).
            creative = campaign.pick_creative(placement.sizes, variant, user.key)
            if creative is None:
                continue
    
            score = variant.score(campaign, creative, req)
            if score > best_score:
                best_score = score
                best_pair = (campaign, creative)
    
        return best_pair
    
    
    def select_ads_for_page(req, user, snapshot, variant, rng):
        """Select deduplicated ads across all placements requested on a single screen."""
        used_campaigns = set()
        chosen = []
        for placement in req.placements:
            match = select_ad_for_placement(placement, req, user, snapshot, variant, rng, used_campaigns)
            if match is not None:
                campaign, creative = match
                used_campaigns.add(campaign.id)
                chosen.append((placement.id, campaign, creative))
        return chosen
    

    How variant.score ranks CPM and CPC ads on a single scale: Higher contractual priority_tier (e.g., guaranteed sponsorship deals over open auction) adds a large tier offset, and within a tier we rank by eCPM (effective Cost Per Mille) — expected revenue per 1,000 impressions:

    CPM campaign:   eCPM = bid_cpm
    CPC campaign:   eCPM = bid_cpc x predicted_CTR x 1,000
    

    predicted_CTR comes from a compact logistic-regression or shallow GBDT model bundled inside the snapshot, scoring (placement, creative, device_type, hour_of_day, user_segments) in < 2 ms.

    Caching strategy (what to cache and what never to cache): - Campaigns, targeting, experiments: Cached 100% in ad-server RAM (~90 MB), refreshed every 60 s + 1–2 s Kafka deltas. - Creative image/video files: Cached globally at the CDN for 1 year using immutable content-hashed URLs (cr_77_3f9a.webp). - Ad decision JSON (POST /v1/ad-requests): Never cached at the CDN, because eligibility depends on per-user frequency caps, live pacing, and experiment variants. Clients may prefetch an ad up to ttl_ms = 60000 ahead of scroll, firing the impression beacon only if rendered.

  7. Deep dive 2: pacing, budgets, frequency capping, and deduplication

    1. Probabilistic pacing and bounding daily overspend (< 0.1%): Why not run an atomic DECRBY in Redis on every ad request? A synchronous cross-region counter adds network latency to every single request and deducts money on serves rather than rendered impressions. Instead, Flink sums deduplicated rendered spend every 10 seconds, compares each campaign's spend rate against an hourly traffic-shaped target curve, and updates its serve probability p (0 < p <= 1):

    p_next = clamp(p_current x target_spend_rate / max(actual_spend_rate, epsilon), p_min, 1.0)
    

    Ad servers pull the tiny ~240 KB probability map (20,000 campaigns x 12 bytes) every 10 seconds and evaluate rng.random() < p in nanoseconds. Let's check worst-case overspend on a $10,000/day campaign at $10 CPM ($0.01 per impression -> 1,000,000 impressions/day):

    Daily average rate:      1,000,000 / 86,400 s                     = ~11.6 impressions/s
    4x prime-time peak rate: 11.6 x 4                                 = ~46.3 impressions/s
    End-to-end stop delay:   beacon -> Kafka -> 10s Flink -> delta    = ~15 seconds
    Unstopped impressions:   46.3/s x 15 s                            = ~695 impressions
    Worst-case overspend:    695 x $0.01                              = ~$6.95  (0.07% of $10,000!)
    

    Notice the share (4 x 15 / 86,400 ≈ 0.07%) is independent of budget size! One subtle trap to guard against: client prefetch (ttl_ms = 60 s). If Flink waited purely for rendered beacons, up to 60 seconds of prefetched ads could still be sitting on phones waiting to render (4 x (60 + 15) / 86,400 = 0.35%, breaching 0.1%). To keep stop latency at ~15 s, Flink tracks committed spend = rendered_spend + (unexpired_prefetched_decisions x placement_render_rate), tapering p down as remaining budget approaches 15 seconds of spend and pushing an instant stop flag via config-deltas at 100% (advertisers are never billed above their cap).

    2. Sliding-window frequency capping: Ad servers check fc[campaign_id] during the initial 2 ms User Store read and asynchronously append now_ts (trimming list length to freq_cap_count) after returning the response. Counting serves slightly under-exposes users whose ad never scrolled into view (safe for advertisers), and two simultaneous requests from the exact same user within 5 ms can occasionally serve cap + 1 (eliminating that rare +1 race would require a slower synchronous compare-and-swap write, reserved only for strict contractual caps).

    3. Three-tier deduplication: - Page level: used_campaigns prevents two slots on one page from showing the same campaign. - Stream level (near-real-time pacing/dashboards): Mobile SDK retries can fire an impression beacon twice. Flink partitions ad-impressions by impression_id and keeps a 24-hour RocksDB deduplication set (400M IDs x ~50 B ≈ 20 GB distributed across tasks), dropping duplicates before summing spend. - Batch level (exact billing): Nightly Spark deduplicates across a full 48-hour window on S3 before generating invoices.

  8. Deep dive 3: A/B testing — orthogonal layers, exposure logging, and budget interference

    1. Stateless deterministic assignment with orthogonal layers: How do we run a ranking model test, a creative rotation test, and an ad-load test at the same time without experiments corrupting each other? Group mutually exclusive experiments into layers (ranking, creative, ad_load), giving each layer 1,000 hash buckets (0..999) and its own secret salt (a unique string mixed into the hash input): - Two ranking experiments take disjoint bucket slices in the ranking layer (e.g., Exp 1 gets 0..199, Exp 2 gets 200..399), so one user never gets two conflicting ranking models. - Because ranking and ad_load use different salts, a user's bucket in ranking is statistically independent of their bucket in ad_load, allowing full traffic reuse across layers!

    import hashlib
    
    
    def compute_bucket(layer_salt, unit_id, num_buckets=1000):
        """Map (layer_salt, unit_id) deterministically to [0, num_buckets) across all languages/servers."""
        payload = f"{layer_salt}:{unit_id}".encode("utf-8")
        digest = hashlib.sha256(payload).digest()
        return int.from_bytes(digest[:8], "big") % num_buckets
    
    
    def assign_variant(layer_config, unit_id):
        """Return (experiment_id, variant_name) for unit_id in this layer, or (None, None)."""
        if not unit_id:
            return None, None
        b = compute_bucket(layer_config["hash_salt"], unit_id)
        for exp in layer_config["experiments"]:
            for variant in exp["variants"]:
                if variant["bucket_start"] <= b < variant["bucket_end"]:
                    return exp["id"], variant["name"]
        return None, None
    

    (Never use Python's built-in hash(), which randomizes its seed on every process restart! Always use a fixed cryptographic or cross-platform hash like SHA-256 or MurmurHash3.)

    2. Counterfactual exposure logging (avoiding dilution and selection bias): Logging an exposure on every request dilutes results whenever 0 or 1 campaign is eligible (where every ranking formula picks the exact same answer). Instead, log an exposure on ad-decisions only when the experiment's code path actually differed or could differ (e.g., >= 2 eligible candidates for a ranking test), obeying two strict statistical rules: 1. Evaluate the exact same eligibility trigger in both Control and Treatment. 2. Once a user has their first valid exposure, include all subsequent requests from that user in the readout (because Treatment's choices alter that user's frequency-cap history on later requests, filtering request-by-request after exposure would introduce post-treatment selection bias!).

    3. Solving the ad-tech trap: shared-budget cannibalization across arms: Suppose Treatment's new CTR model bids more aggressively on high-paying Campaign X ($10,000/day budget). If Control (50%) and Treatment (50%) draw from the same $10,000 pot, Treatment spends $7,000 of Campaign X by 2 PM, Campaign X shuts off early, and Control loses access to Campaign X all evening — making Treatment look artificially profitable by stealing Control's inventory! - Fix for ranking/pacing experiments: Enable traffic-proportional budget splitting — give Control its own isolated $5,000 pacing pool and Treatment its own $5,000 pacing pool for each campaign, paced independently!

    4. Statistical readout, Sample Ratio Mismatch (SRM), and automated guardrails: - SRM check first: Run a chi-square test comparing observed exposed user counts (N_control, N_treatment) against expected bucket weights (50/50); if p < 0.001, block the dashboard immediately (a client crash, timeout, or logging bug broke randomization). - Variance estimation: CTR (total_clicks / total_impressions) is a ratio of sums where multiple impressions come from the same user (violating independence). Compute confidence intervals using the delta method (user-level clustered variance of clicks and impressions) plus CUPED (subtracting pre-experiment user baseline revenue/CTR to cut variance). - Sample size: At baseline CTR = 0.2% (p = 0.002), detecting a 5% relative lift (delta = 0.0001) at 80% power (2 x (1.96 + 0.84)^2 ≈ 16) needs n ≈ 16 x 0.002 x 0.998 / (0.0001)^2 ≈ 3.2M independent impressions per arm (~5M–6M accounting for intra-user correlation) — easily reached in hours on a 10% arm (~40M impressions/day), though we always run >= 7 full days to capture weekday/weekend cycles. - 1-minute Flink guardrails: Flink tracks per-variant p99 latency, error rate, fill rate, and revenue per 1,000 requests (RPM). Any sustained 15-minute guardrail breach triggers POST /v1/experiments/{id}:stop, zeroing traffic via config-deltas in ~2 seconds.

  9. Event pipeline, reporting tiers, and failure modes

    Separate fast operational approximations from exact financial and scientific accounting:

    Consumer / Use case              Freshness    Engine & source                    Guarantee
    -------------------------------  -----------  ---------------------------------  -----------------------------------
    Frequency capping                ~1–5 ms      Regional User Store (serve ts)     Best-effort (+1 max on parallel tab)
    Budget pacing probabilities      ~10–15 s     Flink (24h RocksDB dedup)          Approximate (< 0.1% overspend)
    Experiment safety guardrails     ~1 min       Flink per-variant metrics          Approximate (auto-kill on breach)
    Live Advertiser / Ops UI         ~1–5 min     ClickHouse / Druid OLAP            Labeled "Preliminary (unfiltered)"
    Invoices, payouts & A/B readout  Daily T+1    Spark on S3 Parquet Data Lake      Exact (48h dedup + IVT bot filter)
    

    Key pipeline details: - Untrusted client clocks: Mobile devices go offline on airplanes and upload queued beacons hours later with skewed device clocks. Billing assigns every impression to a calendar day using serve_ts inside the HMAC-signed token (allowing up to a 24-hour late-arrival watermark — a cutoff waiting period for delayed mobile uploads — before closing and freezing the previous day's ledger) and runs Invalid Traffic (IVT) filters to strip data-center bots and click farms.

    Failure modes and graceful degradation: - Regional User Store slow or unreachable (> 5 ms timeout): Ad server catches the timeout at 5 ms and filters only eligible contextual, non-frequency-capped campaigns. Fill rate dips briefly, latency stays < 20 ms, and contractual frequency caps are never violated. - Pacing Controller or Flink lag: Ad servers keep last known p values for 2 minutes, then exponentially decay p on campaigns near budget exhaustion — choosing safe slight under-delivery over unbilled overspend. - Kafka cluster outage: Stateless Tracking Collectors spool verified beacons to local NVMe disk (18,000 beacons/s x 0.5 KB x 3,600 s ≈ 32 GB/hour across the collector fleet — zero lost billing revenue!) and replay once brokers recover. Ad servers buffer decision logs in a bounded ring buffer and increment a drop metric so experiment analysts exclude any window with missing exposure logs. - Full region outage or client network stall: GeoDNS routes traffic to the two healthy regions (sized at 56,000 QPS > 50,000 peak), while the mobile/web SDK's 300 ms timeout ensures an ad incident degrades silently to an ad-free screen rather than a broken app.

Intuition & how it works

Think of a real-time ad-serving and experimentation platform like an airport display board driven by a tiny pocket rulebook in RAM, a single 2-millisecond traveler pass check, and tamper-proof receipt stubs tallied every 10 seconds in the back office. Because the entire catalog of 20,000 active ad campaigns, targeting rules, and 100,000 banner metadata records totals only ~90 MB, every stateless ad server keeps a full copy right in local memory. When an app opens a page, the server makes just one in-region lookup (~2 ms) for that user's audience segments and recent ad views, runs a fast SHA-256 hash to assign A/B test variants locally in microseconds, scores eligible ads by expected revenue, and returns creative metadata plus HMAC-signed tracking URLs (cryptographically signed URLs carrying the impression ID, price, timestamp, and experiment variants so clients cannot forge or alter them). Off the critical path, a streaming job counts rendered receipt beacons every 10 seconds and tunes each campaign's pacing probability (a 0.0 to 1.0 throttle) so daily budgets spend smoothly without ever locking a global database counter during a page load.

Why do obvious, naive designs break immediately at scale? Querying a relational database for campaign targeting or incrementing a centralized global budget counter on every ad request adds cross-region network round trips that blow past a 50 ms latency budget and turn database hiccups into frozen app screens. Charging advertisers the moment the server picks an ad overbills them whenever a user closes the app or fails to scroll down to the banner. And running a ranking A/B test where Control and Treatment spend from the same shared campaign budgets lets an aggressive Treatment model drain top-paying campaigns by early afternoon, starving Control later in the day and creating an illusory revenue "lift."

Trace a concrete 4-step lifecycle for user u_123 opening a home screen with two slots (home_banner_top and home_tile_side):

1. Single batched request arrives (server p99 budget <= 50 ms):
   - Ad server reads user:{u_123} in 2 ms -> segments=[1032], fc={"camp_A": [t1, t2, t3]} (cap=3/24h!).
   - Local SHA-256("ranking_salt:u_123") % 1000 -> bucket 142 -> assigns (exp_rank_7, "treatment").

2. In-memory filtering, deduplication & eCPM ranking (~5 ms):
   - Slot 1 (home_banner_top): camp_A fails 3/24h frequency cap; camp_B ($8 CPM) and camp_C ($2 CPC x
     0.5% predicted CTR x 1000 = $10 eCPM) both pass pacing coin flips -> camp_C wins!
   - Slot 2 (home_tile_side): camp_C is skipped via used_campaigns (no duplicate campaign on one screen)
     -> camp_B wins! (>= 2 candidates existed, so exposure to exp_rank_7 is logged on the decision).

3. Client render & stateless tracking:
   - App renders Slot 1 (camp_C) and fires GET /v1/i?t=<hmac_token>; user never scrolls to Slot 2.
   - Collector verifies HMAC signature in microseconds and appends ONLY camp_C's impression to Kafka.

4. 10-second pacing & daily reconciliation:
   - Flink deduplicates impression_id, adds $0.00 (CPC waits for click) or CPM spend to camp_C's
     treatment-arm budget slice, and updates camp_C's serve probability p for the next 10s window.

Key trade-offs

  • Full ~90 MB in-memory snapshot vs. per-request database/cache queries. Replicating all active campaigns, targeting bitsets, and experiment configs into every ad server's RAM requires a 60-second Snapshot Builder plus a config-deltas Kafka topic for urgent pauses, and means non-urgent edits take up to a minute to propagate. In exchange, candidate lookup and filtering take ~1.5 ms on local CPU with zero database load at 50,000 QPS.
  • Asynchronous probabilistic pacing vs. synchronous atomic budget counters. Updating a local 0..1 serve probability every 10 seconds from rendered impressions keeps serving region-local and fast, at the cost of a tiny bounded overspend during the ~15-second feedback loop (~$6.95, or 0.07% on a $10,000 daily budget at 4x prime-time traffic, provided prefetched unexpired ads are counted as committed spend). A synchronous cross-region counter prevents overspend completely, but adds tens of milliseconds to every decision and wrongly deducts budget for unrendered ads.
  • Serve-time frequency-cap recording vs. impression-time recording. Appending timestamps asynchronously right after an ad decision uses one regional writer and protects users loading back-to-back screens a second apart. It occasionally counts an unrendered ad against a user's cap and can overshoot by +1 on two simultaneous millisecond-level requests, whereas waiting for rendered beacons avoids under-delivery on unrendered slots but leaves a multi-second blind spot during rapid browsing.
  • Two-speed lambda/lakehouse reporting (approximate stream vs. exact daily batch). Using Apache Flink + an OLAP store (a column-oriented analytical database like ClickHouse or Druid) delivers 10-second pacing, 1-minute experiment guardrails, and 5-minute "preliminary" dashboards, while nightly Spark jobs over S3 Parquet apply 48-hour deduplication, 24-hour late-event watermarks (a cutoff window for offline mobile beacons), and Invalid Traffic (IVT) bot filtering to produce exact legal invoices and A/B test readouts.
  • Stateless hash-bucket assignment with orthogonal layers vs. database-stored assignments. Computing SHA-256(layer_salt + ":" + user_key) % 1000 guarantees identical, zero-latency variant assignment across every server and region while letting independent layers (ranking, creative, ad_load) run concurrently. The trade-off is that requests lacking any persistent user_id or device_id must stay out of user-level experiments rather than polluting variants with random per-request IDs.
  • Counterfactual exposure logging vs. assignment-time logging. Logging exposure only on requests where >= 2 eligible candidates competed strips out noise from single-candidate or zero-fill requests, boosting statistical power. It requires evaluating the exact same trigger in Control and aggregating all user events from first exposure onward so variant-driven frequency-cap differences cannot bias which later requests get counted.
  • Arm-split campaign budgets vs. shared campaign budgets in ranking A/B tests. Splitting each campaign's daily budget proportionally across Control and Treatment prevents an aggressive variant from cannibalizing shared budget and starving Control, at the cost of multiplying pacing state per active ranking experiment and adding slight pacing variance on tiny campaigns.

Common mistakes

  • Querying PostgreSQL or a remote cache per campaign during ad selection. Even 3 sequential network calls blow half of a 50 ms p99 budget; keep the 90 MB campaign snapshot in process memory.
  • Caching POST /v1/ad-requests responses at the CDN. Only static creative images/videos belong on the CDN; caching decision responses serves one user's personalized ad, frequency-cap state, and tracking token to thousands of strangers!
  • Billing advertisers on server decisions instead of client-rendered beacons. Network drops, fast scrolling, and prefetched screens mean ~5–20% of served decisions never render; billing on decisions breaks industry standards and overcharges advertisers.
  • Ignoring privacy consent or segments_exclude in targeting. Using behavioral segments when personalized_ads == false violates privacy regulations, and forgetting exclusion segments wastes advertiser spend showing acquisition promos to existing paying subscribers.
  • Using a language's randomized runtime hash() (or sharing one salt across all layers). Python randomizes hash() seeds per process (flipping a user between Control and Treatment on every refresh!), and reusing a single salt across layers couples experiments so Treatment A in Layer 1 always lands in Treatment A in Layer 2.
  • Using a naive independent-binomial z-test on impression-level CTR. Because one heavy user generates dozens of correlated impressions, treating impressions as independent severely underestimates variance and causes rampant false positives; aggregate per user and apply the delta method (a formula for the variance of a ratio of correlated per-user sums).
  • Skipping Sample Ratio Mismatch (SRM) checks or shared-budget splitting. Reading lift numbers when variant user counts deviate from 50/50 (SRM p < 0.001) or when Treatment drained Control's shared campaign budgets leads teams to ship broken or cannibalistic models.
  • Passing raw destination URLs (?url=https://...) on click trackers. Attackers will abuse /v1/c?url=https://phishing.example under your trusted domain; always resolve landing_url from creative_id or verify an HMAC signature.

Follow-up questions

  • How would you upgrade ranking to a deep-learning CTR prediction model without breaking the 50 ms p99 latency budget? Split model computation into a heavy offline/nearline user encoder and a tiny in-process scoring head (two-tower or distilled GBDT/MLP architecture). Precompute dense user embeddings (~64 floats = 256 bytes) asynchronously from browsing history and store them right inside the existing user:{key} record (adding zero extra network calls!), precompute campaign/creative embeddings inside the 60-second 90 MB snapshot, and evaluate a lightweight dot-product or 2-layer MLP cross-network over the ~30 post-filter candidates on local CPU SIMD instructions in ~2–3 ms — shipping the new scorer behind the ranking experiment layer with p99 latency and RPM guardrails.
  • How should the system handle logged-out, privacy-restricted requests that carry neither a user ID nor a device ID? Never invent a random per-request UUID for hashing, because that flips the same human between Control and Treatment across page views and invalidates user-level metrics and frequency caps. Instead, exclude ID-less requests from user-level experiment exposures (serving the default production model), disable behavioral segment targeting, and mark strict frequency-capped campaigns ineligible so only contextual, uncapped campaigns compete. If browser first-party session cookies are permitted for 30 minutes, you can optionally run separate session-randomized experiments and session-scoped caps strictly isolated from user-randomized readouts.
  • Why do live advertiser dashboards often disagree slightly with end-of-month invoices, and how do you keep advertiser trust high? Real-time stream processors must emit numbers within minutes, before offline mobile beacons arrive hours later and before full multi-hour statistical Invalid Traffic (IVT) bot/click-farm detectors finish analyzing IP/device graphs. We minimize drift by keying both Flink and nightly Spark on the exact same impression_id deduplication key and the tamper-proof serve_ts inside the HMAC token, clearly badge live OLAP charts as "Preliminary — excludes final bot filtering & late mobile syncs", freeze each UTC billing day in Spark after a fixed 24-hour late-event watermark, and post any rare post-close fraud clawbacks as explicit credit-memo line items rather than silently mutating historical closed days.

Follow-up questions

Similar questions

More Warner Bros Discovery interview questions

All 2 Warner Bros Discovery questions →