System Design

C16

Stream processing with exactly-once

A stream processor runs one query forever: count events per key per minute. Tasks fail, workers are added, data arrives late. The results must still count each event once.

Not startedSaved in this browser only.
  1. 1Partition by key. One task owns all state of a key, and state is saved per key group so it can move.
  2. 2Barriers flow with the records. Each task saves its state when a barrier has come in on every input, so offsets and state describe one cut.
  3. 3Recovery restores the last complete checkpoint and replays. Output is exactly once only if the sink commits with the checkpoint or overwrites by key.
  4. 4Bounded buffers slow the sources when a task falls behind. A hot key limits what more tasks can do.
C16
    A

    The prompt

    as the interviewer says it
    "Design a stream processor that aggregates events by key over windows, with results that stay exactly-once after failures."
    questionanswer assumed
    How many events?300,000 a second on average, 1,000,000 at peak.
    How many keys?1,000,000 active in any minute.
    Which windows?Tumbling, 1 minute, by event time.
    Where do results go?A table that dashboards read.
    What is exactly once?Each event counts once in the table after any failure.
    Failures?Any task or worker can die at any time.
    Task speed?50,000 events a second per task, from a benchmark of the job.

    I confirm the rate, the number of keys, the window and what exactly once must mean for the output.

    B

    Requirements

    as numbers
    functional
    Run a graph of keyed operators over a partitioned log.
    Count per key per window; roll up per window.
    Recover from a failure without losing or doubling a result.
    Change the parallelism without losing state.
    non-functionaltarget
    Window end to result in the tablep99 < 15 s
    Results lost or doubled0
    Back to live after a task failure< 2 min
    Checkpoint interval10 s

    I promise exactly once in the output table, not exactly-once delivery inside the job. Inside, a replay reads some events twice.

    C

    Estimates

    the arithmetic, on the board
    quantityarithmeticresult
    Tasks1,000,000/s ÷ 50,000/s per task = 2032, for headroom; 64 log partitions
    Key groupsthe default floor of 1284 per task; rescale up to 128 tasks
    Keyed state1,000,000 keys × 2 open windows × 64 B128 MB; 4 MB per task
    Output rows1,000,000 rows a minute ÷ 60≈ 17,000/s; 2 sink connections at 14,000/s each
    Replay after a crash10 s interval × 1,000,000/sup to 10 M events read again
    Catch-up(30 s down + 10 s) × 1,000,000/s ÷ (32 × 50,000 − 1,000,000)/s spare≈ 67 s

    Inputs are the answers in panel A. Sink speed measured in the lab at 1,000 rows per commit. The 128-group floor is the documented default of one stream processor. Method: R2.

    At 1,000,000 events a second and 50,000 per task, I run 32 tasks. After a crash the job catches up in about 67 s with that headroom.

    D

    API

    the job, and the calls that run it
    callforsuccesserrors
    POST /v1/jobs {graph, parallelism}deploy201 + job_id400 bad graph
    POST /v1/jobs/{id}/savepointsa checkpoint to keep202 + savepoint_id409 one running
    POST /v1/jobs/{id}/rescale {parallelism}stop with a savepoint, start wider202400 above max
    GET /v1/jobs/{id}/checkpointssize, duration, last complete200404
    DELETE /v1/jobs/{id}?savepoint=truestop safely202 + savepoint_id404
    the jobpseudo code
    job page_counts:
      source  events, partitions 64, event time from the record
      key by  page1
      window  tumbling 1 minute; count
      key by  window2
      rollup  per window: total and per page
      sink    output table, exactly once3
      checkpoint every 10 s; max parallelism 1284
    1. 1A shuffle: every record goes to the task that owns its page.
    2. 2A second shuffle, so one task sums each window over all pages.
    3. 3The sink commits with each checkpoint. Panel J shows the other choices.
    4. 4The number of key groups. It is fixed for the life of the state.

    The job is a graph declared in code. The control calls deploy it, take savepoints and change the parallelism from a savepoint.

    E

    Data model

    the graph, the state, the output
    As writtenthe logical graphSourcelog partitionskey by pageCountper page, 1 minkey by windowRollupper windowforwardSinkoutput tableAs it runsparallelism 2, 8 key groupsS0partition 0S1partition 1A0key groups 0 to 3A1key groups 4 to 7B0key groups 0 to 3B1key groups 4 to 7Sinkone transactionA record goes to task (key group × parallelism ÷ 8): one owner per key.
    storekeyholds
    State backendkey group, page, windowThe count and the count last sent
    State backendkey group, window, pageThe rollup: each page's count and the total
    Checkpointscheckpoint, operator, taskOffsets, watermarks, state files per key group
    the output tablesql
    -- The output of the keyed job: one row per key per window, read by a dashboard. A row keyed
    -- "total" holds the window's total. The commits table holds the last checkpoint each job
    -- committed, in the same transaction as its rows.
    CREATE TABLE graph_out (
      job          text NOT NULL,
      key          text NOT NULL,
      window_start int  NOT NULL,
      n            int  NOT NULL,
      PRIMARY KEY (job, key, window_start)1
    );
    CREATE TABLE graph_commits (
      job        text PRIMARY KEY,
      checkpoint int  NOT NULL2
    );
    1. 1One row per key per window, so a result can be written again by key.
    2. 2Commits with the rows. After a restore it says which checkpoint the table already holds.

    State is keyed by key group, key and window. The output table has one row per window and key, and a row that records the last committed checkpoint.

    F

    The architecture

    click a step; its path lights up
    Event logpartitionsCoordinatorjob managerSource tasksone per slotCount taskskeyed by pageState backendmemory, local diskRollup taskskeyed by windowSink tasktwo-phase commitCheckpoint storageobject storageOutput tablewindow, key

    Step 1: Submit

    • The coordinator turns the job into tasks: one per operator per parallel slot.
    • It places tasks on workers and connects every keyed exchange all to all.
    • With no checkpoint, sources start at the offsets the job names.

    If it fails

    A worker is missing: the coordinator waits for slots, or starts at a lower parallelism from the last checkpoint.

    Sources read partitions, keyed tasks hold state, barriers cut a consistent checkpoint, and the sink commits when the checkpoint completes. Recovery and rescaling both start from a checkpoint.

    G

    Capabilities used

    what each tool gives you
    toolcapabilitywhat it gives this designalso used for
    FlinkkeyBy, key groups, max parallelismOne owner per key; state that splits by group. Max parallelism has a floor of 128 by default.Joins, sessions
    FlinkState backends: heap or embedded RocksDB, incremental checkpointsState larger than memory; checkpoints upload only changed files.Large joins
    FlinkAligned and unaligned checkpointsA consistent cut while the job runs. Unaligned ones pass full buffers. Checkpoints are off by default.Savepoints
    FlinkTwo-phase-commit sinksOutput commits only when the checkpoint completes.Files, Kafka, databases
    FlinkCredit-based flow control, buffer debloatingBounded buffers between tasks; a slow task slows its senders.Any pipeline
    KafkaOffsets, retentionRestore seeks back to the saved offsets and reads again.Backfills
    KafkaTransactions; consumers with isolation.level = read_committedOutput to a topic appears to readers only at the commit. The default level reads uncommitted data.Read-process-write
    Kafka StreamsState stores with changelog topics, standby replicasState restored from a topic; a standby shortens the restore. Standbys are 0 by default.Microservice aggregates
    PostgresA transaction over rows and a checkpoint markerThe lab's sink: rows and the checkpoint ID commit together.Outbox, ledgers
    PostgresINSERT ... ON CONFLICT DO UPDATEAn idempotent sink: a replayed result writes the same value.Upserts

    Flink gives me keyed state in key groups, barrier checkpoints and two-phase-commit sinks. Kafka gives me offsets to replay and transactions for output.

    H

    Deep dive: checkpoints with barriers

    a consistent cut without stopping
    methodstatuswhy
    Commit offsets, state in memory onlyNot approvedA crash loses or repeats counts (B7).
    Stop the world, save, resumeSmall jobs onlyEvery task pauses on every checkpoint.
    Aligned barriersApprovedA consistent cut while records flow.
    Unaligned barriersUnder backpressureFast, but in-flight records join the checkpoint.
    Commit after every recordNot approved2,800 results a second in the lab, against 14,000 in batches of 1,000.
    • This is the Chandy-Lamport snapshot, applied to a graph with no cycles: the barrier is the marker.
    • Saving a part is quick: the task copies a reference, and uploads in the background.
    • A source's part is its offset and watermark, so the cut also says where to read again.
    barrier alignmentpseudo code
    on item x from input i:
      IF x is barrier n:
        hold input i                        // its later records wait here1
        IF every input has brought barrier n:
          flush buffers; save keyed state as part n2
          send barrier n on every output3
          release every input; report part n saved
      ELSE IF input i is not held: process x
    
    coordinator, every INTERVAL:
      inject barrier n into each source, which saves its offset4
      when every part n is saved: checkpoint n is complete5
    1. 1Records after the barrier belong to the next checkpoint. Processing them now would put them in this one.
    2. 2Anything buffered outside keyed state is sent first, so the saved part is complete.
    3. 3Downstream tasks align on it the same way.
    4. 4The source part. A restore seeks back here.
    5. 5Only now may sinks commit the output that came before barrier n.
    Tested source Go: align and save
    Go: align and savego
    // alignID runs when barrier id has arrived on every input: save state, pass the barrier on.
    func (r *Runner) alignID(ctx context.Context, c *Ctx, id int) error {
      t := c.t
      for j := range t.in.blocked {
        t.in.blocked[j] = false
      }
      if t == r.sink {
        if err := r.cfg.Sink.PreCommit(ctx, id); err != nil {
          return fmt.Errorf("sink pre-commit %d: %w", id, err)
        }
        r.log("sink", fmt.Sprintf("barrier %d on every input: output since barrier %d staged, not committed", id, id-1), "save")
        return r.ack(ctx, id)
      }
      t.op.Flush(c)
      snap := r.partial[id]
      if snap == nil {
        return fmt.Errorf("barrier %d has no checkpoint", id)
      }
      n := 0
      for g, m := range t.state.clone() {
        snap.State[t.stage][g] = m
        n += len(m)
      }
      r.broadcast(t.stage+1, t.index, item{kind: kBarrier, id: id})
      r.log(t.name, fmt.Sprintf("barrier %d on every input: save %d state values, pass the barrier on", id, n), "save")
      return r.ack(ctx, id)
    }
    

    Barriers mark a cut in every stream. A task with several inputs holds each input until the barrier arrives on all of them, then saves its state.

    I

    See it: barriers, a crash and recovery

    recorded: 76 steps of a two-stage job
    step 1 of 76, tick 0
    jump to
    sourcescount, keyed by pagerollup, keyed by windowtwo-phase-commit sinkfrom S0from S1from S0from S1from A0from A1from A0from A1from B0from B1Source 0next offset 012 page viewsSource 1next offset 012 page viewsA0wm noneno stateA1wm noneno stateB0wm noneno stateB1wm noneno stateSinkwm none0 results held0 rows committedno checkpoint runningnone complete yetchips: c10 = cart at 10 s, h=2 = home counted 2, w12 = watermark 12, B1 = barrier 1; the oldest item is nearest its task

    This tick

    Items move one hop; nothing else happens.

      Output table: 0 of 15 rows

      windowkeyclicks
      nothing committed yet

      Checkpoint 1 completed and its rows committed. The crash came with checkpoint 2 half saved and 1 result not committed; the restore replayed from checkpoint 1 and the table ended equal to a batch count.

      J

      Deep dive: exactly-once sinks

      recorded: a crash between checkpoints
      sinktasksreplayedclicks shownstatus
      add255652 of 60012 rows wrong
      overwrite255600 of 600Approved
      two-phase commit255600 of 600Approved
      add467652 of 60012 rows wrong
      overwrite467600 of 600Approved
      two-phase commit467600 of 600Approved
      • Each run read 600 events from 4 partitions and crashed after the sink had received 12 results past the last checkpoint.
      • Overwrite needs results that are absolute counts by key. Readers can see a count step back during the replay.
      • Two-phase commit delays output by up to one interval. Its transaction must outlive the interval plus a recovery.
      a two-phase-commit sinkpseudo code
      write(r):        add r to the open set           // not visible yet1
      on barrier n:    close the open set as part of n // phase 12
      on complete n:   BEGIN
                         write every row of n
                         mark (job, n) as committed3
                       COMMIT                          // phase 2
      on restore:      drop what no complete checkpoint covers4
      1. 1Readers see nothing of this checkpoint until phase 2.
      2. 2The barrier splits the output: rows before it belong to checkpoint n.
      3. 3In the same transaction as the rows. A restore can tell which checkpoints the table holds.
      4. 4The replay produces those rows again.
      Tested source Go: the sink · SQL: add, overwrite, mark
      Go: the sinkgo
      // Write sends a result. The two direct modes write at once; two-phase commit holds it.
      func (s *PGSink) Write(ctx context.Context, r Rec) error {
        switch s.Mode {
        case SinkAdd:
          return s.exec(ctx, gq["add"], r.Key, r.At, r.D)
        case SinkPut:
          return s.exec(ctx, gq["put"], r.Key, r.At, r.N)
        case SinkTx:
          s.open = append(s.open, r)
          return nil
        }
        return fmt.Errorf("unknown sink mode %q", s.Mode)
      }
      
      // PreCommit is phase 1: the barrier reached the sink, so every result before it belongs to
      // checkpoint id.
      func (s *PGSink) PreCommit(_ context.Context, id int) error {
        if s.Mode == SinkTx {
          if s.staged == nil {
            s.staged = map[int][]Rec{}
          }
          s.staged[id], s.open = s.open, nil
        }
        return nil
      }
      
      // Commit is phase 2: checkpoint id is complete, so its results commit in one transaction with
      // the checkpoint id.
      func (s *PGSink) Commit(ctx context.Context, id int) error {
        if s.Mode != SinkTx {
          return nil
        }
        var rows []Rec
        for _, k := range slices.Sorted(maps.Keys(s.staged)) {
          if k <= id {
            rows = append(rows, s.staged[k]...)
            delete(s.staged, k)
          }
        }
        return s.commit(ctx, id, rows)
      }
      
      // Abort runs on a restore: results that no complete checkpoint covers are thrown away. The
      // replay from the checkpoint's offsets produces them again.
      func (s *PGSink) Abort(context.Context) error {
        s.open, s.staged = nil, nil
        return nil
      }
      
      SQL: add, overwrite, marksql
      -- At least once: add the change. A replayed result adds again.
      INSERT INTO graph_out (job, key, window_start, n) VALUES ($1, $2, $3, $4)
      ON CONFLICT (job, key, window_start) DO UPDATE SET n = graph_out.n + EXCLUDED.n;
      
      -- Idempotent: write the absolute count. A replayed result writes the same value.
      INSERT INTO graph_out (job, key, window_start, n) VALUES ($1, $2, $3, $4)
      ON CONFLICT (job, key, window_start) DO UPDATE SET n = EXCLUDED.n;
      
      -- Two-phase commit, phase 2: the rows of a checkpoint and its id commit together.
      INSERT INTO graph_commits (job, checkpoint) VALUES ($1, $2)
      ON CONFLICT (job) DO UPDATE SET checkpoint = EXCLUDED.checkpoint;

      With the same crash, a sink that adds showed 652 clicks for 600. A sink that overwrites by key, or commits with the checkpoint, showed exactly 600.

      K

      Deep dive: rescaling state

      recorded: 2 tasks to 4
      checkpoint 1, count stage: clicks in open windows, by key groupparallelism 2, task 0: 14parallelism 2, task 1: 44group 0promo 1share 1task 0 → 0group 1search 8task 0 → 0group 2help 3login 1task 0 → 1group 3emptytask 0 → 1group 4deals 4orders 4saved 2track 1task 1 → 2group 5emptytask 1 → 2group 6home 22item 5task 1 → 3group 7cart 6task 1 → 3task 0: 10task 1: 4task 2: 11task 3: 33parallelism 4: 9 of 12 keys change task; 58 clicks in state before and afterafter the restore: 600 of 600 clicks in the output, 0 rows wrong
      methodstatuswhy
      hash(key) mod tasks, state per taskNot approvedA new task count rehashes every key; state must be split key by key.
      Key groups, a range per taskApprovedWhole groups move; each task reads a few files.
      Consistent hashing of keys to tasksState moved key by keyFew keys move, but each must be found and copied.
      restore at a new parallelismpseudo code
      key_group(key) = hash(key) mod MAX_PARALLELISM1
      task(group, p)  = group * p / MAX_PARALLELISM   // a range per task2
      
      restore(checkpoint c, parallelism p):
        each source seeks to c.offset and resends c.watermark3
        FOR EACH task t of p:
          load every key group g with task(g, p) = t  // whole groups4
        each sink drops output that c does not cover
        run: records after c.offset are read again
      1. 1Fixed for the life of the job. Choose it larger than any parallelism you will need.
      2. 2At 2 tasks: groups 0 to 3 and 4 to 7. At 4 tasks: two groups each.
      3. 3A replayed late record is judged against the same watermark as before the crash.
      4. 4The lab moved 15 saved values this way; every count stayed the same.
      Tested source Go: key groups · Go: restore
      Go: key groupsgo
      // KeyGroup returns the key group of a key.
      func KeyGroup(key string) int {
        h := fnv.New32a()
        h.Write([]byte(key)) // hash.Hash.Write never returns an error
        return int(h.Sum32() % MaxParallelism)
      }
      
      // TaskOf returns the task that owns a key group: each task owns one contiguous range of groups.
      func TaskOf(group, parallelism int) int { return group * parallelism / MaxParallelism }
      
      Go: restorego
      // Restore starts a job from a complete checkpoint. The stage parallelism in cfg may differ from
      // the job that took the checkpoint: each task loads the key groups it owns now. The sink drops
      // output that no complete checkpoint covers.
      func Restore(ctx context.Context, cfg GraphConfig, s *Snapshot) (*Runner, error) {
        if s == nil {
          return nil, errors.New("restore: no complete checkpoint")
        }
        if err := cfg.Sink.Abort(ctx); err != nil {
          return nil, fmt.Errorf("restore: abort the sink: %w", err)
        }
        return start(cfg, s)
      }
      
      func start(cfg GraphConfig, s *Snapshot) (*Runner, error) {
        if len(cfg.Log) == 0 || len(cfg.Stages) == 0 || cfg.Sink == nil || cfg.Cap < 1 || cfg.WMEvery < 1 {
          return nil, fmt.Errorf("bad job config: %d partitions, %d stages, cap %d, watermark every %d", len(cfg.Log), len(cfg.Stages), cfg.Cap, cfg.WMEvery)
        }
        if cfg.Rate == 0 {
          cfg.Rate = 1
        }
        r := &Runner{cfg: cfg, pending: map[int]int{}, partial: map[int]*Snapshot{}, Counters: map[string]int{}, nextID: 1}
        for i := range cfg.Log {
          src := &source{index: i, maxSeen: math.MinInt, wm: math.MinInt}
          if s != nil {
            src.off, src.maxSeen, src.wm = s.Offsets[i], s.MaxSeen[i], s.WM[i]
          }
          r.sources = append(r.sources, src)
        }
        inputsOf := len(cfg.Log)
        for si, st := range cfg.Stages {
          if st.Parallelism < 1 || st.Parallelism > MaxParallelism {
            return nil, fmt.Errorf("stage %s: parallelism %d, want 1 to %d", st.Name, st.Parallelism, MaxParallelism)
          }
          var tasks []*task
          for ti := range st.Parallelism {
            t := &task{name: fmt.Sprintf("%s%d", st.Name, ti), stage: si, index: ti, op: st.New(), state: keyed{}, in: newInputs(inputsOf), wm: math.MinInt}
            if s != nil {
              for g, m := range s.State[si] {
                if TaskOf(g, st.Parallelism) == ti {
                  t.state[g] = maps.Clone(m)
                }
              }
            }
            tasks = append(tasks, t)
          }
          r.stages = append(r.stages, tasks)
          inputsOf = st.Parallelism
        }
        r.sink = &task{name: "sink", stage: len(cfg.Stages), in: newInputs(inputsOf), wm: math.MinInt}
        if s != nil {
          r.nextID = s.ID + 1
          r.latest = s
          // Each source sends its saved watermark before any record, so a replayed record is
          // judged late or on time against the same watermark as before the crash.
          for _, src := range r.sources {
            if src.wm != math.MinInt {
              r.broadcast(0, src.index, item{kind: kWM, wm: src.wm})
            }
          }
        }
        return r, nil
      }
      

      To rescale, I take a savepoint and restart at the new parallelism. Each task loads a range of key groups: 9 of 12 keys moved, and the output matched.

      L

      Deep dive: backpressure and skew

      recorded: the same log at 1, 2 and 4 tasks
      tasks per stagetickssource ticks stalledbusiest task
      19032,846600 of 600
      26601,823417 of 600
      45471,311329 of 600
      • Each task moves one item a tick, and a channel holds 4. A full channel stops its sender, back to the sources.
      • Fix skew with partial counts per task before the shuffle (C15), or salt the hot key.
      • Watch buffer use and checkpoint duration. Rising alignment time means backpressure.

      More tasks helped less each time: one page is hot, and at 4 tasks one task got 55% of the records. A job runs at the speed of its busiest task.

      M

      Late data and watermarks

      event time in a parallel job
      casewhat to do
      Watermark of a taskThe smallest watermark of its inputs.
      A partition goes quietMark it idle after a timeout, so it does not hold the watermark.
      A record behind the watermarkUpdate the window within the allowed lateness; else a side output.
      A restoreResend the saved watermark before the replay.
      A rescaleWatermarks restart from the savepoint; windows stay in keyed state.

      Windows, delay and lateness, with a recorded run: B7.

      Each task's watermark is the smallest of its inputs. A quiet partition holds every window back, so I mark idle sources.

      N

      Failure cases

      what breaks, and what keeps the output right
      eventresultwhy it is safesaved by
      A task dies between checkpointsThe job restarts from the last complete checkpoint.State, offsets and committed output all describe that checkpoint.Checkpoint
      A crash with a checkpoint half savedThat checkpoint is dropped.Only complete checkpoints are restored; the sink never committed its rows.Two-phase commit
      The sink adds per result652 clicks shown for 600.Not safe. Overwrite by key, or commit with the checkpoint.Upsert
      A transaction times out before its checkpoint completesThe broker aborts it.Not safe: that output is lost. Set the timeout above interval plus recovery.Timeout
      A checkpoint takes longer than the intervalCheckpoints queue or fail.The job keeps running; replays grow. Find the backpressure, or use unaligned checkpoints.Unaligned
      A worker is lost for goodIts tasks have nowhere to run.Restore from the checkpoint at a lower parallelism; key groups spread over fewer tasks.Key groups
      One key gets most eventsOne task falls behind; sources stall.Pre-aggregate per task, then combine.Two-phase sum
      The checkpoint store is downCheckpoints fail.The job runs on; a crash now replays from an older checkpoint. Alert on checkpoint age.Alert
      O

      Scale ladder

      start simple; climb only on a signal
      Each step adds one component1One consumer, one transaction2Partitions, keyed tasks3+ barrier checkpoints4+ disk state, incremental5+ standbys, unalignedmore load →
      Measured rates and this prompt's demand1k10k100k1M10MDemand: events, peak: 1,000,000 events or results per secondDemand: events, peak1,000,000Demand: output rows: 16,667 events or results per secondDemand: output rows16,667Sink, 1 per commit: 2,849 events or results per secondSink, 1 per commit2,849Sink, 100 per commit: 12,431 events or results per secondSink, 100 per commit12,431Sink, 1,000 per commit: 13,986 events or results per secondSink, 1,000 per commit13,986Job logic, one goroutine: 460,371 events or results per secondJob logic, one goroutine460,371events or results per second, log scale
      stepaddit handlesmove up when you see
      1One consumer: counts in memory, saved with the offset in one transaction (B7).About 14,000 results a second at 1,000 per commit, in the lab.One process cannot keep up, or its state outgrows memory.
      2Partitions and keyed tasks, each with its own state.Rate grows with tasks until one key dominates. The keyed logic ran 460,000 records a second here.A crash in one task corrupts the others' view of progress.
      3Barrier checkpoints and a two-phase-commit sink.Exactly-once output after any failure; replay up to one interval.State no longer fits in memory, or checkpoints take too long to copy.
      4State on local disk with incremental checkpoints.State far larger than memory; each checkpoint uploads changed files only.Restores take minutes; checkpoints stall under backpressure.
      5Standby state and unaligned checkpoints.Fast failover; checkpoints that pass full buffers.Top of the ladder.

      Demand from panel C. Rates measured with one client on one 8-core laptop, Postgres 16, median of 3 runs; read them as orders of magnitude. The job logic number is the lab's engine on one goroutine, with no network and no serialization.

      I start with one consumer and a transactional sink. When state or rate outgrows it, I move to a stream processor with keyed state and barrier checkpoints, then add standby state and unaligned checkpoints.

      P

      Follow-ups

      what the interviewer asks next
      questionanswerdeeper
      How do windows decide they are complete?A watermark trails the newest event time; a window fires when the watermark passes its end. Late records update it within a bound.B7
      How do you choose the number of partitions?At least the largest parallelism you plan, since a partition is read by one task. More partitions later move keys.B6
      Show it on a real prompt.Ad clicks: a seen set per user, partial counts for the hot ad, and a batch recount that makes counts final.C15
      The output feeds payments. Is this enough?Write each result once with an idempotency key into a ledger, and reconcile against the source.T9
      How is a two-phase commit here different from 2PC across services?The coordinator and all participants are one job, and a participant never votes no after it pre-commits. Across services, a participant can refuse.T7
      A key is far hotter than the rest.Split the work with partial counts per task, or salt the key and sum the parts.X2
      What do you alert on?Consumer lag in seconds, checkpoint duration and age, alignment time, and restarts per hour.O3
      Q

      Drill

      predict, then reveal

      0 of 10 known

      1. Why route keys through key groups, and not straight to hash(key) mod tasks?

      2. A task has two inputs. Barrier 3 arrives on one. What does the task do?

      3. The job crashes between checkpoints. What is read again?

      4. The sink adds each result to a counter. What does a crash do?

      5. An overwriting sink and a two-phase-commit sink both ended right. What differs?

      6. Doubling the tasks from 2 to 4 did not halve the run time. Why?

      7. Why do aligned checkpoints get slow under backpressure?

      8. How long should the checkpoint interval be?

      9. The output is a Kafka topic with transactions. What timeout matters?

      10. After a restore, why must the sources resend their saved watermark?

      R

      Numbers to say

      measured, recorded or documented
      replay
      Up to one checkpoint interval: 55 of 600 records in the lab run.
      sinks
      Adding: 652 shown for 600. Overwrite or commit: exactly 600.
      commits
      2,800 results a second at 1 per commit; 14,000 at 1,000.
      rescale
      2 to 4 tasks: 9 of 12 keys moved; 0 rows wrong.
      skew
      One task got 55% of records at 4 tasks.
      key groups
      Max parallelism has a floor of 128 by default, and is fixed once state exists.
      defaults
      Checkpoints off; Kafka readers see uncommitted data; Kafka Streams has 0 standbys.

      Lab engine on one goroutine and Postgres 16 on an 8-core laptop, median of 3 runs. Defaults from the Flink and Kafka documentation.