Advertising Platform Data Schema

Medium · System Design · Software Engineer · Onsite

Prompt

Architect the logical database schema for a large-scale digital advertising system.

Your schema design should model these core domain records:

  • Advertiser accounts & buying organizations: direct brands, agencies, billing metadata, and console staff permissions.
  • Campaigns & spending caps: flight schedules and lifetime or daily budget limits.
  • Buying tiers (ad groups / line items): bid rates, pacing strategies, and frequency caps.
  • Creatives & media files: ad formats, reviewable versions, and underlying video or image assets.
  • Targeting criteria: audience cohorts, geographic regions, device classes, and content attributes.
  • Viewer identity & privacy boundaries: pseudonymous identifiers, consent preferences, and erasure handling.
  • Event telemetry: ad-serving decisions, impressions, clicks, and downstream conversions.

For instance, a brand such as Summit Sportswear might configure a $2,000 daily campaign with a $25.00 CPM line item targeting sci-fi viewers in Canada, serve approved video renditions during playback breaks, and later upload purchase events to measure campaign return.

Scope & Expectations

  • Define core entities, primary/foreign keys, and cardinality relationships (1:N and N:M), explaining which physical storage engines hold mutable configuration, viewer state, and high-volume event streams.
  • Trace how the data model supports three operational lifecycles: campaign authoring (creating campaigns, targeting predicates, and creatives), real-time ad selection (millisecond eligibility matching at break time), and event tracking & attribution (deduplicating playback/click beacons and crediting conversions).
  • Show how user identifiers and consent records keep personal subscriber information isolated from ad-serving and reporting tables.
  • Specify indexing, sharding, and partitioning choices that sustain peak write throughput and multi-timezone advertiser reporting.

