Multi-Tenant Ad Serving and Attribution Platform

Medium · System Design · Software Engineer · Onsite

Prompt

Architect a multi-tenant ad platform that serves creatives submitted by many separate organizations and records telemetry so each organization can judge which creatives perform strongest and weakest.

Core product choices—supported creative formats, ad-selection policy, traffic volume, billing rules, audience targeting, and the exact definition of "better performance"—are intentionally unspecified. Settle foundational v1 rules before introducing real-time bidding auctions or user-level personalization.

Enforce strict tenant isolation so one organization can never access or distort another's campaigns or statistics, and cleanly separate genuine human ad exposures from raw slot fetches, duplicate network retries, or automated bot activity.

Ambiguities to Resolve First

  • Tenant onboarding and eligibility: Who can register and manage creatives, and what verification, review, or policy gates apply prior to serving?
  • Funnel event definitions: What exact technical criteria define a slot opportunity, a rendered or viewable exposure, a click, and a downstream conversion?
  • Fair evaluation metrics: Should creatives be compared using exposure-normalized rates, raw totals, or monetary return—and how do you account for unequal exposure volume, small-sample noise, and slot bias?
  • Noisy real-world telemetry: How does the ingestion pipeline handle retried beacons, delayed or out-of-order mobile events, and invalid automated traffic?

Scope & Expectations

  • Explicit v1 scope and tenant boundaries: Define creative review workflows, serving eligibility, an unbiased baseline rotation policy, and multi-layer tenant isolation across APIs and storage.
  • Low-latency serving and verified funnel tracking: Design ad selection alongside tamper-proof event collection distinguishing slot requests, rendered/viewable exposures, click redirects, and conversion callbacks.
  • Deduplication, late-event reconciliation, and bot filtering: Detail stateful processing for duplicate beacons, clicks arriving ahead of impressions, delayed mobile flushes, and auditable invalid-traffic filtering.
  • Statistically sound comparisons: Show how dashboards compare click-through and conversion rates with proper denominators, confidence intervals, and placement-scoped aggregation.

