System Design

C15

Ad-click aggregation

Every click on an ad costs the advertiser money, so each click must count once, in the minute it happened. The stream gives counts within seconds; the raw log gives the final answer.

Not startedSaved in this browser only.
  1. 1Log every click with a click ID and its event time. Counts are derived data; the log can rebuild them.
  2. 2Drop repeats with a seen set keyed by user, cap clicks per user, then count per ad per minute by event time.
  3. 3Exactly-once counts need the seen set and the counts in the checkpoint, and a sink that commits with it.
  4. 4The stream is fast but not final. A batch recount over the raw log corrects late clicks and late repeats.
C15
    A

    The prompt

    as the interviewer says it
    "Design a pipeline that counts ad clicks per ad per minute, in near real time, with totals that are correct."
    questionanswer assumed
    How many clicks?1 billion a day. Peak is 5 times the average.
    How many ads?2 million. 200,000 get a click in a given minute.
    How fresh?A minute's count shows within 30 s after the minute ends.
    How correct?Each click counts once. Invoices use final counts, at most a day old.
    Late clicks?Most within seconds. Offline phones send up to 24 hours late.
    Repeats?Phones and servers retry, so one click can arrive twice.
    Fraud?Clicks over a cap per user per ad per minute are not billed.
    Queries?Per-minute charts for one ad; top ads for an advertiser.

    First I confirm what a click is, how late clicks can come, and which numbers are for dashboards and which are for invoices.

    B

    Requirements

    as numbers
    functional
    Record a click and redirect to the landing page.
    Count clicks per ad per minute, without repeats and fraud.
    Chart one ad by minute; list top ads in a time range.
    Mark each count as provisional or final.
    non-functionaltarget
    Redirect latencyp99 < 50 ms
    Minute end to count shownp99 < 30 s
    Click lost or counted twice in final counts0
    Final counts availablewithin 1 h, rechecked daily
    Raw log kept7 days in the log, 2 years archived

    Dashboards can show a provisional count; invoices must use a count that a recount of the raw log confirms.

    C

    Estimates

    the arithmetic, on the board
    quantityarithmeticresult
    Clicks1 B a day ÷ 86,400≈ 12,000/s; 5× peak ≈ 58,000/s
    Raw log1 B × 200 B200 GB a day; 7 days × 3 copies = 4.2 TB
    Ingest bandwidth58,000/s × 200 B≈ 93 Mbit/s at peak
    Seen set58,000/s × 190 s kept × 72 B (measured)≈ 11 M IDs, 0.8 GB over all tasks
    Minute rows200,000 active ads × 1,440 minutes288 M rows a day; × 32 B ≈ 9.2 GB before compression
    Row writes200,000 rows each minute ÷ 60≈ 3,300/s into the OLAP table

    Inputs are the answers in panel A. The seen set keeps an ID for the watermark delay (10 s), the lateness (120 s) and the minute (60 s). Bytes per ID measured in a Go map. Method: R2.

    Clicks average about 12,000 a second and peak near 58,000. The table gains about 288 million minute rows a day.

    D

    API

    endpoints, status codes, retries
    callforretry safe bysuccesserrors
    GET /c/{signed_click_id}a click on an ad linkthe click ID302 to the landing page400 bad signature
    POST /v1/clicks [{click_id, ad_id, ts}]batched clicks from an appthe click IDs202400, 429
    GET /v1/ads/{id}/clicks?from&to&step=1ma charta read200 + points, each final or not400, 403
    GET /v1/advertisers/{id}/top-ads?from&to&limit=10a leaderboarda read200 + ads, clicks400, 403
    • The ad server signs the click ID when it shows the ad. A forged or replayed link fails the check or repeats a known ID.
    • Each point carries final: true once the batch recount has written it.

    The click endpoint never waits for counting. A retried click carries the same click ID, so the pipeline drops the repeat.

    E

    Data model

    one shape per store
    storekeyholdskept
    Click loguserclick_id, ad, user, event time7 days
    Job stateuser, click_idThe seen set: event time of each click ID190 s
    Job stateuser, ad, minuteClicks so far, for the fraud capuntil the minute closes
    Job statead, minuteThe count, and the count last sentuntil the minute closes
    OLAP tablead, minuteClicks; who wrote it last90 days; hour rollups 2 years
    Raw archivehourColumnar files of the raw log2 years
    • The log is keyed by user, so every copy of a click reaches the task that holds its user's seen set.
    • A minute "closes" when the watermark passes its end plus the lateness.
    the OLAP tablesql
    -- The OLAP table: clicks per ad per minute. The stream job writes each minute; the batch recount
    -- overwrites closed minutes. A column store holds the same shape, sorted by (ad, minute).
    CREATE TABLE ad_clicks_minute (
      ad     text        NOT NULL,
      minute timestamptz NOT NULL,
      clicks bigint      NOT NULL,
      source text        NOT NULL CHECK (source IN ('stream', 'batch'))2,
      PRIMARY KEY (ad, minute)1
    );
    CREATE INDEX ad_clicks_by_minute ON ad_clicks_minute (minute, ad);3
    
    -- The last checkpoint the stream job committed, in the same transaction as its rows.
    CREATE TABLE ad_sink_commits (
      job        text PRIMARY KEY,
      checkpoint int  NOT NULL4
    );
    1. 1One row per ad per minute. A chart for one ad is one range of this key.
    2. 2Who wrote the row last. Batch rows are final; the stream never overwrites them.
    3. 3Top ads in a time range: read a range of minutes, sum per ad.
    4. 4The last checkpoint committed, written in the same transaction as its rows.

    The log holds raw events keyed by user. The job holds a seen set and counters per user. The OLAP table holds one row per ad per minute.

    F

    The architecture

    click a step; its path lights up
    Browser, appclicks an adClick service302, log eventClick logkeyed by userStream jobclean, countCheckpointsoffsets, stateRaw archivefiles per hourBatch recountevery hourOLAP tablead, minuteDashboardadvertiserQuery APIcharts, top ads

    Step 1: Click

    • The ad link carries a signed click ID, made when the ad was shown.
    • The service checks the signature, appends the event to the log keyed by user, and returns 302 to the landing page.
    • The event holds the click ID, ad, user, and the event time from the device.

    If it fails

    The log is slow: the service buffers events locally and returns the redirect anyway. A retry sends the same click ID, so the job drops it.

    The click service logs the event and redirects. The stream job cleans and counts by event time and commits with each checkpoint. An hourly batch recount makes the counts final.

    G

    Capabilities used

    what each tool gives you
    toolcapabilitywhat it gives this designalso used for
    KafkaPartitions by key, retention, offsetsEvery copy of a click goes to one partition; a restore or a backfill reads again from an offset.Change data capture
    KafkaIdempotent producer (on by default since 3.0)A producer retry does not write the event twice. Device retries still need the click ID.Any producer
    FlinkKeyed state with a TTLThe seen set and the fraud counters, per user, expired by time.Sessions, joins
    FlinkEvent-time tumbling windows, allowed lateness, side outputsCounts per minute; late updates; very late clicks set aside.Any rollup
    FlinkTwo-phase aggregation (local, then global)Partial counts per task before the shuffle by ad, so the hot ad does not load one task.Skewed group-bys
    FlinkCheckpoints, two-phase-commit sinksState, offsets and output commit at the same point.Exactly-once pipelines
    Column storeSorted by (ad, minute), compressed columns, rollupsSums over millions of rows in milliseconds. A replacing table engine keeps the newest version of a row.Metrics, logs
    SparkBatch jobs over columnar filesThe hourly recount over the raw archive, with every late click in view.Backfills
    PostgresINSERT ... ON CONFLICT with a WHEREThe lab's OLAP table: the stream upserts; it never overwrites a batch row.Idempotent sinks
    Postgresunnest() of arrays in one statementThe reconcile writes a whole hour in one round trip and one transaction.Bulk upserts

    Kafka gives me a replayable log keyed by user. Flink gives me keyed state with a TTL, event-time windows and checkpoints. A column store gives me fast sums over ad and minute.

    H

    Deep dive: repeats and fraud

    before anything is counted
    methodwherestatus
    Count every eventServiceNot approved
    Seen set of click IDs in keyed state, with a TTLFlinkApproved
    Seen set in task memoryServiceNot approved
    Bloom filter of click IDsServiceA false positive drops a real click
    Unique key on click ID in the databasePostgresLow rates: one write per click
    Cap per user per ad per minuteFlinkApproved
    A fraud model scores clicks laterSparkFeeds the recount
    • Key the first stage by user. The seen set and the cap are both per user, so one task owns both.
    • A TTL shorter than the delay plus the lateness lets a late repeat count twice. Panel I shows how many.
    • A Bloom filter saves memory but drops a real click on a false positive (B10).
    the clean stagepseudo code
    on click c, keyed by c.user1:
      IF c.id in seen, not expired: DROP    // a repeat
      seen[c.id] = c.event_time             // expires after TTL2
      n = clicks[c.user, c.ad, minute(c)]
      IF n >= CAP: DROP to the fraud output3
      clicks[c.user, c.ad, minute(c)] = n + 1
      partial[c.ad, minute(c)] += 1         // task memory, not state4
    
    on watermark w:
      SEND partial[ad, m] WHERE m + 60 <= w // keyed by ad
    on barrier:
      SEND every partial, then save seen and clicks5
    1. 1Every copy of a click comes from the same user, so it reaches the same task and the same seen set.
    2. 2Event time, not wall time, so a replay expires the same IDs. The lab kept IDs 30 s.
    3. 3The cap was 3. The bot in the lab clicked 40 times in each of 2 minutes.
    4. 4Partial counts are sent before every barrier, so the checkpoint never needs them.
    5. 5The seen set is state. A restore brings it back with the offsets it matches.
    Tested source Go: the clean stage
    Go: the clean stagego
    // Process handles one click.
    func (s *Clean) Process(c *streams.Ctx, r streams.Rec) {
      id, ad, attempt, err := parse(r.Val)
      if err != nil {
        c.Count("bad", 1) // a malformed event goes to a side output, not a count
        return
      }
      minute := r.At - r.At%Minute
      if s.isSeen(c, r.Key, id) { // 1. a click ID seen before: drop
        c.Count(fmt.Sprintf("dup@%d", minute), 1)
        return
      }
      s.markSeen(c, r.Key, id, r.At)
      f := "f" + ad + "@" + strconv.Itoa(minute) // 2. more than Cap clicks: fraud
      n := c.Get(r.Key, f)
      if s.counterGone(minute, c.Watermark()) {
        n = 0
      }
      if n >= s.Cap {
        c.Count(fmt.Sprintf("fraud@%d", minute), 1)
        return
      }
      c.Set(r.Key, f, n+1)
      if attempt > 1 { // a retry the seen set no longer held: it counts twice
        c.Count(fmt.Sprintf("retry@%d", minute), 1)
      }
      if !s.PreAgg { // 3. one record per click, or one partial count per ad and minute
        c.Emit(streams.Rec{Key: ad, At: minute, N: 1, D: 1})
        return
      }
      if s.partial == nil {
        s.partial = map[[2]string]int{}
      }
      s.partial[[2]string{ad, strconv.Itoa(minute)}]++
    }
    
    // Advance sends the partial counts of closed minutes. Every 10 s of watermark it also deletes
    // expired click IDs and fraud counters, to free memory; reads treat them as gone at once.
    func (s *Clean) Advance(c *streams.Ctx, wm int) {
      s.send(c, func(minute int) bool { return minute+Minute <= wm })
      if wm < s.swept+sweepEvery {
        return
      }
      s.swept = wm
      c.Scan(func(key, name string, v int) {
        switch name[0] {
        case 's':
          if s.idGone(v, wm) {
            c.Del(key, name)
          }
        case 'f':
          _, at, _ := strings.Cut(name, "@")
          if m, err := strconv.Atoi(at); err == nil && s.counterGone(m, wm) {
            c.Del(key, name)
          }
        }
      })
      for id, v := range s.seen {
        if s.idGone(v, wm) {
          delete(s.seen, id)
        }
      }
    }
    
    // Flush sends every partial count before a barrier, so no count lives outside keyed state when
    // the task saves its part of the checkpoint.
    func (s *Clean) Flush(c *streams.Ctx) { s.send(c, func(int) bool { return true }) }
    

    I drop repeats by click ID with a seen set keyed by user, and I cap clicks per user per ad per minute. In the lab that removed 418 repeats and 75 bot clicks.

    I

    See it: stream against batch

    recorded: 6,562 events over 10 minutes
    ads
    stage
    stream minus batch recount, clicks-20-100+10+2012:0012:0112:0212:0312:0412:0512:0612:0712:0812:09
    late retry counted twice click dropped as too late
    minute
    Minute 12:00, all ads
    events in the log621
    repeats the seen set dropped− 43
    clicks over 3 per user per ad− 0
    stream count558
    of which: retries counted twice+ 8
    missing: clicks dropped late− 20
    batch recount570
    after reconciliation-
    totals
    all ads: stream 5,958, batch 6,006
    minutes off
    10 of 10
    hot ad
    ad07 at 12:00: stream 269, batch 275
    rows fixed
    69 of 383 (ad, minute) rows
    settings
    seen set 30 s, delay 10 s, lateness 120 s

    The stream: 5,958 clicks; the batch recount: 6,006. Each minute's stream count equals the batch count plus repeats counted twice, minus late clicks dropped; the lab checks this for every minute.

    The stream was off in 10 of 10 minutes: 63 late repeats counted twice and 111 late clicks dropped. Reconciliation made every minute equal the recount.

    J

    Deep dive: late clicks and the recount

    Lambda, or Kappa
    methodstatuswhy
    Count by arrival timeNot approvedA late click lands in the wrong minute; a replay gives another answer.
    Event time, drop late clicksNot approvedOffline phones are never billed.
    Event time, lateness, updatesApprovedLate clicks within the bound update the minute.
    Hold minutes open for 24 hoursSmall key spaceState for every ad and minute of a day.
    Batch recount overwrites closed hours (Lambda)ApprovedEvery late click and repeat in view. Two code paths.
    Replay the log into a new table (Kappa)Log keeps the rangeOne code path. For bug fixes and rule changes.
    • Both paths must share one rule set for repeats, fraud and minutes. Put it in one library both jobs call.
    • The recount writes the whole hour in one statement. A rerun writes the same values, so it is safe to repeat.
    • More on Lambda, Kappa and backfills: B7.
    the count stagepseudo code
    on partial p, keyed by p.ad:
      IF p.minute + 60 + LATENESS <= watermark:
        DROP to the late output1             // the recount has it
      count[p.ad, p.minute] += p.n
      IF the minute was sent: SEND count    // an update
    
    on watermark w:
      SEND count[ad, m] WHERE m + 60 <= w   // the first result3
      forget m once m + 60 + LATENESS <= w
    1. 1The lab dropped 111 clicks here. The batch recount counts them.
    2. 2The sink overwrites the row with the new absolute count.
    3. 3The watermark trails the newest event by the delay, so a minute is sent soon after it ends.
    Tested source Go: count per key per window
    Go: count per key per windowgo
    // Process adds a record to its window, or drops it when the window's state is gone.
    func (w *WindowCount) Process(c *Ctx, r Rec) {
      start := r.At - mod(r.At, w.Size)
      if start+w.Size+w.Lateness <= c.Watermark() {
        c.Count("late", r.N)
        c.Count(fmt.Sprintf("late@%d", start), r.N)
        return
      }
      n := c.Get(r.Key, "n"+strconv.Itoa(start)) + r.N
      c.Set(r.Key, "n"+strconv.Itoa(start), n)
      if sent := c.Get(r.Key, "e"+strconv.Itoa(start)); sent > 0 {
        c.Emit(w.result(r.Key, start, n, n-sent)) // the window already fired: send an update
        c.Set(r.Key, "e"+strconv.Itoa(start), n)
      }
    }
    
    // Advance fires every window the watermark has passed and forgets windows past their lateness.
    func (w *WindowCount) Advance(c *Ctx, wm int) {
      c.Scan(func(key, name string, n int) {
        start, ok := windowOf(name, "n")
        if !ok {
          return
        }
        if start+w.Size <= wm && c.Get(key, "e"+strconv.Itoa(start)) == 0 {
          c.Emit(w.result(key, start, n, n))
          c.Set(key, "e"+strconv.Itoa(start), n)
        }
        if start+w.Size+w.Lateness <= wm {
          c.Del(key, name)
          c.Del(key, "e"+strconv.Itoa(start))
        }
      })
    }
    
    the hourly recountpseudo code
    every hour, for the hour that closed LATENESS ago:
      clicks = that hour of the raw log, late ones included1
      drop every repeated click ID2          // no TTL here
      apply the same CAP per user per ad per minute
      counts = GROUP BY ad, minute
      IN ONE STATEMENT: write counts, source = 'batch'3
    
    stream sink: never overwrite a 'batch' row4
    1. 1The archive file of an hour is read after the lateness, so clicks that came late are in it.
    2. 2No TTL here: the batch sees the whole hour at once.
    3. 369 of 383 rows changed in the lab.
    4. 4A late stream update after the recount cannot undo a final count.
    Tested source Go: reconcile · SQL: reconcile and the stream sink
    Go: reconcilego
    // Reconcile writes the batch recount over the stream's rows for every minute in [from, to),
    // in one statement. It returns the rows it wrote.
    func Reconcile(ctx context.Context, db *pgxpool.Pool, batch map[Key]int, from, to int) (int64, error) {
      var ads []string
      var minutes []time.Time
      var clicks []int64
      for k, n := range batch {
        if k.Minute >= from && k.Minute < to {
          ads = append(ads, k.Ad)
          minutes = append(minutes, Base.Add(time.Duration(k.Minute)*time.Second))
          clicks = append(clicks, int64(n))
        }
      }
      tag, err := db.Exec(ctx, queries["reconcile"], ads, minutes, clicks)
      if err != nil {
        return 0, fmt.Errorf("reconcile minutes %d to %d: %w", from, to, err)
      }
      return tag.RowsAffected(), nil
    }
    
    SQL: reconcile and the stream sinksql
    -- The batch recount of closed minutes replaces the stream's rows in one statement.
    INSERT INTO ad_clicks_minute (ad, minute, clicks, source)
    SELECT ad, minute, clicks, 'batch'
    FROM unnest($1::text[], $2::timestamptz[], $3::bigint[]) AS b(ad, minute, clicks)
    ON CONFLICT (ad, minute) DO UPDATE SET clicks = EXCLUDED.clicks, source = 'batch';
    
    -- The stream sink, inside the checkpoint's transaction: write the minute's count. A minute the
    -- batch recount has corrected is never overwritten by the stream.
    INSERT INTO ad_clicks_minute (ad, minute, clicks, source) VALUES ($1, $2, $3, 'stream')
    ON CONFLICT (ad, minute) DO UPDATE SET clicks = EXCLUDED.clicks
    WHERE ad_clicks_minute.source = 'stream';

    The stream holds each minute open for 2 minutes. Anything later goes to the recount, which writes final counts over the stream's rows for every closed hour.

    K

    Deep dive: the hot ad

    recorded: one ad has 50% of clicks
    4 tasks per stageno pre-aggregationpartial counts first
    Records into the hot ad's task3,429442
    Source ticks stalled by backpressure1,33575
    Ticks to read the log2,0201,753
    methodstatus
    Key by ad onlyNot approved
    Partial counts per task, then combine by adApproved
    Salt the key: ad plus a number from 0 to 7Needs a second sum

    Each task handles 2 items a tick; a full channel stops its sender. Partial counts are sent when a minute closes and before every barrier.

    Keyed by ad, the hot ad's task fell behind and stalled the sources 1,335 times. Partial counts per task cut its input from 3,429 records to 442.

    L

    Deep dive: a crash between checkpoints

    recorded: restore, replay, compare
    seen set inclicksrecountrows wrong
    Keyed state, in the checkpoint6,0066,0060
    Task memory6,0196,0069
    • The job restored checkpoint 2 and read 804 clicks again. The sink had committed nothing past that checkpoint.
    • This run keeps every ID and accepts every late click, so the only cause of a difference is the crash.
    • Sinks, barriers and rescaling in depth: C16.

    After a crash and restore, the job with the seen set in keyed state matched the recount in all 383 rows. With the seen set in task memory, 9 rows were wrong.

    M

    Failure cases

    what breaks, and why the counts stay right
    eventresultwhy it is safesaved by
    A phone sends a click twiceTwo events, one click ID.The seen set drops the second copy.Seen set
    A repeat arrives after its ID expiredThe stream counts it twice.The recount drops it and overwrites the minute.Recount
    A click arrives hours lateThe stream drops it.It is in the archive; the next daily recount counts it.Recount
    A stream task crashesEvents since the checkpoint are read again.The seen set, counters and sink all roll back to the same checkpoint.Checkpoint
    The sink crashes mid-commitThe transaction rolls back.The checkpoint is not complete; the replay writes the rows again.Transaction
    One ad gets half of all clicksOne count task falls behind; sources stall.Partial counts per task, then one sum per ad.Pre-aggregation
    A bot clicks one ad 40 times a minuteClicks over the cap.The cap drops them to a fraud output for review.Cap
    A device clock is wrong by a dayEvent time far ahead of arrival.Reject or clamp event times more than a few minutes ahead of the receive time.Validation
    The stream job has a counting bugWrong counts for days.Fix it, replay the log into a new table, switch reads (Kappa).Replay
    N

    Scale ladder

    start simple; climb only on a signal
    Each step adds one component1Postgres only2+ log, consumer3+ stream job4+ column store5+ recountmore load →
    Capacity against this prompt's demand1k10k100k1MDemand: clicks, average: 11,574 clicks or rows per secondDemand: clicks, average11,574Demand: clicks, peak: 57,870 clicks or rows per secondDemand: clicks, peak57,870Demand: minute rows: 3,333 clicks or rows per secondDemand: minute rows3,333Postgres: 1 row a commit: 2,849 clicks or rows per secondPostgres: 1 row a commit2,849Postgres: 1,000 rows a commit: 13,986 clicks or rows per secondPostgres: 1,000 rows a commit13,986Postgres: reconcile: 36,668 clicks or rows per secondPostgres: reconcile36,668Click job, one goroutine: 85,151 clicks or rows per secondClick job, one goroutine85,151clicks or rows per second, log scale
    stepaddit handlesmove up when you see
    1One Postgres: insert each click with a unique click ID; GROUP BY ad and minute for charts.About 2,800 clicks a second, one per commit, in the lab.Inserts near that rate, or charts that scan millions of raw rows.
    2A log and one consumer with a seen set, minute counts and a transactional sink.About 14,000 rows a second at 1,000 rows per commit; the counting logic ran 85,000 clicks a second.State outgrows one process, or one consumer falls behind the peak.
    3A stream processor: keyed state, checkpoints, partial counts per task.Add tasks up to the partition count. This prompt's peak is about 58,000 clicks a second.Charts and top-ads queries slow down as rows reach hundreds of millions.
    4A column store sorted by ad and minute, with hour rollups.About 288 M rows a day. In Postgres, top ads over 60,000 rows took 26.8 ms.Invoices need counts that survive late clicks and late repeats.
    5An hourly and a daily recount over the raw archive.Final counts; the reconcile wrote about 37,000 rows a second in one statement.Top of the ladder. Regions next: count per region, then merge.

    Demand from panel C. Lab rates are one client on one 8-core laptop, Postgres 16, median of 3 runs; read them as orders of magnitude. The click job is the lab's engine on one goroutine, not a cluster.

    I start with a table and a GROUP BY. Next comes a log and one consumer with a seen set. Then a stream processor with partial counts and a column store, and a recount on top.

    O

    Follow-ups

    what the interviewer asks next
    questionanswerdeeper
    How does the job stay exactly once after a crash?Barriers save offsets and state at one point, and the sink commits with that checkpoint. A replay then writes nothing twice.C16
    How do watermarks and lateness work?The watermark trails the newest event time by a delay, and a window fires when it passes the end. Lateness keeps the window open for updates.B7
    How many partitions does the log need?At least the number of tasks you will run, with headroom; keys stay on one partition. Adding partitions later moves keys.B6
    Can you save memory on the seen set?A Bloom filter uses a few bits per ID but drops a real click on a false positive. Keep exact IDs for billing.B10
    How do you store minute counts for 2 years?Roll minutes up to hours and days, and drop old minute partitions. Queries pick the coarsest table that answers them.B12
    How do invoices use these counts?Bill from final rows only, and post each invoice line once with an idempotency key into a ledger.T9
    One advertiser's ads are all hot. Now what?Pre-aggregate per task, and salt the key if one ad still exceeds a task. Sum the salted parts in a second step.X2
    How do you know the pipeline is healthy?Alert on consumer lag in seconds, checkpoint age, late-output rate, and the gap between stream and recount per hour.O3
    P

    Drill

    predict, then reveal

    0 of 10 known

    1. A phone sends the same click twice, 4 s apart. What stops a double count?

    2. A retry arrives 90 s after the first copy. The seen set keeps IDs for 30 s. What happens?

    3. A click arrives 4 minutes late. Lateness is 120 s. Where does it go?

    4. Why must the seen set be in the checkpoint?

    5. 50% of clicks are on one ad. What breaks, and what fixes it?

    6. What does reconciliation change, and how often?

    7. Lambda or Kappa for this prompt?

    8. Why key the first stage by user, not by ad?

    9. Why count by event time and not by arrival time?

    10. How do the top-ads queries stay fast?

    Q

    Numbers to say

    derived, measured or recorded
    demand
    About 12,000 clicks a second; 58,000 at a 5× peak.
    seen set
    72 B per ID in a Go map; about 0.8 GB for 190 s at peak.
    rows
    288 M minute rows a day for 200,000 active ads.
    stream off
    63 repeats counted twice and 111 late clicks dropped, of 6,562 events.
    recount
    Changed 69 of 383 rows; reconcile about 37,000 rows a second.
    hot ad
    3,429 records into one task, or 442 with partial counts.
    queries
    One ad, one day: 1.3 ms. Top ads, 60,000 rows: 26.8 ms.

    Lab: Go on one goroutine and Postgres 16 on an 8-core laptop, median of 3 runs. Recorded runs: seed 15, 4 partitions, 4 tasks per stage.