Step-by-step walkthrough

  1. Clarify requirements and scope

    Because this prompt asks for a logical data model, the database schemas and entity relationships are the main deliverable. System architecture matters only insofar as it explains which storage engine holds each group of entities and how the three core flows read and write them without stepping on each other.

    Assumed product context: video ads shown during commercial breaks on a streaming service's ad-supported subscription tier (across smart TVs, mobile phones, and web browsers). Advertisers mostly buy on a CPM basis (cost per mille, meaning the price paid per 1,000 ad views), with scheduled start/end dates (called a flight), budgets, audience/content targeting rules, and frequency caps (limits on how many times one viewer sees the same ad within a time window).

    Functional requirements

    • Intake flow: advertisers (directly or via an ad agency) create campaigns (overall marketing goals and budgets), line items (specific buying rules under a campaign: bid price, targeting, and frequency cap), and creatives (the actual ad experience shown to viewers, backed by video/image assets that must pass policy review).
    • Serving flow: when a viewer hits an ad break, select 2–3 eligible ads (an ad pod) in a few milliseconds by checking active flight dates, targeting match, remaining budget, pacing (spreading delivery smoothly across the day instead of spending the whole budget at 8:00 AM), frequency caps, creative approval, and competitive separation (never showing two rival car brands in the same break).
    • Tracking flow: record ad decisions, impressions (an ad actually starting playback), video quartiles (playback reaching 25%, 50%, 75%, and 100%), and clicks; ingest advertiser conversions (purchases or sign-ups); perform attribution (crediting an earlier impression or click for a conversion); and bill only valid, deduplicated impressions.
    • Reporting & privacy: report metrics per advertiser, campaign, line item, and creative in the advertiser's local time zone. Keep viewers pseudonymous (represented only by a random ID inside the ad platform), enforce user consent for personalization, and honor data-deletion requests.

    Non-functional requirements

    • Low-latency, isolated serving: ad selection p99 latency under ~20 ms; serving must never query the transactional intake database directly.
    • Billing accuracy: each real impression is billed at most once (idempotent under network retries), and budget overruns from reporting lag are bounded and absorbed by the platform.
    • Reporting freshness: preliminary dashboard numbers within minutes; finalized, fraud-filtered billing numbers within 24 hours.
    • Privacy by design: no names, emails, payment details, IP addresses, or exact GPS coordinates ever enter ad-serving or delivery-log tables.

    Central modeling insight: an ad platform handles three fundamentally different data shapes, so forcing everything into one database fails. Instead, we split the logical model across three physical storage tiers: 1. Configuration data (advertisers down to creatives): small, relational, edited by humans, requiring strict transactions -> relational database (PostgreSQL). 2. Viewer state (pseudonymous profile attributes, audience segments, frequency counters): tens of gigabytes, looked up by one viewer key on every ad break -> distributed key-value store. 3. Delivery logs (decisions, impressions, quartiles, clicks, conversions): billions of immutable events per day -> append-only stream (Kafka), columnar data lake (Parquet/Iceberg), and pre-aggregated OLAP (online analytical processing, fast column-oriented analytics) rollup tables.

  2. Back-of-the-envelope numbers

    Sizing the data tells us immediately why configuration fits in memory while delivery logs need partitioned append-only storage:

    All numbers below are illustrative sizing assumptions, not internal figures.
    
    1. Configuration (relational DB + compiled in-memory snapshot)
       Advertisers                  20,000 (direct brands + agency-managed accounts)
       Active campaigns            100,000
       Active line items           500,000 x ~2 KB (with targeting rules) = ~1 GB total
       Creatives                 1,000,000 x 3-10 encoded video renditions (assets)
       -> Takeaway: all active serving config (~1 GB) fits easily in RAM on every ad server!
    
    2. Ad requests & impressions
       Daily active ad-plan profiles   50,000,000
       Ad breaks per profile per day           ~3  -> 150M ad decisions/day
                                                   -> ~1,700 decisions/s avg, ~6,000/s prime-time peak
       Ads per break (pod size)              2-3   -> ~400M impressions/day
                                                   -> ~4,600 impressions/s avg, ~15,000/s peak
    
    3. Tracking & attribution events
       Beacons per impression     1 impression + 4 quartiles (25/50/75/100%) = 5 events
                                  -> ~2B playback events/day (~23,000/s avg, ~75,000/s peak)
       Clicks / QR scans          ~0.3% click rate -> ~1.2M clicks/day
       Conversions uploaded       ~5M/day across all advertisers
       Storage volume             2B events x ~400 B raw JSON = ~800 GB/day (~0.8 TB/day) raw
                                  Columnar Parquet compression (5-7x) -> ~120-150 GB/day in lake
    
    4. Viewer state (key-value stores)
       Audience segments          50M profiles x ~30 segments x 8 B IDs = ~12 GB raw (~18 GB with keys)
       Frequency-cap counters     50M profiles x ~10 recent line items x ~50 B = ~25 GB
                                  Write rate: 1 counter update per billed impression (~15,000 writes/s peak)
    

    Three design conclusions jump right out of this math: - Config is tiny (~1 GB): a single primary PostgreSQL instance (with read replicas) easily handles advertiser edits, and ad servers can keep a compiled copy of all active campaigns in RAM so serving never touches PostgreSQL. - Viewer state (~43 GB total) is purely single-key: every ad break looks up one ad_profile_id, making a hash-partitioned key-value store ideal. - Logs (~2B rows/day) are write-heavy and time-ordered: they belong in Kafka and time-partitioned lake tables, never in the relational config database.

  3. API across intake, serving, tracking, and reporting

    Before writing table schemas, sketch the APIs that read and write them. Two conventions prevent classic bugs: - Money is stored as integer micros (1 unit of currency = 1,000,000 micros, so $25.00 = 25,000,000 micros), never floating-point numbers that suffer from binary rounding errors. - Mutable endpoints require optimistic concurrency via an HTTP If-Match: <version> header: an update succeeds only if the database row still has that version, preventing two agency staffers from silently overwriting each other's edits.

    1. Intake API (advertiser-facing; OAuth token scoped to advertiser_id or agency_id)
       POST /v1/advertisers/{aid}/campaigns
            {name, objective, start_at, end_at, budget: {type: "lifetime"|"daily", amount_micros}}
       POST /v1/advertisers/{aid}/campaigns/{cid}/line_items
            {name, start_at, end_at, bid_cpm_micros, budget_micros?, pacing: "even"|"asap",
             frequency_cap: {max_impressions, window_seconds},
             targeting: {include: {dimension: [values]}, exclude: {dimension: [values]}}}
       PUT  /v1/advertisers/{aid}/line_items/{lid}/targeting    (Header: If-Match: <version>)
       POST /v1/advertisers/{aid}/assets                        -> {asset_id, signed_upload_url}
       POST /v1/advertisers/{aid}/creatives
            {name, format, duration_ms, asset_ids, landing_url, advertiser_domain}
       PUT  /v1/advertisers/{aid}/line_items/{lid}/creatives    [{creative_id, weight}]
    
    2. Serving API (internal RPC from playback service to ad server)
       POST /internal/ad-decisions
            {ad_profile_id?, device_type, os, country, region, content_id, genre,
             maturity_rating, break_position, max_ads, max_duration_ms}
         -> {decision_id, ads: [{impression_id, creative_id, rendition_url, tracking_token}]}
    
    3. Tracking API (public edge endpoints called by video players & advertiser servers)
       GET  /t/{event}?tok=<hmac_signed_token>&cts=<client_ts>  (event: imp|q25|q50|q75|q100|click)
       POST /v1/advertisers/{aid}/conversions
            [{external_event_id, event_type, event_ts, value_micros?, hashed_email?}]
    
    4. Reporting API (advertiser console & automated BI exports)
       GET  /v1/advertisers/{aid}/reports?level=line_item&from=2026-10-01&to=2026-10-07
            &tz=America/Toronto&breakdown=country,device_type
    

    Why tracking_token is signed and omits ad_profile_id: the ad server signs (impression_id, line_item_id, creative_id, creative_version, price_cpm_micros) using an HMAC (hash-based message authentication code, a cryptographic signature proving the server created the token) so clients cannot spoof free impressions or fake prices. Crucially, the URL token never contains ad_profile_id because URLs leak into CDN and proxy access logs; the backend joins the beacon back to ad_decision using decision_id instead.

  4. Data model: advertiser, campaign, creative, and targeting schema

    First, visualize how the configuration entities relate to one another before looking at SQL columns:

      [agency] 1 ---- 0..N [advertiser] N >---< M [console_user]
                                 |                (via advertiser_member)
                                 | 1
                                 v N
                            [campaign]  (holds overall flight & campaign budget)
                                 | 1
                                 v N
                           [line_item]  (holds bid CPM, pacing, freq cap, optional sub-budget)
                            /        \
                       1:N /          \ N:M (via line_item_creative, with rotation weight)
                          v            v
              [targeting_rule]      [creative] 1 ---- N [creative_version] (immutable, reviewed)
                     |                                           |
         (references segment_id)                    N:M (via creative_asset)
                     v                                           v
            [audience_segment]                                [asset] (mezzanine & renditions)
    

    These tables live in PostgreSQL. Every advertiser-owned table carries advertiser_id so queries are always scoped to one tenant (and if the DB ever shards, advertiser_id is the shard key so all single-advertiser transactions stay on one shard):

    CREATE TABLE agency (
      agency_id          BIGINT PRIMARY KEY,
      name               TEXT NOT NULL
    );
    
    CREATE TABLE advertiser (
      advertiser_id      BIGINT PRIMARY KEY,
      agency_id          BIGINT REFERENCES agency(agency_id), -- NULL when brand buys directly
      legal_name         TEXT NOT NULL,
      billing_account_id BIGINT NOT NULL,
      currency           CHAR(3) NOT NULL,   -- ISO 4217 (e.g., 'USD'), fixed at account creation
      time_zone          TEXT NOT NULL,      -- IANA zone (e.g., 'America/Chicago') for daily budgets
      industry_category  TEXT NOT NULL,      -- e.g., 'automotive', used for competitive separation
      status             TEXT NOT NULL,      -- 'active' | 'suspended'
      version            INT NOT NULL DEFAULT 1,
      created_at         TIMESTAMPTZ NOT NULL
    );
    
    -- Humans who log into the ad manager UI (agency buyers, brand marketers — NOT streaming viewers)
    CREATE TABLE console_user (
      user_id            BIGINT PRIMARY KEY,
      email              TEXT NOT NULL UNIQUE
    );
    
    -- N:M join table: one agency buyer manages many advertisers; one advertiser has many staffers
    CREATE TABLE advertiser_member (
      advertiser_id      BIGINT NOT NULL REFERENCES advertiser(advertiser_id),
      user_id            BIGINT NOT NULL REFERENCES console_user(user_id),
      role               TEXT NOT NULL,      -- 'admin' | 'editor' | 'viewer' | 'billing'
      PRIMARY KEY (advertiser_id, user_id)
    );
    
    CREATE TABLE campaign (
      campaign_id        BIGINT PRIMARY KEY,
      advertiser_id      BIGINT NOT NULL REFERENCES advertiser(advertiser_id),
      name               TEXT NOT NULL,
      objective          TEXT NOT NULL,      -- 'awareness' | 'reach' | 'conversions'
      status             TEXT NOT NULL,      -- 'draft' | 'active' | 'paused' | 'completed'
      start_at           TIMESTAMPTZ NOT NULL,
      end_at             TIMESTAMPTZ NOT NULL,
      budget_type        TEXT NOT NULL,      -- 'lifetime' | 'daily'
      budget_micros      BIGINT NOT NULL,    -- NOTE: target cap only; live spend is NOT stored here!
      click_window_days  SMALLINT NOT NULL DEFAULT 7,  -- attribution look-back for clicks
      view_window_days   SMALLINT NOT NULL DEFAULT 1,  -- attribution look-back for impressions
      version            INT NOT NULL DEFAULT 1,
      updated_at         TIMESTAMPTZ NOT NULL
    );
    
    CREATE TABLE line_item (
      line_item_id       BIGINT PRIMARY KEY,
      campaign_id        BIGINT NOT NULL REFERENCES campaign(campaign_id),
      advertiser_id      BIGINT NOT NULL REFERENCES advertiser(advertiser_id),
      name               TEXT NOT NULL,
      status             TEXT NOT NULL,      -- 'draft' | 'active' | 'paused'
      start_at           TIMESTAMPTZ NOT NULL, -- validated inside [campaign.start_at, campaign.end_at]
      end_at             TIMESTAMPTZ NOT NULL,
      bid_cpm_micros     BIGINT NOT NULL,    -- price per 1,000 impressions in micros
      budget_micros      BIGINT,             -- NULL means share the parent campaign's budget
      impression_goal    BIGINT,             -- set for guaranteed reservation deals
      pacing             TEXT NOT NULL,      -- 'even' | 'asap'
      priority           SMALLINT NOT NULL,  -- e.g., 1 = guaranteed deal, 10 = open auction
      freq_cap_count     INT,                -- e.g., max 3 impressions...
      freq_cap_window_s  INT,                -- ...per 86,400 seconds (24 hours)
      version            INT NOT NULL DEFAULT 1,
      updated_at         TIMESTAMPTZ NOT NULL
    );
    
    CREATE TABLE audience_segment (
      segment_id          BIGINT PRIMARY KEY,
      owner_advertiser_id BIGINT REFERENCES advertiser(advertiser_id), -- NULL = platform segment
      name                TEXT NOT NULL,
      source              TEXT NOT NULL,     -- 'platform_interest' | 'advertiser_crm' | 'lookalike'
      min_size            INT NOT NULL,      -- privacy floor (e.g., >= 1,000 profiles) to prevent singling out
      size_estimate       INT,
      consent_purpose     TEXT NOT NULL,     -- e.g., 'personalized_ads'
      expires_at          TIMESTAMPTZ
    );
    
    -- 1:N from line_item: normalized targeting predicates (OR within same dimension, AND across dimensions)
    CREATE TABLE targeting_rule (
      line_item_id       BIGINT NOT NULL REFERENCES line_item(line_item_id),
      dimension          TEXT NOT NULL,      -- 'country' | 'region' | 'device_type' | 'os' | 'genre'
                                             -- | 'maturity_rating' | 'daypart' | 'audience_segment'
      value              TEXT NOT NULL,      -- e.g., 'US', 'tv', 'comedy', or segment_id as text
      is_exclude         BOOLEAN NOT NULL DEFAULT FALSE,
      PRIMARY KEY (line_item_id, dimension, value)
    );
    
    CREATE TABLE creative (
      creative_id        BIGINT PRIMARY KEY,
      advertiser_id      BIGINT NOT NULL REFERENCES advertiser(advertiser_id),
      name               TEXT NOT NULL,
      format             TEXT NOT NULL,      -- 'video' | 'pause_screen' | 'interactive_qr'
      duration_ms        INT,
      current_version    INT NOT NULL
    );
    
    -- Immutable versions: editing a landing URL or swapping video creates version + 1 for fresh review
    CREATE TABLE creative_version (
      creative_id        BIGINT NOT NULL REFERENCES creative(creative_id),
      version            INT NOT NULL,
      landing_url        TEXT,
      advertiser_domain  TEXT NOT NULL,
      category           TEXT NOT NULL,      -- IAB category for policy & competitive separation
      review_status      TEXT NOT NULL,      -- 'pending' | 'approved' | 'rejected'
      review_reasons     TEXT[],
      reviewed_at        TIMESTAMPTZ,
      PRIMARY KEY (creative_id, version)
    );
    
    -- Raw uploaded master ('mezzanine') and transcoded playback files ('rendition') in object storage
    CREATE TABLE asset (
      asset_id           BIGINT PRIMARY KEY,
      advertiser_id      BIGINT NOT NULL REFERENCES advertiser(advertiser_id),
      kind               TEXT NOT NULL,      -- 'mezzanine' | 'rendition' | 'companion_image' | 'captions'
      parent_asset_id    BIGINT REFERENCES asset(asset_id),
      storage_uri        TEXT NOT NULL,      -- e.g., 's3://ads-media/...' (media bytes never live in SQL)
      sha256             BYTEA NOT NULL,
      mime_type          TEXT,
      width              INT,
      height             INT,
      bitrate_kbps       INT,
      duration_ms        INT
    );
    
    -- N:M between creative_version and asset (e.g., one brand logo asset reused across 20 creatives)
    CREATE TABLE creative_asset (
      creative_id        BIGINT NOT NULL,
      version            INT NOT NULL,
      asset_id           BIGINT NOT NULL REFERENCES asset(asset_id),
      role               TEXT NOT NULL,      -- 'primary_video' | 'companion_banner' | 'brand_logo'
      PRIMARY KEY (creative_id, version, asset_id),
      FOREIGN KEY (creative_id, version) REFERENCES creative_version(creative_id, version)
    );
    
    -- N:M between line_item and creative (campaign service verifies matching advertiser_id on write)
    CREATE TABLE line_item_creative (
      line_item_id       BIGINT NOT NULL REFERENCES line_item(line_item_id),
      creative_id        BIGINT NOT NULL REFERENCES creative(creative_id),
      weight             INT NOT NULL DEFAULT 1, -- relative rotation share (e.g., 70 vs 30 for A/B creative test)
      start_at           TIMESTAMPTZ,
      end_at             TIMESTAMPTZ,
      PRIMARY KEY (line_item_id, creative_id)
    );
    

    Three critical schema decisions to highlight: 1. Why spent_micros is NOT in campaign or line_item: live spend updates up to 15,000 times per second. Updating a PostgreSQL row on every impression would cause crippling row-lock contention and couple ad serving to the intake database. Spend lives in a separate stream-aggregated counter store instead. 2. Why targeting_rule uses rows instead of a JSON column: rows allow B-tree indexing on (dimension, value) so inventory forecasting and policy tools can instantly answer "which active line items target teenagers or alcohol categories in Canada?". (If database-enforced foreign keys are required specifically for segments so nobody deletes an in-use segment, split segments into a dedicated line_item_segment(line_item_id, segment_id REFERENCES audience_segment, is_exclude) table.) 3. Why creative_version is immutable: if an advertiser changes a creative's landing URL, the new version enters 'pending' review while the previous 'approved' version keeps serving seamlessly, and historical impression logs pointing to (creative_id, version) remain 100% auditable.

  5. Data model: privacy-isolated viewer state and delivery logs

    To enforce privacy by construction, we physically separate who the subscriber is (in a locked-down Privacy Vault database) from what the ad system sees (a random UUID ad_profile_id with zero link to names, emails, or billing cards):

    -- PRIVACY VAULT (isolated database, strict IAM, never directly reachable by ad servers)
    CREATE TABLE ad_identity (
      account_id     BIGINT NOT NULL,        -- streaming subscription account
      profile_id     BIGINT NOT NULL,        -- individual household viewer profile
      ad_profile_id  UUID   NOT NULL UNIQUE, -- randomly generated UUID (NOT a hash of profile_id!)
      valid_from     TIMESTAMPTZ NOT NULL,
      valid_to       TIMESTAMPTZ,            -- set when viewer resets ad ID or opts out
      PRIMARY KEY (account_id, profile_id, valid_from)
    );
    
    -- Normalized email hashes for matching advertiser conversion uploads inside the vault
    CREATE TABLE match_key (
      key_type       TEXT  NOT NULL,         -- e.g., 'sha256_email'
      key_hash       BYTEA NOT NULL,
      account_id     BIGINT NOT NULL,
      PRIMARY KEY (key_type, key_hash)
    );
    
    CREATE TABLE consent (
      account_id     BIGINT NOT NULL,
      profile_id     BIGINT NOT NULL,
      purpose        TEXT NOT NULL,          -- 'personalized_ads' | 'measurement' | 'advertiser_matching'
      granted        BOOLEAN NOT NULL,
      jurisdiction   TEXT NOT NULL,          -- e.g., 'EU_GDPR', 'US_CA'
      source         TEXT NOT NULL,          -- 'onboarding_banner' | 'privacy_settings' | 'region_default'
      updated_at     TIMESTAMPTZ NOT NULL,
      PRIMARY KEY (account_id, profile_id, purpose)
    );
    

    Outside the vault, the ad server reads two low-latency key-value stores partitioned by ad_profile_id, while all playback and conversion events flow into append-only logs and OLAP rollups:

    KEY-VALUE STORES (read by ad servers in < 2 ms; partitioned by ad_profile_id)
      ad_profile_store
        key:   ad_profile_id
        value: {country, region, language, coarse_age_band?, is_kids_profile,
                consent_bits, segment_ids: [int64, ...], updated_at}
               (Note: ~1.5B profile-segment memberships live here as compact sorted arrays,
                NOT as a 1.5B-row SQL table, because serving always looks up all segments for ONE viewer!)
    
      frequency_cap_store (TTL = max cap window, e.g., 30 days)
        key:   ad_profile_id
        value: {line_item_id -> [recent_impression_epoch_seconds]}
    
    APPEND-ONLY DELIVERY LOGS (Kafka topics -> partitioned Parquet/Iceberg lake tables)
      ad_decision   decision_id, decision_ts, ad_profile_id, device_type, os, country, region,
                    content_id, genre, break_position, config_version,
                    slots: [{impression_id, line_item_id, creative_id, creative_version,
                             price_cpm_micros, cost_nanos}]
      impression    impression_id (= decision_id + ":" + slot_idx), server_ts, client_ts,
                    ad_profile_id, advertiser_id, campaign_id, line_item_id,
                    creative_id, creative_version, cost_nanos, currency,
                    country, device_type, genre, is_valid_traffic
      progress      impression_id, quartile (25 | 50 | 75 | 100), server_ts
      click         click_id, impression_id, server_ts
      conversion    conversion_id, advertiser_id, external_event_id, event_type,
                    value_micros, event_ts, source ('api'|'upload'|'pixel'),
                    matched_ad_profile_id (NULL until batch vault match)
      attribution   conversion_id, touch_type ('click'|'view'), touch_id (click_id or impression_id),
                    model ('last_touch' | 'linear'), credit_fraction (sums to 1.0), attributed_at
    
    OLAP REPORTING ROLLUP (ClickHouse / Druid / Pinot)
      delivery_15m  advertiser_id, campaign_id, line_item_id, creative_id,
                    bucket_start_utc (15-min interval), country, device_type,
                    impressions, valid_impressions, completes_q100, clicks, spend_nanos,
                    unique_viewers_hll (HyperLogLog sketch for fast approximate distinct counts)
    

    Why impressions are denormalized (copying advertiser_id, campaign_id, cost_nanos, and creative_version) and rolled up into 15-minute UTC buckets: - Denormalizing avoids joining 2 billion log rows per day against PostgreSQL, and preserves historical truth as of serving time even if an advertiser later edits or renames a line item. - Using 15-minute UTC buckets instead of hourly buckets allows exact daily reporting for every time zone on Earth, including 30-minute and 45-minute offsets such as India (UTC+5:30) and Nepal (UTC+5:45).

    Relationship Cardinality Physical representation
    agency -> advertiser 1:N (optional) Nullable foreign key advertiser.agency_id
    advertiser <-> console_user N:M Join table advertiser_member(advertiser_id, user_id, role)
    advertiser -> campaign -> line_item 1:N, 1:N Foreign keys + advertiser_id copied down for tenant sharding
    line_item -> targeting_rule 1:N Composite PK (line_item_id, dimension, value)
    line_item <-> creative N:M Join table line_item_creative with rotation weight
    creative -> creative_version <-> asset 1:N, N:M Immutable creative_version rows + creative_asset join table
    viewer <-> audience_segment N:M (~1.5B pairs) Embedded segment_ids[] array inside ad_profile_store
    decision -> impression -> progress/click 1:N, 1:N Deterministic impression_id chain minted at decision time
    conversion <-> impression/click N:M attribution rows carrying credit_fraction
  6. High-level architecture and the three flows

     Advertiser UI / API                         Video Player (TV, mobile, web)
            |                                       | 1. ad request       | 2. beacons (/t/imp...)
            v                                       v                     v
     +---------------+  Outbox/CDC   +-------------------+     +---------------------+
     | Campaign Svc  |-------------->| Kafka: config-chg |     | Tracking Collector  |
     | (validate &   |               +---------+---------+     | (verify HMAC token, |
     |  review flow) |                         v               |  drop IP after geo) |
     +-------+-------+               +-------------------+     +----------+----------+
             |                       | Index Builder     |                v
             v                       | -> snapshot v123  |     +---------------------+
     +---------------+               +---------+---------+     | Kafka: ad-events    |
     | Config SQL DB |                         | push (30-60s) | (key = decision_id) |
     | (PostgreSQL)  |                         v               +----+-----------+----+
     +---------------+               +-------------------+          |           |
                                     | Ad Servers        |          v           v
      +----------------+  KV read    | (in-RAM bitmaps,  |   +-----------+ +----------------+
      | Ad Profile KV  |<------------|  pacing, ranking) |   | Stream    | | Data Lake      |
      +----------------+             +----+---------+----+   | Processor | | (Iceberg by    |
      +----------------+  KV read         |         |        | (dedup,   | |  date/hour)    |
      | Freq-Cap KV    |<-----------------+         |        |  spend,   | +-------+--------+
      +----------------+                            |        |  freq KV) |         v
      +----------------+  poll every ~2s            |        +-----+-----+ +----------------+
      | Spend Counters |<---------------------------+              |       | Batch Jobs     |
      | (sharded KV)   |<------------------------------------------+       | (attribution,  |
      +----------------+                                                   |  final billing)|
      +----------------+  batch hashed-email lookup                        +-------+--------+
      | Privacy Vault  |<----------------------------------------------------------+
      +----------------+                                                           v
                                                                     +----------------------+
                                                                     | OLAP 15m Rollups     |
                                                                     +----------------------+
    

    How the schema powers each flow end to end: 1. Intake flow: Campaign Svc validates invariants (e.g., line-item flight sits inside campaign flight, targeting values exist) and commits the config rows plus a transactional outbox row (an event record written in the exact same SQL transaction so a crash can never commit to the DB without publishing to Kafka). CDC (change data capture, a process tailing the database write-ahead log) streams that change to config-chg. Media uploads go directly to object storage via pre-signed URLs, trigger transcoding into multiple bitrates (asset rows), and await policy approval on creative_version. 2. Serving flow: Index Builder compiles all active, approved, unexhausted line items into an immutable in-memory snapshot every 30–60 seconds and pushes it to Ad Servers. At ad-break time, an ad server performs zero SQL queries: it evaluates targeting in RAM, makes two parallel key-value reads by ad_profile_id (Ad Profile KV and Freq-Cap KV), checks locally cached Spend Counters (polled every ~2 seconds), logs an ad_decision message to Kafka keyed by decision_id, and returns the selected ad pod with HMAC-signed tracking_tokens. 3. Tracking flow: video players call /t/imp, /t/q25, etc. Tracking Collector verifies the HMAC signature, converts the client IP to (country, region) + fraud score in memory (discarding the raw IP), and writes to ad-events keyed by decision_id. Because ad_decision and all beacons for its impressions share the same decision_id partition key, the Stream Processor co-locates them on the same worker without a network shuffle, enriches beacons with ad_profile_id from ad_decision, deduplicates retries, updates Spend Counters, Freq-Cap KV, and OLAP 15m Rollups, and lands raw events in Iceberg. Nightly batch jobs run conversion attribution and finalize billing.

  7. Deep dive 1: compiling targeting rows into an inverted index

    At prime-time peak, each ad server must check 500,000 active line items in ~1 millisecond. Scanning 500,000 rule sets per request is far too slow. Instead, Index Builder assigns active line items dense integer slots 0 .. N-1 and compiles targeting_rule rows into an inverted index (a lookup structure mapping each attribute value, such as country=US, to the set of line items matching it) stored as compressed bitmaps (such as Roaring bitmaps, compact bit arrays where bitwise AND, OR, and AND NOT check thousands of line items in a single CPU instruction).

    Trace how 4 tiny line items compile and match a request {country: {"CA"}, genre: {"sci_fi"}}:

    Line items:
      0: country IN ('CA', 'US'), genre IN ('sci_fi')
      1: country IN ('CA')                             (no genre rule -> any genre is fine!)
      2: country NOT IN ('US')                         (exclude-only rule -> any country EXCEPT 'US'!)
      3: country IN ('JP'),       genre IN ('sci_fi')
    
    Compiled bitmaps per dimension:
      country:
        no_include_rule: {2}            <-- Line item 2 has NO positive country include rule!
        include['CA']:   {0, 1}
        include['US']:   {0}
        include['JP']:   {3}
        exclude['US']:   {2}
      genre:
        no_include_rule: {1, 2}         <-- Line items 1 and 2 accept any genre
        include['sci_fi']: {0, 3}
        exclude:         {}
    
    Matching request {country: {'CA'}, genre: {'sci_fi'}}:
      1. country allowed = no_include_rule {2}    | include['CA'] {0, 1}    = {0, 1, 2}
      2. genre allowed   = no_include_rule {1, 2} | include['sci_fi'] {0,3} = {0, 1, 2, 3}
      3. AND across dims = {0, 1, 2} & {0, 1, 2, 3}                         = {0, 1, 2}
      4. Subtract excludes for 'CA' and 'sci_fi' (none)                     = {0, 1, 2} -> Eligible!
    

    Notice why tracking no_include_rule explicitly is critical: line item 2 (country NOT IN ('US')) has an exclude rule on country and zero include rules on country. Putting 2 into no_include_rule lets it pass step 1 for all countries, and exclude['US'] removes it only when the viewer is in the United States!

    def eligible_line_items(all_line_items, index, request):
        """Return the set of line_item ordinals matching all targeting rules.
    
        all_line_items: set of all active, servable line_item ordinals (0 .. N-1).
        index[dim]: {
            "no_include_rule": set of ordinals with zero positive include rules on dim,
            "include": {value: set of ordinals including value},
            "exclude": {value: set of ordinals excluding value},
        }
        request[dim]: set of attribute values present on this ad request (e.g., {"CA"}).
        """
        # Start with every servable line item; each dimension narrows this set via AND.
        candidates = set(all_line_items)
    
        # Phase 1: within one dimension, values are ORed together (plus line items with no include rule).
        for dim, posting in index.items():
            allowed_for_dim = set(posting["no_include_rule"])
            for value in request.get(dim, set()):
                allowed_for_dim |= posting["include"].get(value, set())
            candidates &= allowed_for_dim
            if not candidates:
                return set()
    
        # Phase 2: any matching exclude rule on any dimension disqualifies the line item.
        for dim, posting in index.items():
            for value in request.get(dim, set()):
                candidates -= posting["exclude"].get(value, set())
    
        return candidates
    

    After bitmap matching narrows 500,000 line items down to a few hundred candidates, the ad server finishes selection in order: 1. Exact flight check: verify start_at <= now < end_at in RAM so campaigns start and stop to the exact second even between 60-second snapshots. 2. Consent-by-omission: if the viewer has not granted 'personalized_ads' consent (or is using a kids profile), Ad Profile KV returns an empty segment_ids list. Every line item requiring an audience_segment include rule automatically fails Phase 1 — consent is enforced by data absence, not fragile if statements! 3. Frequency cap & pacing: filter out line items exceeding the viewer's Freq-Cap KV history, then probabilistically throttle line items running ahead of their smooth daily pacing curve. 4. Auction & pod assembly: rank remaining candidates by priority (guaranteed reservations beat auction bids) then bid_cpm_micros, greedily pack the break up to max_ads and max_duration_ms while skipping any candidate whose category duplicates an ad already placed in the pod (competitive separation), and pick an approved creative version weighted by line_item_creative.weight.

  8. Deep dive 2: tracking deduplication, exact spend, and privacy-safe attribution

    Deterministic ID chain & streaming deduplication Smart TVs and mobile apps frequently lose Wi-Fi and retry beacons hours later. Because the ad server mints decision_id at serving time and sets impression_id = f"{decision_id}:{slot_index}" before returning the response, every retry of the same playback event carries the exact same impression_id. Inside the Stream Processor (partitioned by decision_id), each worker keeps a compact 8-bit bitmask per impression_id (1 bit each for imp, q25, q50, q75, q100, click) in RocksDB state with a 72-hour TTL: - 400M impressions/day * 3 days = 1.2B keys -> ~25 GB of state sharded across stream workers. - If bit imp is already 1, the duplicate beacon is dropped immediately. Events arriving more than 72 hours late go to a late_events lake table reconciled by the nightly billing batch.

    Zero-truncation integer spend (cost_nanos) and budget caps Look closely at CPM arithmetic: if bid_cpm_micros is the price per 1,000 impressions in microdollars (10^-6 USD), dividing bid_cpm_micros // 1000 on every impression would truncate up to 999 microdollars whenever an auction clears at a fractional cent CPM (losing up to $500 across a million impressions!). Instead, express single-impression cost in nanodollars (10^-9 USD, where 1 microdollar = 1,000 nanodollars):

    1,000 impressions cost  price_cpm_micros  microdollars
                          = price_cpm_micros * 1,000  nanodollars
    Therefore:
        1 impression costs  price_cpm_micros  nanodollars  (exact integer, ZERO division!)
    
    Example: $25.00 CPM -> price_cpm_micros = 25,000,000
             1 impression adds 25,000,000 nanodollars (= $0.025) to spend_nanos.
    

    The stream processor increments sharded Spend Counters keyed by (line_item_id, advertiser_local_date) and (campaign_id, advertiser_local_date) (plus lifetime keys). Because ad servers poll these counters every ~2 seconds, a fast-spending campaign can overshoot its budget_micros by a few seconds of traffic during peak hours. Two mechanisms protect the advertiser: smooth pacing throttles delivery as remaining budget shrinks, and the billing pipeline hard-caps invoice charges at budget_micros, so the platform absorbs any tiny lag overrun.

    Privacy-safe conversion attribution & GDPR deletion 1. Advertisers upload conversions with an idempotency key external_event_id and a normalized SHA-256 hashed_email. 2. A batch service sends hashed_email to the Privacy Vault, which joins match_key -> ad_identity -> consent inside the vault and returns only the ad_profile_ids on that account that granted 'advertiser_matching' consent. 3. In the data lake, both impression/click tables and matched conversion rows (~5M/day) are hash-bucketed into N buckets by ad_profile_id, turning the look-back join (click_window_days, view_window_days) into a fast bucket-by-bucket local join with no cluster-wide shuffle. Last click wins over last view. Advertisers see only aggregated conversion counts in reports (with cells suppressed below a privacy threshold such as 50 unique viewers). 4. Right-to-erasure (deletion) & ID rotation: when a user resets their ad ID, the vault sets valid_to = now() on the old ad_identity row and mints a fresh random UUID, making future logs unlinkable to past logs. On an account deletion request, the vault immediately deletes the ad_identity and match_key rows (severing all linkability at once) and enqueues an audited background job (received -> vault_deleted -> kv_deleted -> lake_deleted) that deletes ad_profile_id from the KV stores and runs targeted Iceberg row-level deletes using the ad_profile_id buckets. Aggregated delivery_15m rollups contain no viewer IDs and remain intact for financial auditing.

  9. Indexing, partitioning, failure handling, and trade-offs

    Exact indexing & partitioning strategy - PostgreSQL (Config DB): - campaign(advertiser_id, status) and line_item(campaign_id): fast advertiser console list pages. - Partial index line_item(end_at) WHERE status = 'active': lets Index Builder scan only active line items in milliseconds. - targeting_rule(dimension, value): powers inventory forecasting and policy sweeps. - line_item_creative(creative_id): finds affected line items immediately when a creative is rejected. - UNIQUE (advertiser_id, sha256) on asset: deduplicates re-uploaded video files per advertiser. - Data lake (Iceberg) & OLAP (delivery_15m): - Lake tables are partitioned by (event_date, event_hour) in UTC (so 90-day retention drops whole partitions cleanly and time-bounded attribution reads only relevant days), bucketed by ad_profile_id (for shuffle-free attribution joins and fast GDPR deletes), and sorted within Parquet files by (advertiser_id, campaign_id) so billing queries skip irrelevant Parquet row groups via min/max column statistics. - OLAP delivery_15m is partitioned by day and sorted by (advertiser_id, campaign_id, line_item_id, bucket_start_utc) so single-advertiser dashboards scan one contiguous range.

    Failure handling - PostgreSQL intake outage: ad creation/editing fails gracefully, while ad servers continue serving the last compiled in-memory snapshot with zero user-facing impact (and still stop expiring flights on the exact second via end_at). Urgent legal or brand-safety stops bypass the DB via a lightweight compacted Kafka kill-switch topic read directly by ad servers. - Corrupted index snapshot: Index Builder sanity-checks every new snapshot against the prior version (blocking sudden drops or spikes in active spend capacity); ad servers retain the previous snapshot in RAM for instant rollback, and config_version on ad_decision pinpoints affected impressions. - Stream processor lag: spend counters carry a watermark timestamp; if lag exceeds a threshold (e.g., 15 seconds), ad servers conservatively tighten pacing on campaigns near their budget limit rather than risking uncapped overspend. - Collector / network blips: players buffer beacons locally and retry with exponential backoff; HMAC verification + 72-hour impression_id bitmask dedup + nightly lake reconciliation guarantee accurate billing.

    Summary of core design choices - Three specialized physical stores (SQL config + KV viewer state + Kafka/Iceberg/OLAP logs) add operational pipelines (CDC, index builder, stream processor) in exchange for sub-20 ms serving and zero lock contention at 75,000 events/s. - Normalized config + denormalized logs keeps edits consistent at intake while freezing historical serving truth for fast, join-free reporting. - Privacy Vault + random ad_profile_id isolates personal identity from every ad table, making consent enforcement, ID rotation, and deletion tractable at billion-event scale.