Step-by-step walkthrough

  1. Clarify requirements and settle v1 scope before auctions

    The prompt intentionally leaves formats, selection rules, event definitions, and the meaning of "performance" open — and warns us to pin those down before jumping to auctions or personalization. Start by answering each clarifying question with concrete v1 rules:

    1. Tenant onboarding, creative review, and serving eligibility - Self-serve organizations register, verify ownership of their landing-page domains (via a DNS TXT record so Org A can never run ads linking to Org B's website), and invite team members under role-based access control: owner, editor (create/edit campaigns and ads), and analyst (view statistics only). - Platform Trust & Safety reviewers approve every new or edited creative version before it can serve. - An ad is eligible for a page slot (placement) only when: (a) its live creative version is approved, (b) both ad and campaign are active and within [start_at, end_at], (c) its daily impression cap has headroom, (d) its format matches the placement, and (e) its landing URL belongs to one of the org's verified domains.

    2. Six-stage exposure and engagement funnel - Separate an opportunity from an actual human display across six distinct funnel stages: 1. Ad request (opportunity): a page slot asks our server for an ad. 2. Served: the ad server picks an eligible ad and mints a unique impression_id (still not visible to the user!). 3. Rendered impression: browser code confirms the ad's pixels actually rendered in the DOM. 4. Viewable impression: at least 50% of the ad's pixels stayed in the viewport for >= 1 continuous second (the industry MRC/IAB display standard). 5. Click: the user clicks the ad and passes through our /c/ redirect endpoint. 6. Conversion: a downstream goal (signup, purchase) reported server-to-server by the organization using our click_id within a 7-day attribution window.

    3. Rate-based evaluation and v1 rotation - Never rank ads by raw click or conversion counts — an ad with 10x more exposure naturally collects more clicks! Compare rates paired with their denominators and 95% confidence intervals, strictly within the same placement and time period: - Primary CTR (click-through rate): valid_clicks_on_viewable_impressions / viewable_impressions. - Rendered CTR (fallback where viewability scripts cannot run): valid_clicks / rendered_impressions. - Conversion rate (CVR): valid_conversions / valid_clicks. - v1 selection policy — uniform random rotation among eligible ads for a placement, capped at 3 exposures per user per day (frequency cap). Skipping auctions and personalization in v1 is a deliberate statistical advantage: random rotation gives every eligible ad in a slot the exact same audience and time-of-day mix!

    4. Deduplication, late arrival windows, and invalid traffic - Duplicates: deduplicated to at most 1 event per (impression_id, event_type) (and 1 conversion per (org_id, dedup_key)). - Delayed events: bucketed by server served_at event time (never arrival time). Render/viewable beacons are accepted up to 1 hour after served_at, clicks up to 24 hours, and hourly rollups stay provisional until 48 hours after the UTC day ends, when a batch job marks impression/click stats final. - Invalid traffic (IVT) (automated bots, scrapers, or click spam): flagged and excluded from primary counts, but stored with a reason code and surfaced in a separate "invalid_filtered" column so numbers stay 100% auditable.

    Non-functional targets: ad serving latency P99 < 50 ms (pages time out after 100 ms and render cleanly with no ad rather than blocking), 99.95% serving availability, ~5 min provisional dashboard freshness, and strict zero-leakage multi-tenant isolation.

  2. Back-of-the-envelope numbers

    Estimate funnel counts, ingestion throughput, state size, and statistical power up front:

    1. Daily funnel (assuming ~50 placements on properties we operate)
       Ad requests (opportunities)    100,000,000 / day  (~1,160 RPS avg, ~5,000 RPS peak)
       Served (80% fill rate)          80,000,000 / day
       Rendered (90% of served)        72,000,000 / day  (10% lost to ad blockers / fast tab closes)
       Viewable (70% of rendered)      50,000,000 / day  (30% stay below the fold)
       Clicks (0.50% viewable CTR)        250,000 / day
       Conversions (2.0% of clicks)         5,000 / day
    
    2. Event ingestion & storage
       Total raw events/day    100M serve/req logs + 72M renders + 50M views + 0.25M clicks = ~222M/day
       Throughput & disk       ~2,570 events/s avg, ~10,000 events/s peak
                               222M x ~300 B = ~67 GB/day raw (~6.0 TB for 90-day raw retention)
    
    3. Ad catalog & stream deduplication state
       Active catalog          2,000 orgs x 50 active ads = 100,000 ads (~30 MB RAM snapshot per server)
       48-hour dedup state     80M served/day x 2 days x ~100 B = ~16 GB across stream-processor workers
    
    4. Statistical sample-size reality check (two-proportion test, alpha = 0.05, 80% power)
       Detecting a 10% relative CTR lift (0.50% -> 0.55%) requires ~330,000 viewable impressions per ad!
       Average ad volume       50,000,000 viewable / 100,000 ads = ~500 viewable impressions / day
    

    Three crucial design lessons emerge from this math:

    • Most ads receive ~500 views/day, far short of 330,000: a naive leaderboard sorted by raw CTR percentage will be dominated by tiny-sample luck (2 clicks / 50 views = 4.0%!). Confidence intervals and minimum-denominator gates are mandatory product features.
    • Serving fits completely in RAM: 100,000 eligible ads occupy ~30 MB, so every ad server selects ads in microseconds from an in-memory snapshot.
    • Dashboards query tiny hourly rollups, not raw beacons: 30 days of hourly rollups for a 50-ad org across 5 placements is at most 50 x 5 x 24 x 30 = 180,000 rows in an analytical store instead of millions of raw events.
  3. API and stateless cryptographic impression tokens

    Organization Management & Stats API (authenticated session; org_id verified against caller membership)
      POST  /v1/orgs/{org_id}/campaigns          {name, start_at, end_at, daily_impression_cap}
      POST  /v1/orgs/{org_id}/ads                {campaign_id, format, creative, landing_url, placements[]}
      PATCH /v1/orgs/{org_id}/ads/{ad_id}        creates a new immutable creative_version -> pending_review
      POST  /v1/orgs/{org_id}/ads/{ad_id}:pause | :resume
      GET   /v1/orgs/{org_id}/stats?from=...&to=...&placement_id=...&group_by=ad_id,day
            -> [{ad_id, version_id, served, rendered, viewable, clicks, conversions, invalid_clicks,
                 viewable_ctr, ctr_ci_95: [lo, hi], sufficient_sample: bool, finality: "provisional"|"final"}]
      POST  /v1/orgs/{org_id}/conversions        {click_id, event_name, occurred_at, dedup_key} (org API key)
    
    Trust & Safety Review API (internal staff RBAC)
      GET   /v1/review/queue
      POST  /v1/review/versions/{version_id}:approve | :reject {reason}
    
    Ad Serving & Event Collection API
      GET   /v1/serve?placement_id=guide_banner_728x90&page_view_id=...
            -> 200 {ad_id, version_id, creative, impression_token, click_url: "/c/<click_token>"}
            -> 204 No Content (no eligible ad or cap reached)
      POST  /v1/events      [{event_id, impression_token, event_type: "rendered" | "viewable"}]
      GET   /c/{click_token} -> verify signature, log click, 302 redirect to landing_url?click_id=...
    

    Why the signed impression_token is the linchpin of the pipeline:

    When /v1/serve picks an ad, it mints a random impression_id and signs (impression_id, org_id, ad_id, version_id, placement_id, user_hash, served_at) using HMAC (hash-based message authentication code — a fast cryptographic signature created with a secret server key so clients cannot forge or alter the payload):

    • Stateless edge verification: event collectors validate the HMAC signature and expiry in microseconds with zero database lookups.
    • Anti-spoofing: an attacker cannot invent fake impression_ids or alter ad_id to pollute a rival org's CTR (automated bots that call /v1/serve still obtain real tokens, which our IVT filters catch downstream).
    • Trusted server clock: all hourly buckets use served_at embedded inside the signed token, ignoring skewed user device clocks.
  4. Data model and tenant isolation

    Use PostgreSQL for low-volume relational metadata and ClickHouse (an OLAP columnar database — an analytical store that lays out each column contiguously on disk so summing millions of rows takes milliseconds) for event tables and hourly rollups:

    PostgreSQL (Control Plane — backed by Row-Level Security on org_id)
      orgs               (org_id UUID PK, name, status, verified_domains[])
      memberships        ((org_id, user_id) PK, role [owner|editor|analyst])
      campaigns          (campaign_id UUID PK, org_id, name, start_at, end_at, daily_cap, status)
      ads                (ad_id UUID PK, org_id, campaign_id, format, placements[], status, live_version_id)
      creative_versions  (version_id UUID PK, ad_id, org_id, creative_json, landing_url,
                          review_status, reviewer_id, reviewed_at)   -- immutable once submitted!
      placements         (placement_id PK, surface, format, dimensions)
      audit_log          (audit_id PK, org_id, actor_id, action, entity_id, before_json, after_json, ts)
    
    ClickHouse + S3 Parquet Archive (Analytics Plane)
      serve_log          (impression_id, served_at, placement_id, org_id, ad_id, version_id,
                          user_hash, eligible_count, selection_prob)
      valid_events       ((impression_id, event_type) UNIQUE KEY, org_id, ad_id, version_id,
                          placement_id, served_at, received_at, inferred bool)
      invalid_events     (event_id, impression_id, org_id, ad_id, event_type, served_at, reason)
      conversions        ((org_id, dedup_key) UNIQUE KEY, click_id, impression_id, ad_id, occurred_at)
      agg_hourly         ((org_id, ad_id, version_id, placement_id, hour_start) PK,
                          served, rendered, viewable, clicks_total, clicks_on_viewable, conversions,
                          invalid_renders, invalid_clicks, unique_users_hll, finality)
      placement_hourly   ((placement_id, hour_start) PK, ad_requests, served_count)
    

    Three schema choices worth calling out:

    • org_id lives on every single table (including events and rollups): queries enforce WHERE org_id = :session_org_id directly on the primary sort key without fragile cross-table joins.
    • Immutable creative_versions: editing an ad's headline creates version_2 (pending_review) while version_1 keeps serving (or pauses), preventing unreviewed edits from going live and keeping before/after creative stats cleanly separated.
    • Compact unique-reach sketches (unique_users_hll): storing a HyperLogLog sketch (a ~1.5 KB probabilistic counter that estimates distinct user_hash counts within ~1–2% error and merges across hours/days) gives orgs unique reach and average frequency without scanning raw user logs.
  5. High-level architecture

    Decouple low-latency ad serving, durable event collection, stateful stream reconciliation, and analytical queries so a spike or outage in analytics never slows down page loads:

      [ Org Portal ] ---> [ Management API (RBAC + RLS) ] ---> [ PostgreSQL ] <--- [ Trust & Safety UI ]
                                                                     |
                                        every 30s snapshot (+ <5s kill-list pub/sub)
                                                                     v
      [ First-Party Page ] --GET /v1/serve--> [ Stateless Ad Servers (in-memory catalog) ] <--> [ Redis Caps ]
             |                                          |
             | (renders ad, fires sendBeacon            +--> async serve_log --------+
             |  to /v1/events, clicks /c/token)                                      |
             v                                                                       v
      [ Stateless Collectors (verify HMAC) ] -----------------------------> [ Kafka (64 partitions,   ]
      [ Conversion API (verify org owns click_id) ] ----------------------> [ keyed by impression_id) ]
                                                                               |                 |
                                                +------------------------------+                 |
                                                v                                                v
                               [ Stateful Stream Processor (Flink) ]               [ S3 Raw Parquet (90d) ]
                               (48h keyed state: dedup, join funnel,                             |
                                flag IVT, reconcile click-before-render)                         v
                                                |                                  [ Nightly Batch Job ]
                                                v (provisional, ~2-5 min)          (48h final recompute +
                                         [ ClickHouse OLAP ] <--------------------- subnet fraud clustering)
                                                ^
                                                | (mandatory org_id filter + Wilson CIs)
                                         [ Org Stats API ]
    
  6. Deep dive 1: Funnel event validation, deduplication, and bot filtering

    Map every stage of the funnel to its exact validation rule and statistical role:

    Funnel Stage   Source            Counted Only When                                  Used As Denominator For
    -------------  ----------------  -------------------------------------------------  -----------------------
    ad_request     /v1/serve call    Every slot request (filled or 204 unfilled)        Placement fill rate
    served         Ad Server         Eligible ad picked; impression_id minted           Render rate
    rendered       Browser beacon    Valid HMAC; 1st "rendered" for id; <=1h; non-IVT   Viewability rate & rendered CTR
    viewable       Browser beacon    >=50% pixels >=1s continuous; <=1h; non-IVT        Primary viewable CTR
    click          /c/ redirect      Valid HMAC; 1st "click" for id; <=24h; non-IVT     Conversion rate (CVR)
    conversion     Org backend       click_id belongs to org; <=7d; 1st per dedup_key   Cost / value per conversion
    

    Why duplicates happen constantly — and how partitioned state absorbs them - Single-page apps re-mount components, mobile browsers retry sendBeacon after flaky cellular ACKs, and impatient users double-click links. Because retries may generate a new event_id for the same impression, deduplicating by event_id is not enough — the business key is (impression_id, event_type). - Every Kafka topic is partitioned by hash(impression_id) % 64. All serve, rendered, viewable, and click events for imp_88 land on the exact same Flink task, which holds a 48-hour disk-backed keyed state record ({served_flag, seen_mask, viewable_seen, pending_click}) totaling ~16 GB across the cluster. Flink checkpoints (periodically snapshots in-memory/RocksDB state alongside Kafka offsets to durable storage) so worker restarts never double-count.

    Filtering invalid traffic (IVT) transparently - Real-time stream rules: known crawler/headless User-Agent lists, cloud data-center IP ranges, inhumanly fast clicks (< 150 ms after render — faster than human visual reaction time; note that setting this to < 1 s would mistakenly discard fast real human clicks!), and per-user click bursts (> 5 clicks from one user_hash on one ad in an hour). - Nightly batch rules: cross-impression graph checks, such as one /24 IP subnet generating 40% of clicks on a single org's campaign. - Filtered rows land in invalid_events with reason so orgs can audit traffic spikes instead of seeing mysterious drops.

  7. Deep dive 2: Late, out-of-order, and click-before-impression reconciliation

    Mobile tabs go offline in subways and flush queued beacons 20 minutes later, and clicking an <a href="/c/..."> link starts page navigation immediately — often reaching our server before (or instead of) the asynchronous rendered or viewable beacon!

    Case A: Out-of-order arrival (beacon delayed by slow mobile network)
      14:12:00.100  Ad Server logs serve(imp_88, served_at=14:12)
      14:12:01.400  User clicks /c/<token>  --> arrives FIRST! Held in Flink state for imp_88
      14:12:03.900  rendered + viewable beacons arrive --> joined! 1 render, 1 viewable, 1 viewable_click
                    (all credited to hour 14:00 via served_at, NOT arrival time!)
    
    Case B: Orphan click (page navigation or blocker dropped the render beacon completely)
      14:12:00.100  serve(imp_88) logged
      14:12:00.900  click(imp_88) arrives with valid HMAC; 1-hour render window expires with no beacon
      15:12:00.100  Timer fires -> serve_log proves imp_88 was served -> emit 1 click +
                    1 INFERRED rendered impression (inferred=true), WITHOUT inferring viewability!
    

    Notice how two invariants prevent broken math like CTR > 100%:

    1. clicks_total <= rendered always holds because an un-rendered orphan click verified against serve_log synthesizes 1 rendered impression marked inferred = true (alerting engineers or fraud analysts if inferred / rendered spikes above ~2% on a placement).
    2. clicks_on_viewable <= viewable always holds because we never guess viewability from a fast click; viewable_ctr divides clicks_on_viewable (clicks whose imp_id also recorded a viewable event) by viewable, keeping numerator and denominator on the exact same set of impressions!
  8. Deep dive 3: Fair performance comparisons across ads and placements

    Consider why raw click totals mislead:

    • Creative M: 800 clicks across 250,000 viewable impressions -> 0.32% CTR.
    • Creative N: 120 clicks across 20,000 viewable impressions -> 0.60% CTR.

    Ranking by raw clicks crowns Creative M (800 > 120) even though Creative N engages viewers at nearly twice the rate! Even when comparing rates, three statistical pitfalls remain:

    1. Quantify small-sample uncertainty with Wilson score intervals The textbook p +- 1.96 * sqrt(p*(1-p)/n) interval produces nonsense (like negative lower bounds or zero width) when clicks == 0 or n is small. Use the Wilson score interval (a closed-form binomial confidence interval that stays strictly inside [0, 1] at any sample size):

    import math
    
    
    def wilson_ctr_interval(clicks: int, viewable_impressions: int, z: float = 1.96) -> tuple[float, float]:
        """Compute a 95% Wilson confidence interval for CTR = clicks / viewable_impressions."""
        if viewable_impressions <= 0:
            return (0.0, 1.0)
    
        n = viewable_impressions
        p_hat = clicks / n
        z2 = z * z
    
        # Shift the center slightly toward 0.5 and scale by (1 + z^2 / n) so small samples stay well-behaved.
        denom = 1.0 + z2 / n
        center = (p_hat + z2 / (2.0 * n)) / denom
        spread = z * math.sqrt((p_hat * (1.0 - p_hat) / n) + (z2 / (4.0 * n * n))) / denom
        return (max(0.0, center - spread), min(1.0, center + spread))
    
    • 2 clicks / 200 viewable -> 1.00% point CTR, but 95% CI is [0.27%, 3.57%] -> UI badges "Insufficient data" instead of crowning it #1.
    • 500 clicks / 100,000 viewable -> 0.50% point CTR, 95% CI is [0.46%, 0.55%] -> tight and actionable.

    2. Defeat Simpson's paradox by comparing within placements (or standardizing) - Simpson's paradox happens when Ad X looks better overall than Ad Y simply because Ad X got 90% of its views in a high-CTR top hero slot (2.0% baseline) while Ad Y ran mostly in a footer slot (0.1% baseline), even if Ad Y beat Ad X in both slots individually! - Default every comparison table to a single placement and date range. When showing a cross-placement summary across common slots S, compute a standardized CTR weighting each ad's slot CTR by the shared slot impression shares w_s: sum_{s in S} w_s * CTR(ad, s).

    3. Future-proofing for non-uniform selection and multi-ad leaderboards - Logging selection_prob on every serve_log row (1 / eligible_count today) means that if v2 introduces bandit optimization or auctions, offline comparisons can reweight each impression by 1 / selection_prob (inverse propensity weighting, which removes selection bias as long as every eligible ad keeps a small non-zero exploration floor, e.g. 5%). - When an org compares 50 creatives at once, rank using empirical Bayes shrinkage (blending noisy low-impression CTRs toward the placement's prior mean CTR until sample size grows).

  9. Deep dive 4: Multi-tenant data isolation

    Multi-tenant analytics bugs are catastrophic trust failures. Enforce isolation across five independent layers:

    • Identity-derived scoping: resolve allowed org_ids from the authenticated session or API key in middleware; if /v1/orgs/{org_id}/ads/{ad_id} references an unauthorized org or another org's random UUID, return 404 Not Found (never 403 Forbidden, which leaks existence).
    • Mandatory storage predicates + Postgres RLS: our query builder rejects any SQL or ClickHouse query missing a bound org_id parameter, backed by PostgreSQL row-level security (RLS) policies (USING (org_id = current_setting('app.org_id')::uuid)). Orgs never get direct SQL/BI credentials to ClickHouse.
    • Conversion ownership check: POST /v1/orgs/{org_id}/conversions looks up click_id first and verifies click.org_id == caller_org_id before writing, preventing one org from injecting fake conversions into another org's funnel.
    • Aggregated cross-org benchmarks (k-anonymity): placement benchmarks ("Median CTR on guide_banner_728x90 is 0.48%") are shown only when at least 10 distinct organizations served >= 1,000 impressions in that slot, and audience breakdowns with < 10 distinct users are suppressed.
    • Verified landing domains: enforcing DNS domain ownership + re-reviewing every creative edit prevents phishing and brand impersonation between tenants.
  10. Scaling, failure modes, and trade-off summary

    • Stateless serving + fast kill switch: 4–6 stateless ad servers easily serve 5,000 RPS peak from RAM (~30 MB catalog). Normal creative updates propagate via 30-second snapshots; emergency policy takedowns push a tiny kill_list over Redis Pub/Sub in < 2 seconds.
    • Linear stream & collector scaling: stateless collectors validate HMACs and append to 64 impression_id-hashed Kafka partitions — zero hot keys even if one viral campaign receives 50% of all impressions, because every impression has a distinct UUID!
    Failure Scenario                  Impact & System Behavior
    --------------------------------  --------------------------------------------------------------------
    Ad server slow or unreachable     Page's 100 ms fetch timeout fires -> collapses slot cleanly (no ad)
    Redis frequency/daily cap down    Serve from RAM without user freq cap (or fail closed on strict caps)
    Snapshot builder / Postgres down  Ad servers keep serving last valid snapshot; alert after 10 min
    Collector / network blip          Browser retries sendBeacon; (impression_id, type) dedup absorbs it
    Flink worker crashes              Restores RocksDB checkpoint + Kafka offset; zero double-counting
    Stream vs. nightly batch drift    Nightly 48h batch over S3 Parquet overwrites final agg_hourly; alert >0.5%
    

    Summary of core design choices

    • Uniform random rotation + logged selection_prob in v1 delivers clean, unbiased ad-to-ad comparisons before adding auction complexity.
    • HMAC-signed impression tokens decouple serving from collection, stop forged impression IDs without DB reads, and anchor late events to server served_at.
    • Six-stage funnel + (impression_id, event_type) keyed state + inferred renders on orphan clicks separate raw requests from human-viewable impressions and guarantee 0% <= CTR <= 100%.
    • Rates with Wilson intervals + single-placement scoping + defense-in-depth org_id enforcement keep small-sample noise and cross-tenant data leaks out of customer dashboards.

Intuition & how it works

Think of a multi-organization advertising platform like running fair blind taste-test booths across a shopping mall for hundreds of independent brands. Printing a flyer in the back office ("ad served") does not mean a shopper actually saw the sign ("viewable impression"), and a brand given 500 hours in the busy main entrance will naturally collect more samples than a brand given 10 hours near a side exit — so judging quality by raw click totals is meaningless unless you divide clicks by the exact number of shoppers who saw that same booth.

Why does a naive design break down immediately? Counting every /serve API response as an impression inflates denominators with ads blocked by extensions or buried below the fold, ranking ads by raw click counts rewards bigger schedules rather than better creatives, and comparing overall click-through rates across different page slots falls into Simpson's paradox (a statistical trap where an inferior ad appears to win overall only because most of its impressions ran in a high-performing top banner). Worse, accepting plain client-sent IDs or timestamps lets bots or rival tenants spoof events, double-count network retries, and corrupt competitors' dashboards.

Follow one ad opportunity (imp_88) through our pipeline to see how every stage stays accurate and isolated:

Step  Component                     What happens
----  ----------------------------  ----------------------------------------------------------------------
1     Ad Server (/v1/serve)         Picks Org Atlas's Ad #19 uniformly at random for "guide_banner_728x90",
                                    mints HMAC token (imp_88, org_atlas, ad_19, served_at=14:12), logs serve
2     Browser Beacons (/v1/events)  Sends "rendered" twice (cellular retry) + "viewable" (>=50% pixels
                                    on screen >=1s); stateless Collector verifies HMAC with zero DB reads
3     Click Redirect (/c/<token>)   User clicks at 14:12 (520 ms after render >= 150 ms human floor) ->
                                    logs click for imp_88 and 302-redirects to Org Atlas's verified domain
4     Flink Stream Processor        Partitioned by imp_88: collapses the duplicate "rendered", joins
                                    viewable + click under hour 14:00 (from served_at), updates agg_hourly
5     Org Atlas Stats API           Scopes query to org_atlas, computes viewable CTR + 95% Wilson
                                    confidence interval strictly within slot "guide_banner_728x90"

Key trade-offs

  • Uniform random rotation vs. click-optimized selection (bandits or auctions). Uniform rotation gives every eligible ad in a placement the exact same mix of users and times of day, making ad-to-ad CTR comparisons unbiased out of the box, at the cost of spending impressions on weaker ads. Optimizing selection early boosts short-term clicks, but starves new ads and biases every historical rate unless you reserve random exploration traffic and log selection_prob for inverse propensity weighting (reweighting each impression by 1 / selection_prob).
  • Viewable impressions vs. rendered impressions as the primary CTR denominator. Requiring viewability (>= 50% of pixels visible for >= 1 continuous second) measures ads users actually had a chance to see and removes bias against below-the-fold page slots, but relies on browser IntersectionObserver beacons that strict privacy extensions may block. Tracking both and using viewable CTR as primary (with rendered CTR as fallback) gives accuracy without flying blind.
  • Dual streaming + nightly batch pipeline (Lambda-style reconciliation) vs. streaming alone. Stateful stream processing delivers provisional stats within 2–5 minutes, while a nightly batch job over raw S3 logs after 48 hours catches late mobile beacons, runs cross-subnet fraud clustering, and guarantees reproducible final counts from scratch — trading extra compute for auditability that future billing can trust.
  • 48-hour late-event window vs. 7-day window for impressions and clicks. Keeping deduplication state open for 48 hours (~16 GB in Flink) captures 24-hour click windows plus offline mobile retries while letting daily numbers lock within two days; extending impression state to 7 days would grow state 3.5x and delay final badges for marginal gain (7-day windows are reserved for low-volume server-to-server conversions).
  • Synthesizing inferred renders for orphan clicks vs. dropping orphan clicks. When a user clicks an ad whose render beacon was dropped during page unload, emitting an inferred = true rendered impression preserves real user clicks and enforces clicks <= rendered_impressions, at the risk of counting bot clicks that bypass rendering — mitigated by verifying serve_log, checking IVT rules, and alerting on inferred spikes.
  • Confidence intervals and sample gates vs. simple sorted leaderboards. Showing Wilson score intervals and "Insufficient data" badges requires slightly more user education than a plain #1, #2, #3 rank list, but prevents organizations from pausing strong ads or promoting lucky 2 / 50 outliers when average ads receive only ~500 views/day.
  • Shared multi-tenant tables with org_id vs. physical database-per-tenant. Shared tables keyed by org_id simplify operations across 2,000 organizations and enable anonymized placement benchmarks, trading physical separation for strict application-layer query guards and database row-level security (RLS) (automatic engine-enforced row filtering by tenant).

Common mistakes

  • Counting raw ad requests or server served logs as impressions. Ad blockers, network drops, and fast tab closes prevent ~10% of served responses from ever painting on screen, and ~30% more never scroll into view.
  • Ranking ads by total clicks or conversions without denominators. Exposure volume dominates raw counts; a creative shown 250,000 times with 0.32% CTR collects far more clicks (800) than a nearly twice-as-effective 0.60% CTR creative shown 20,000 times (120).
  • Comparing CTRs aggregated across different placements. Aggregating a 2.0% hero banner with a 0.1% footer slot rewards whichever ad happened to run more often in the hero banner (Simpson's paradox).
  • Using textbook normal-approximation intervals (p +- 1.96 * sqrt(p(1-p)/n)) on low counts. At 0 or 1 click, normal intervals collapse to zero width or go negative; the Wilson score interval stays accurate near zero.
  • Deduplicating by event_id instead of (impression_id, event_type). Browser component re-mounts and bfcache restores generate brand-new event_ids for the exact same ad display.
  • Setting the fast-click bot filter to < 1 second. Real humans routinely click prominent banners in 300–600 ms; only clicks faster than human visual reaction time (< 150 ms) indicate automated scripts.
  • Bucketing analytics by server arrival time instead of served_at. Delayed mobile beacons shift clicks into later hours than their impressions, creating hours with 5 clicks / 0 impressions.
  • Silently deleting invalid traffic or allowing unverified click_id conversions. Dropping bot events without logging invalid_events makes discrepancies impossible to audit, and skipping click.org_id == caller_org_id lets tenants corrupt competitors' conversion rates.

Follow-up questions

  • If a user click reaches your collectors ahead of the corresponding impression beacon, how does your pipeline join and count both events? Every click URL carries an HMAC-signed token containing impression_id, org_id, ad_id, placement_id, and served_at, and Kafka partitions every stream by impression_id so both events always land on the same stateful stream worker. When the click arrives first, the worker validates its HMAC and stores it as pending in keyed state for impression_id, joining it cleanly as soon as the rendered (and viewable) beacon arrives within the 1-hour beacon window. If the 1-hour timer expires with no rendered beacon — common when clicking <a href="/c/..."> unloads the page before sendBeacon flushes — the worker confirms impression_id exists in serve_log and emits both the valid click and an inferred rendered impression (inferred = true) bucketed under served_at, guaranteeing clicks <= rendered_impressions while keeping viewable_ctr strictly scoped to impressions that logged a real viewable event.
  • How would you design an online controlled experiment to prove causally that one creative outperforms another? Run a user-randomized A/B test scoped to a single placement and fixed date window where both Creative M and Creative N satisfy identical eligibility rules. Whenever an opportunity arrives on that placement, assign the user deterministically via hash(user_key, experiment_id) % 2 so each user consistently sees only M or only N (eliminating cross-contamination across repeat page views). Pre-specify the primary metric (such as viewable CTR or conversions per exposed user), minimum detectable effect, and required sample size (for example, ~330,000 viewable impressions per arm for a 0.50% vs. 0.55% CTR lift at alpha = 0.05 and 80% power, inflated slightly for within-user correlation), and run full 7-day cycles to cover weekday/weekend patterns without early peeking. Analyze using cluster-robust standard errors grouped by user_key (since multiple impressions from the same user are not independent), and run a chi-square sample-ratio mismatch (SRM) check (verifying the observed user split matches 50/50 within chance so broken redirects or bot filters did not skew one arm).

Follow-up questions

Similar questions

More Digitalocean interview questions

All 3 Digitalocean questions →