Intuition & how it works

Think of an advertising platform like running a national restaurant chain that relies on three completely different notebooks: a menu binder (updated occasionally by managers, requiring strict proofreading and approval: advertisers, campaigns, budgets, creatives, and targeting rules), a guest-preferences card file at the host stand (looked up in a split second by a guest number when someone walks in: viewer segments and how many times they already saw a specific ad today), and a cash-register receipt roll (printing tens of thousands of lines per second and never erased, only totaled up for accounting: impressions, video progress beacons, clicks, and purchases).

Trying to store all three notebooks inside one standard relational database fails quickly at streaming scale. Updating a budget_spent column or inserting 75,000 playback beacons per second creates heavy row-lock contention that stalls advertisers trying to edit campaigns, while joining five normalized targeting tables across 500,000 line items on every video ad break takes hundreds of milliseconds instead of the 20-millisecond latency budget. Worse, putting real subscriber account IDs or emails directly into billion-row delivery logs makes privacy rotation and data-deletion requests slow and error-prone.

Walk through one concrete cycle to see how splitting the logical model across three purpose-built stores solves all three problems: 1. Intake (PostgreSQL -> compiled snapshot): Advertiser "Summit Sportswear" creates a campaign ($2,000 daily budget) and a line item (a buying rule bidding $25.00 CPM, meaning $25.00 per 1,000 impressions, targeting country = CA and genre = sci_fi, capped at 2 views per viewer per day). Every 30–60 seconds, an index builder compiles active PostgreSQL rows into compressed in-memory bitmaps (Snapshot v123) and pushes them to ad servers. 2. Serving (RAM + Key-Value lookups): A viewer known inside the ad system only by random UUID ad_profile_id = v-4b8e hits an ad break during a Canadian sci-fi episode. The ad server intersects the CA and sci_fi bitmaps in under 1 ms, reads v-4b8e's segments and frequency history (0 < 2) from key-value stores, mints decision_id = dec-204 and impression_id = dec-204:0, and returns the video URL with a signed tracking_token. 3. Tracking & Attribution (Kafka -> Stream -> Lake/Vault): When playback starts, the TV fires /t/imp twice due to a Wi-Fi retry. A stream worker partitioned by decision_id checks a 72-hour deduplication bitmask for dec-204:0, counts only the first beacon, adds 25,000,000 nanodollars ($0.025, exact integer math with zero division) to Summit's daily spend counter, and updates v-4b8e's frequency count to 1. That night, Summit uploads a purchase with a SHA-256 hashed email; an isolated Privacy Vault maps that hash to v-4b8e (after verifying matching consent), and a bucketed lake join attributes the purchase to impression dec-204:0.

Key trade-offs

  • One logical schema split across three physical stores vs. a single relational database. Configuration lives in PostgreSQL for ACID transactions (atomic, consistent database writes), viewer state lives in a distributed key-value store for single-key millisecond reads, and delivery logs flow through Kafka into a columnar data lake (Parquet/Iceberg) plus OLAP (online analytical processing, fast column-oriented analytics) rollup tables. Running three storage tiers requires CDC (change data capture, streaming committed SQL changes to Kafka) and stream processors, which is extra operational complexity in exchange for isolating 75,000 tracking writes/s from both advertiser edits and sub-20 ms ad serving.
  • Targeting stored as normalized SQL rows vs. a JSON expression blob. Storing one targeting_rule(line_item_id, dimension, value, is_exclude) row per criterion lets B-tree indexes answer forecasting and policy queries (such as "who targets Canada?") and lets intake validate values against reference tables. A JSON blob supports arbitrary nested AND/OR trees in a single column write, whereas fixed semantics (OR within a dimension, AND across dimensions, exclude wins) cover almost all ad buying cleanly and compile directly into inverted-index bitmaps (lookup bit arrays mapping each attribute value to matching line items).
  • Denormalized impression logs vs. query-time joins to configuration. Copying advertiser_id, campaign_id, line_item_id, creative_version, and cost_nanos onto every impression event uses extra storage bytes (which compress 5–7x in columnar Parquet files). In return, reporting queries never join 2 billion daily events against PostgreSQL, and historical logs preserve the exact price and parent campaign that were active at serving time even after later edits.
  • Stream-derived spend counters vs. transactional budget decrements. Decrementing a remaining_budget row in PostgreSQL on every impression would turn popular campaigns into lock bottlenecks and take ad serving down whenever the database hiccups. Asynchronous stream counters lag behind reality by 2–5 seconds, risking slight budget overspend at peak traffic; smooth pacing (throttling ad selection probability as remaining budget nears zero) shrinks the gap, and capping the billed invoice at budget_micros guarantees the advertiser never pays for the overrun.
  • Periodic push-compiled serving snapshots vs. live database reads. Pushing an immutable snapshot every 30–60 seconds means a newly paused campaign may serve for up to a minute, unless stopped immediately via a lightweight emergency kill-switch Kafka topic. That 60-second propagation delay buys millisecond in-memory decisions and 100% serving uptime during config-database maintenance.
  • Pseudonymous ad_profile_id behind a Privacy Vault vs. subscriber account IDs in ad tables. Routing conversion matching and deletions through an isolated vault adds an extra service boundary, yet guarantees zero personal data inside ad servers or lake logs, makes ad-ID resets a single row update (valid_to = now()), and confines identity access to one heavily audited database.
  • 15-minute UTC rollup buckets vs. hourly buckets. Fifteen-minute buckets produce 4x as many rows in delivery_15m as hourly buckets, which pays off by allowing exact daily totals in every advertiser local time zone, including 30- and 45-minute UTC offsets like India (UTC+5:30) and Nepal (UTC+5:45).

Common mistakes

  • Putting a mutable spent_micros column directly on campaign or line_item: updating relational config rows thousands of times per second creates severe lock contention and mixes high-rate event state with human-edited configuration.
  • Querying PostgreSQL or joining SQL targeting tables on the live ad-serving path: scanning relational tables across 500,000 line items blows past the 20 ms serving budget and makes the config DB a single point of failure.
  • Using floating-point types for money or truncating sub-cent CPMs: floats introduce binary rounding drift (0.1 + 0.2 != 0.3), and integer-dividing fractional cpm_micros // 1000 loses up to 999 micros per impression; use integer micros for budgets and integer nanodollars (10^-9) for per-impression spend.
  • Logging raw subscriber IDs, email addresses, IP addresses, or GPS coordinates in impression tables: use a random vault-mapped ad_profile_id and discard client IP addresses after deriving coarse (country, region) and invalid-traffic flags in memory.
  • Modeling viewer-to-segment membership (~1.5B pairs) as a SQL join table read at serving time: ad serving always fetches all segments for a single viewer, so store segment_ids[] directly inside that viewer's key-value profile record.
  • Minting event IDs at collection time instead of decision time: without a deterministic decision_id -> impression_id chain created before playback, player retries create duplicate billable impressions and clicks cannot reliably link back to views.
  • Mutating creatives in place instead of versioning them (creative_version): overwriting a creative's video or URL bypasses policy re-review and destroys auditability for what viewers actually saw last week.
  • Partitioning billion-row delivery logs by advertiser_id instead of event time: retention drops, 7-day attribution windows, and late-event restatements all need time partitions (event_date, event_hour), with advertiser_id handled via OLAP rollups and intra-file Parquet sort keys.

Follow-up questions

  • How would you extend the schema to support upfront guaranteed reservation deals alongside open-auction line items? Add a reservation_deal table linked 1:N to line_item, storing a contracted impression_goal, fixed cpm_micros, penalty terms for under-delivery, and a higher priority tier (for example priority = 1 vs. priority = 10 for auction ads). Before intake allows a salesperson to book a deal, an inventory forecasting service samples historical ad_decision logs matching the proposed targeting_rule set to estimate available future impressions per day and subtracts already-booked reservations so inventory is not oversold. At serving time, reserved line items get first claim on matching breaks whenever their pacing schedule says they need impressions to hit impression_goal evenly by end_at.
  • How should daily budget caps and smooth pacing handle advertiser time zones and Daylight Saving Time transitions? Every advertiser row stores an explicit IANA time_zone (such as 'America/Toronto'), and stream-aggregated daily spend counters are keyed by (line_item_id, advertiser_local_date) computed by converting the impression's UTC server timestamp into that zone. On spring-forward and fall-back DST transition days, the local calendar day lasts 23 hours (82,800 seconds) or 25 hours (90,000 seconds) rather than 86,400 seconds, so the pacing curve divides budget_micros across the actual UTC duration of that local day. For reporting, summing delivery_15m buckets between the local midnight-to-midnight UTC timestamps produces exact daily spend in every time zone.
  • What changes if advertisers want frequency caps enforced across a whole household TV rather than per viewer profile? Introduce a second random pseudonymous identifier in the Privacy Vault, ad_household_id (mapped 1:1 to account_id with its own valid_from/valid_to rotation lifecycle and consent check), and allow line_item to specify freq_cap_scope as 'profile', 'household', or both. During an ad break, the ad server fetches frequency histories for both ad_profile_id and ad_household_id in one batched key-value lookup, disqualifying the line item if either counter hits its cap. Because ad_household_id links activity across family members sharing an account, it requires explicit privacy-policy disclosure and must be rotated and purged alongside ad_profile_id on deletion requests.

Follow-up questions

Similar questions

More Netflix interview questions

All 97 Netflix questions →