Skip to content
Tech Interview Prep
Technical interview guide

Batch vs. Streaming Processing

Processing data in scheduled chunks versus continuously as it arrives, and the latency/complexity tradeoff.

Minutes to read
3
Practice MCQs
25
Interview Q&A
25
Edition
v5
Editorial status
Reviewed

Scope: Apache Flink stable/current 2026-08-31; Apache Spark 4.2; Apache Beam, Kafka, Iceberg, OpenLineage current 2026-08-31.

Interview Q&A

Treat each question like a live interview question: answer out loud first (structure, assumptions, tradeoffs), then open the model answer to spot gaps and rehearse a tighter follow-up.

Curated: · Written: · Reviewed:

25 questions

Q&A-14

Walk me through how you decide between continuous streaming, micro-batch, and daily batch when designing an ingestion and transformation pipeline.

Answer

The rule I use: pick the coarsest cadence that still meets the tightest consumer SLA, then check that the latency budget actually closes. Finer cadence costs more in every dimension (24/7 headroom, state, operational surface) so streaming is something you pay for with a freshness requirement you can name out loud. If nobody can name the consumer that breaks at 60 seconds, you don't need streaming.

Three questions decide it.

  1. What's the tightest consumer SLA, and what breaks if you miss it? "The fraud decision must land before the card auth completes" (~200 ms) is streaming. "The dashboard refreshes hourly" is not.
  2. Is the transform per-record or global? Map/filter/enrich runs at any cadence. Dedup, sessionization, joins against a slowly-changing dimension, and global ranking want batch or micro-batch, because the shuffle is the cost, not the freshness.
  3. What's the sink's commit model? This often decides it before freshness does.

The latency budget is the artefact that settles arguments. End-to-end freshness = source commit + processing + sink commit, and the floor is set by the coarsest of those, not the fastest.

  • Streaming with an exactly-once sink: the freshness floor is the checkpoint interval, not the per-record processing time. A Flink job with execution.checkpointing.interval = 60s writing to Iceberg through a two-phase-commit sink cannot publish a record faster than ~60 s plus commit latency, however fast the operator is. Teams routinely build a "sub-second" pipeline and ship 60-second freshness because nobody looked at the checkpoint interval.
  • Micro-batch: floor = trigger interval + batch duration. With trigger(processingTime="1 minute"), freshness is ≥ 60 s. If the batch takes 90 s you don't get 90 s freshness: you get unbounded lag, because the next trigger queues behind the running one.
  • Daily batch: floor = schedule time + runtime + upstream arrival. If upstream lands at 02:00 and the job starts at 01:00, you are processing yesterday's partition.

Write that sum down with real numbers and check it against the SLA. It usually eliminates one option immediately.

Failure modes and how I detect them.

ParadigmFailure modeDetection
StreamingCheckpoint timeout under a GC pause → restart from last checkpoint, replay window = checkpoint intervallastCheckpointDuration approaching checkpointInterval; checkpoint size trend
StreamingUnbounded keyed state (no TTL) → RocksDB disk fills, checkpoints slow to a crawlcheckpoint size growing monotonically; state-backend disk usage
Micro-batchtriggerExecution exceeds the trigger interval → lag grows without boundSpark StreamingQueryProgress.durationMs.triggerExecution vs the trigger interval
Micro-batchSmall-file explosion: 1-minute triggers write 1,440 files/day/partitionfile count per partition; compaction-job backlog
Daily batchSkew: one partition runs 10× the median taskSpark stage task-duration histogram; max/median ratio
Daily batchLate-arriving data silently droppedrow count per partition vs upstream source count

Cost, illustrative. 100M events/day at ~1 KB each ≈ 100 GB/day uncompressed → ~1,150 events/s average, 10,000/s peak.

  • Streaming must be sized for peak, not average: 3 × 4-vCPU workers at ~$0.19/hr on-demand ≈ $420/month, plus the log (MSK/Kinesis) and its storage. Call it $500–700/month, running whether or not traffic shows up.
  • Daily batch: 10 spot workers at ~$0.06/hr = $0.60/hr; 12 minutes/day ≈ $0.12/day ≈ $4/month, scaling to zero between runs.

That gap is the whole argument. Streaming buys freshness at roughly 100× the compute cost, so the freshness requirement has to be real.

When not to use each. Don't stream if the SLA is 15 minutes: you're paying 24/7 headroom for nothing. Don't micro-batch if you need sub-second; the trigger interval is a hard floor. Don't daily-batch if consumers need intra-day correction (inventory, fraud, pricing): reprocessing a partition at 03:00 doesn't help at 14:00.

The hybrid I default to: decouple ingest cadence from transform cadence. Stream ingest into the lake with a short commit interval (Kafka → Iceberg, 1-minute commits) so raw data is fresh and replayable, then run transforms at whatever cadence the consumer needs: micro-batch for the hot path, daily for the heavy global joins. One source of truth, and you can move a transform between cadences without re-architecting ingest.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-13

Compare Lambda and Kappa architectures for data pipelines: when is Kappa preferred, and how do you handle historical data reprocessing?

Answer

Lambda splits processing into two paths: an immutable batch layer (e.g., Iceberg or Spark over object storage) computing accurate historical views, and a speed layer (e.g., Flink or Spark Streaming) processing low-latency increments. A serving layer merges both views at query time. Kappa simplifies this into a single stream-processing engine over an append-only, durable log (e.g., Kafka or Kinesis). Everything is an event stream, and batch is treated as a bounded stream over historical offsets.

When Kappa is Preferred

Lambda introduces dual-codebase maintenance: business logic must be implemented twice (or forced into a cross-engine abstraction like Apache Beam) and yields reconciliation divergence between the batch window and streaming state. Kappa is preferred when:

  1. Business logic involves complex event-time state (sessionization, pattern detection, deduplication) that is error-prone to duplicate across disparate engines.
  2. The storage engine can retain raw events long enough for replay, or tier historical logs to object storage transparently.
  3. The streaming engine supports out-of-order event-time processing and watermarking natively (e.g., Apache Flink, Spark Structured Streaming).

Lambda remains necessary only when analytical queries require full-table iterative scans, heavy multi-way ad-hoc joins across petabytes where log replay is cost-prohibitive, or machine learning training loops that require columnar vectorized random access not supported by stream re-read.

Mechanics of Historical Data Reprocessing in Kappa

Reprocessing in Kappa never mutates the active running job in place. The standard pattern is side-by-side blue/green pipeline deployment:

Raw Durable Log (Kafka / Tiered Storage / Iceberg Change-Log)
   |---------------------------------------|
   | (live offsets)                        | (offset 0 / historical)
   v                                       v
[ Streaming Job v1 ]                   [ Streaming Job v2 (Backfill) ]
   |                                       |
   v                                       v
[ Serving Table v1 ]                   [ Serving Table v2 ]
        ^                                   |
        |---- [ Query Router / View Switch ]|<-- (Catch-up complete)
  1. Version and Deploy: Deploy code version 2 (Job v2) as an independent consumer group pointing to offset 0 (or the required historical timestamp/snapshot).
  2. Catch-Up Processing: Job v2 runs with scaled-up parallel task slots. Watermarks advance based on event timestamps in the log rather than processing time, allowing the job to process historical data as fast as I/O allows without artificially throttling for wall-clock time.
  3. Dual-Writing / Isolated Sink: Job v2 writes to an isolated target sink (e.g., metrics_v2 in Iceberg or a distinct key-prefix/database table).
  4. Cutover: Once Job v2 consumes to the head of the log (lag approaches zero and watermarks reach current wall-clock time), switch read traffic via a view or routing layer from v1 to v2.
  5. Teardown: Stop Job v1 and delete Serving Table v1 after a stabilization window.
DimensionLambda ArchitectureKappa Architecture
CodebaseDual (batch engine + streaming engine)Single (unified streaming code)
ConsistencyPotential divergence between speed & batchUnified semantics and state transitions
ReprocessingRun batch job over historical filesReplay log from offset 0 or source snapshot into new job
Storage CostHigh (raw logs + batch store + speed state)Lower (unified durable log / tiered storage)
Operational ComplexityHigh at serving layer (query-time merge)High during backfill (cluster scaling, I/O burst)

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-1

Choose batch, micro-batch, or streaming for a new data product.

Answer

The 90-second answer. Pick the coarsest cadence whose worst-case event-to-decision delay still fits the decision, then verify the pipeline can meet it. Ask what consumes the output and how stale it may be: a daily revenue close tolerates hours, a churn score tolerates a day, a card-authorization block tolerates single-digit milliseconds. Then check what the source can actually give you (event time or only arrival time, replayable log or destructive CDC feed) because that, not the engine choice, sets the correctness floor. Batch when a bounded, complete period is the unit of correctness: replay is a rerun, late data is a re-run of one partition, reconciliation is a diff of two tables. Micro-batch when seconds-to-minutes genuinely helps and bounded increments stay practical. Streaming only when latency changes a fraud, safety, control or personalization outcome, and only if the whole path (source, state, sink, on-call) can sustain it. A hybrid is common and honest: publish a provisional low-latency view from the log, reconcile authoritative history from batch.

CadenceFits whenWhat it actually costs
Batch, hourly or dailythe decision is a close, a report, a retrain; correctness = a complete periodrerun to correct; warehouse resume billing
Micro-batch, 1-60 s triggerseconds-to-minutes freshness, bounded increments, joins you can recomputefixed per-trigger overhead * triggers per day; state grows between triggers
Continuous streaming, sub-secondthe action is taken inside the event: block, alert, reroute, pricestate, watermarks, checkpoint recovery, 24/7 on-call for job and sink

Why the mechanism decides this. In a streaming engine the watermark is the only thing that turns "late" into a decision: a window can wait for more input or fire, and without a bound on out-of-orderness it can only do one or the other. Micro-batch inherits that problem and adds one: state lives across triggers while shuffle fan-out is fixed per trigger, so a 5 s trigger over 200 shuffle partitions is latency-bound, not throughput-bound, and a stateful join grows a state store every trigger.

Worked arithmetic (hypothetical 1 GB/min source, documented defaults). Spark Structured Streaming's default trigger is "as fast as possible" and spark.sql.shuffle.partitions defaults to 200; each micro-batch can therefore write up to 200 files. On a 5 s trigger that is 24 * 60 * 60 / 5 = 17,280 batches/day, up to 17,280 * 200 = 3.46M files/day if the sink never compacts. On Snowflake, AUTO_SUSPEND defaults to 600 s and every resume bills a 60 s minimum: a job that runs every 5 minutes and computes for 20 s bills 12 * 60 = 720 s/hour against 12 * 20 = 240 s of real work, roughly 3x the compute you think you bought. Both are measurable before launch (WAREHOUSE_METERING_HISTORY, files-per-partition metrics).

Failure modes, with the signal that catches them.

FailureSymptomDetectionFix
An idle Kafka partition holds the watermark backwindows never fire, output goes silent for minutescurrentInputWatermark flatlined across all subtasksWatermarkStrategy.withIdleness(...), or table.exec.source.idle-timeout (default 0 = disabled)
Unbounded stateful joincheckpoint size and duration climb each trigger, then task OOMRocksDB state size in checkpoints, checkpoint-duration trendstate TTL, or convert to an interval/append-only join
Checkpoint restore re-emitscounts double after a restartnumRecordsIn after restore vs source offsets; duplicate keys in sinkidempotent or upsert sink chosen before you need it
Batch partition arrives after closetotals short with no errorrow count vs source count reconciliation, freshness SLA alertpartition-overwrite rerun, never append

Write the contract down: maximum lateness before an event is dropped, what the degraded path serves when checkpoints fail, and who is paged. Revisit the cadence when the decision-latency budget changes, not when the platform team ships something new.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-5

Design partitioning and ordering for a keyed event stream.

Answer

First 90 seconds

"Ordered" is not one requirement. I would ask: which events must be ordered relative to each other? Usually it is every event for one entity, an account, an order, a device. That makes order a per-key property, and the design follows from it: key by the narrowest stable entity id, partition by that key, and let the log's per-partition ordering give you per-key order. Global order is off the table unless the consequence justifies it, because it forces one partition, one consumer, and caps throughput at one core.

Assumptions I would state out loud: Apache Kafka 3.x, producers set the key, one consumer group, at-least-once processing with enable.idempotence=true (default since 3.0) and acks=all (default since 3.0).

Key choice

The default partitioner computes murmur2(key) % numPartitions, so all events for a key land on one partition and are appended in arrival order. A consumer reads a partition in order, so per-key order holds, until the key changes or the partition count changes.

keyorder deliveredcardinalitywhat breaks
account_idper account10^6 to 10^8one hot tenant skews a partition
device_idper device10^8+device migrates to a new account
order_idper order10^9, short livedper-key state overhead exceeds the payload
account_id + entity_idper entityhighaccount merge changes the key

Pick the narrowest key that still covers the events you must order together. If two entities must stay ordered relative to each other, they are one key.

Partition count, with arithmetic

Assumed: 40k events/s average, 3x peak, 250 bytes per event, so 10 MB/s average and 30 MB/s peak; 1 day retention; each consumer handles about 5 MB/s.

  • Parallelism: 30 MB/s / 5 MB/s = 6 consumers needed at peak, so at least 6 partitions; round to 12 so assignment stays even.
  • Recovery: 30 MB/s * 86400 s = 2592 GB of retained log. Across 12 partitions that is 216 GB per partition to replay when a leader fails. To keep failover under 5 minutes at roughly 200 MB/s of disk read you must replay under 60 GB, so 2592 GB / 60 GB = 43 partitions, round to 48.

Every extra partition costs file handles, controller work and slower rebalances. Count can be raised but never lowered, so size once for the peak you expect and commit.

Duplicates, gaps, late events

Idempotent producers suppress retry duplicates inside a producer session using a producer id and a per-partition sequence. Across restarts, or from an at-least-once source, the consumer dedupes on (key, seq):

# at-least-once consumer, dedupe by (key, seq)
def handle(key, seq, payload, store):
    last = store.get(key)                # RocksDB or Redis
    if last is not None and seq <= last:
        return                           # duplicate or replay
    if last is not None and seq > last + 1:
        metrics.incr("gap", key)         # missing event, page on this
    store.put(key, seq)
    apply(key, payload)

Trace with key A receiving seq 1, 2, 2, 4: 1 applies and stores 1; 2 applies and stores 2; the second 2 is dropped as a replay; 4 exceeds 2 + 1 so the gap counter fires (event 3 was never delivered) and then applies. A gap is a missing event, not a duplicate, and that distinction is what makes the counter worth paging on.

Late events: run on event time with a watermark and bounded allowed lateness (Flink, for example, 2 minutes); records older than the bound go to a side output instead of holding back the stream.

Hot keys

Salt only when the downstream operation is commutative. Splitting account# into account#0 through account#9 spreads one 8 MB/s hot key over ten partitions, but per-key order is now ten independent orders. You have to merge them under the original key by event time, or aggregate per subkey and combine, and that merge pulls the traffic back toward one partition. Confirm the merge is order-correct before salting, and expect salting to help throughput only if the aggregation is associative.

Key change and repartition

Both move ownership and both can leave one logical entity in two ordered streams. Increasing the partition count from 12 to 48 remaps every key, since murmur2(key) % 12 becomes murmur2(key) % 48, and in-flight events split across the boundary. Handle it with versioned topics written in parallel and a check that no key lands on two partitions during the transition, comparing per-key last seq on both sides. Use the cooperative-sticky assignor (Kafka 2.4+) so a rebalance does not stop every consumer.

What to watch

Per-partition lag rather than the aggregate, skew as max/median partition rate, ISR shrink, rebalance count, and the rates of the gap counter and the late side output.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-6

Design state management and checkpointing for a streaming application.

Answer

What I'd say first

Before designing anything I'd pin down four things: is the source replayable, what delivery guarantee does the business actually need, what's the recovery objective (how many seconds of reprocessing is acceptable), and how big is the state. Those decide almost everything else.

The model: state is everything a task must have to resume correctly. Keyed state, operator state, broadcast state, and the timers registered against them. A checkpoint takes a consistent snapshot of that state plus the source offsets, and the sink commits only when the checkpoint completes. So RPO is bounded by the checkpoint interval plus the time the checkpoint took; RTO is restore time plus replay from the last committed offset.

State inventory

StateWhere it livesCheckpointed
Keyed ValueState / MapState / ListStatepartitioned by key groupyes
Operator ListState (e.g. Kafka source offsets)per subtask, redistributableyes
BroadcastStatereplicated to every subtaskyes
Event-time timersinside keyed stateyes
Sink transactionsexternal (Kafka txn, DB)committed on checkpoint complete

Backend choice

The heap backend keeps state as Java objects: fast access, but GC pressure and full checkpoints only; fine up to a few GB. RocksDB keeps state on local disk, supports incremental checkpoints, and is the right default past roughly 10 GB. Incremental checkpoints upload only the SST files new since the last one: a full checkpoint of 10 GB at 200 MB/s to S3 is ~50 s, while an incremental one after warm-up is typically a few hundred MB, ~1–2 s.

Config, with numbers

Java
env.enableCheckpointing(60_000);            // 60 s interval
CheckpointConfig cc = env.getCheckpointConfig();
cc.setCheckpointingMode(CheckpointingMode.EXACTLY_ONCE);
cc.setMinPauseBetweenCheckpoints(30_000);
cc.setCheckpointTimeout(5 * 60_000);
cc.setMaxConcurrentCheckpoints(1);
cc.setTolerableCheckpointFailureNumber(3);
cc.enableExternalizedCheckpoints(ExternalizedCheckpointCleanup.RETAIN_ON_CANCELLATION);
cc.enableUnalignedCheckpoints();
env.setStateBackend(new EmbeddedRocksDBStateBackend(true)); // incremental

Flink's defaults are 10 minutes for both interval and timeout, min pause 0, one concurrent checkpoint, and unaligned and incremental off. Those defaults are wrong for anything with a tight RPO.

Why unaligned matters

Aligned checkpoints inject a barrier into the stream and wait for every input to reach it before snapshotting. Under backpressure one slow input stalls the barrier, and checkpoint duration tracks the stall. Unaligned checkpoints snapshot in-flight data instead of waiting, so duration stays flat under backpressure: at the cost of larger checkpoints and no concurrent checkpoints. Turn it on when checkpoints are timing out, not by default.

TTL

TTL is a semantic decision, not memory tuning. It's evaluated on processing time, so a restore can resurrect state that had expired or drop state that hadn't: it is not deterministic cleanup. For correctness use event-time cleanup or explicit domain completion (emit and clear on session end) with a late-event correction path. Keep TTL as a backstop.

Failure modes

  • Checkpoint timeout under sustained backpressure: after tolerableCheckpointFailureNumber failures the job fails. Alert on the checkpoint-duration trend, not just on failures.
  • RocksDB local disk fills: task failure. Monitor per-task disk, not just cluster disk.
  • Restore at different parallelism: keyed state redistributes by key group, but operator state must be union- or split-redistributable or the restore fails.
  • Serializer change without a migration path: restore fails. Version serializers and keep savepoints for upgrades and rescaling.
  • Checkpoints are not backups. Retain a few for recovery; use savepoints for upgrades.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-2

Design event-time windows and late-data behavior for a streaming metric.

Answer

Core answer (first 90 seconds)

Metric: successful checkouts per merchant per 5-minute window, read by a merchant dashboard. Assumptions that decide the design: the producer stamps the event, client clocks sit within 90 s of true time, Kafka holds the raw topic with 7-day retention, and the dashboard may show a number that is corrected upward within 30 minutes but must never silently lose rows.

Design: 5-minute tumbling event-time windows keyed by merchant_id. Watermark = (max event time in a partition) - 90 s, then min across partitions, with 5-minute per-partition idleness so a silent partition stops pinning the minimum. A window fires once when the global watermark passes its end; with 90 s of out-of-orderness that means every live partition has seen an event at or after window_end + 90 s. Flink's allowedLateness(Time.minutes(5)) lets a late element re-fire the window and rewrite the same result; anything older goes to a side output, and an hourly batch job recomputes those (merchant_id, window_start) rows from Kafka. The sink is an upsert KV keyed by (merchant_id, window_start) carrying a pane/version column, so a correction is a new write on the same key, not a retraction the dashboard must understand. Watermarks are emitted periodically every 200 ms (Flink's default).

Why the watermark moves the way it does: a trace

Take three partitions, out-of-orderness 90 s. P0 max event time 10:00:07 gives it 09:58:37. P1 max 10:00:55 gives 09:59:25. P2 last spoke at 10:00:03, so 09:58:33, then goes silent. Global watermark = min = 09:58:33, and window [10:00:00, 10:05:00) cannot fire. At 10:05:03 P2 crosses the 5-minute idleness timeout, drops out of the min, and the global watermark becomes 09:59:25. The window fires only when every non-idle partition reaches max event time 10:06:30. Without the idleness rule that one silent partition pins the watermark at 09:58:33 forever: the window never fires and its state grows until the checkpoint fails.

Failure modes, what you see, what it costs

failuredetection signalcost
idle partition, no idleness configuredper-partition watermark flat while ingest is healthy; max watermark lag > 10 minresults stop; state grows unbounded
producer clock fast / future-dated eventsshare of events with event_time > ingest_time + 30 s; alert above 0.1%watermark jumps, genuine events land in the side output, dashboard undercounts until the batch repair
at-least-once duplicatededupe hits on event_id with 10-minute TTL statedouble-counted checkouts, fixed only by replay
state TTL shorter than window + latenesscounter for late events arriving with no window state; must stay 0silent undercount, no error raised
delete event older than TTLdelete event_time < watermark - latenessper-merchant recompute instead of an incremental update

Sizing and the alternatives

300k merchants active per 5-minute window: state retains window + lateness = 10 minutes = 2 windows, ~200 bytes per RocksDB entry (16-byte key, two 8-byte accumulators, block overhead) → 300k * 2 * 200 B = 120 MB, incrementally checkpointed every 60 s. Switch to 1-minute windows with 30-minute lateness and it is 300k * 31 * 200 B = 1.86 GB, where RocksDB cache pressure and checkpoint duration start to matter. A one-day replay is 288 windows * 300k merchants = 86.4M upserts, so rate-limit replays rather than letting them overwrite the live job. Kafka Streams requires you to state grace explicitly (ofSizeWithNoGrace vs .grace(...)) and counts discarded records in its dropped-records metric; Spark Structured Streaming's withWatermark drops events older than the watermark with no side output, so late data needs your own dead-letter path. Keep the raw topic at 7 days: once events age out, a correction is impossible.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-7

Join two unbounded event streams safely.

Answer

First I'd pin down three things before touching an operator: the join key, the time semantics, and what the consumer does when a match it already saw turns out to be wrong. Assume the key is stable (account id, not a mutable field), the relationship is event-time (an auth happens after an order), and the output is consumed by something that can handle a correction.

The default safe answer is an event-time interval join with watermarks on both inputs, state TTL set to the interval plus allowed lateness, and an append-only output carrying a version so downstream can retract. Watermarks are the gate: a watermark of T on the left asserts no left event with timestamp ≤ T will arrive again. The operator buffers left events in keyed state and only emits a match once the right side's watermark has passed the left event's timestamp: otherwise a right event arriving 30 seconds later would be silently missed. That's why the join is bounded: state is retained for the interval, and once both watermarks pass ts + interval + allowedLateness, the entry is evicted. State is keyed by the join key, so a hot key concentrates state on one subtask.

In Flink:

Java
WatermarkStrategy<Order> wm = WatermarkStrategy
    .<Order>forBoundedOutOfOrderness(Duration.ofSeconds(30))
    .withIdleness(Duration.ofMinutes(1));

orders.keyBy(Order::accountId)
      .intervalJoin(auths.keyBy(Auth::accountId))
      .between(Time.minutes(-5), Time.seconds(0))
      .process(new MatchFn());

between(-5m, 0) means an auth matches an order placed up to 5 minutes earlier. Flink holds the left record until the watermark passes order.ts + 5m; with 30s out-of-orderness that's roughly 5.5 minutes of state per key. At 10k orders/s and 200 bytes per buffered order: 10,000 × 330s × 200B ≈ 660 MB across the job. Fine on heap, but move to RocksDB once you're past a few GB. Kafka Streams is the same shape: JoinWindows.ofTimeDifferenceWithNoGrace(Duration.ofMinutes(5)). The WithNoGrace variant is required since 3.0; the older of() silently gave you 24 hours of grace, which is a common source of unbounded state.

Retraction is where most designs break. Flink SQL's regular join emits +I, -U, +U changelog rows; the DataStream interval join emits only appends. So if a late auth arrives after the order was already emitted, you either drop it or emit a correction record with the same key and a higher version. Downstream must be idempotent on (key, version).

Failure modes worth naming with their signals:

  • Idle source. A partition with no traffic stalls its watermark and the join stops emitting. Detect by comparing currentInputWatermark to currentProcessingTime: the gap grows without bound. withIdleness fixes it.
  • Late records. Anything past allowed lateness is dropped. Flink exposes numLateRecordsDropped; alert on it rather than discovering the gap in reconciliation.
  • Skew and amplification. One account with 1000 auths per order turns a 1:1 join into 1:1000 output. Watch the output/input ratio and per-subtask state size; checkpoint duration p99 climbing is the early signal.
  • Duplicates. At-least-once sources replay; dedup on (key, seq) with the same TTL as the join state.

When not to use it: if the join is historical and completeness matters more than latency (reconciliation, month-end close) a batch job over the same two tables is simpler and cheaper. The interval join only ever sees what arrives inside the window.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-24

A nightly batch job rebuilds a customer dimension table, and a real-time stream needs to enrich events with it. How do you join the stream to that table, and what happens when the dimension changes mid-stream?

Answer

Ask one thing before designing: does the enriched event need the dimension as it was at the event's own time, or as it is now? A customer's tier at order time and their current risk score are different joins, and that choice decides the whole design.

Assume point-in-time. Then the dimension is not a table you look up, it is a changelog. Each nightly rebuild publishes new versions with effective_from/effective_to (or an Iceberg snapshot commit), and the stream does an event-time temporal join against it:

sql CREATE TABLE customer_dim ( customer_id BIGINT, tier STRING, region STRING, update_time TIMESTAMP(3), WATERMARK FOR update_time AS update_time - INTERVAL '5' MINUTE, PRIMARY KEY (customer_id) NOT ENFORCED ) WITH ('connector' = 'kafka', 'topic' = 'customer_dim_cdc', ...);

SELECT e.order_id, e.customer_id, d.tier, d.region FROM orders e LEFT JOIN customer_dim FOR SYSTEM_TIME AS OF e.event_time AS d ON e.customer_id = d.customer_id;

Flink holds the dimension versions in keyed state and picks the one whose interval contains e.event_time. A late event arriving after the nightly swap still gets the old tier, which is the point. Re-running the same events produces the same output, so the enrichment is replayable and auditable.

The alternative most teams reach for first is a lookup: async I/O against Redis or HBase with a local cache and a TTL. That gives latest-value semantics, costs one RPC per cache miss, and is non-deterministic: replaying yesterday's events enriches them with today's dimension. If the business genuinely wants "current tier", take that trade and stamp the dimension version into the output so the decision can be explained later.

approachfreshnessreplay-deterministiccost
event-time temporal joinversion at event timeyesversions held in state until TTL
broadcast state (Flink)whatever you last loadedonly if you replay the same broadcast sequencefull copy per subtask
async lookup + TTL cachebounded by TTLnoRPC per miss
Spark stream-static joinre-read each micro-batchnofull scan of dimension per micro-batch

Broadcast state is the trap worth naming. It replicates the whole dimension into every parallel subtask: 2M customers × ~200 bytes is ~400 MB, and at parallelism 32 that is ~12.8 GB of heap before any event state. Fine for a 50k-row currency table, not for a customer master. Spark's stream-static join has the same shape: the static DataFrame is re-read at the start of every micro-batch, so a 2M-row dimension is a full scan every few seconds.

Mid-stream change is where it breaks. Three failure modes:

  • Truncate-and-load. The nightly job empties the table and every event in that window enriches to null. Detect with a null-enrichment-rate alert against baseline; fix by publishing versions atomically (Iceberg snapshot, or insert new rows with effective_from before retiring old ones) so readers never see an empty dimension.
  • Restore from checkpoint. Broadcast state comes back from the checkpoint, so the dimension can be hours stale. Re-broadcast on startup before the first event is processed, or gate on a version check.
  • Watermark stall. The temporal join waits for the dimension side to advance past the event time. An idle dimension source holds events indefinitely; set withIdleness on the watermark or emit a heartbeat. Set state TTL to cover max lateness plus your reprocessing window, or version state grows without bound.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-19

Design sessionization for user activity events.

Answer

Assumptions. Web and mobile product events, ~50M DAU, events land in Kafka with a client timestamp and a server receive timestamp, the live dashboard tolerates a few minutes of lag, and a nightly job produces the numbers finance and A/B analysis actually use. If sessions must be exact in real time, the design changes.

The answer. Sessionize on event time with a 30-minute inactivity gap, keyed by a resolved user key, using a stateful stream processor's session windows. In Flink 1.18 that is SessionWindows.withGap(Time.minutes(30)), a watermark of forBoundedOutOfOrderness(Duration.ofSeconds(30)), and .allowedLateness(Time.hours(2)). Kafka Streams is the other mainstream option: SessionWindows.with(Duration.ofMinutes(30)).grace(...), where the default grace period is 24 hours. Thirty minutes is what users expect, GA4's session timeout defaults to 30 minutes, so pick it unless the product says otherwise, and make it configurable per event stream.

Event time, not processing time: mobile clients buffer events offline and flush hours later, so processing-time windows would cut a session at the flush boundary. Session windows, not tumbling: a 90-minute active session is one session, and only a merging window can represent that.

Worked trace. One user, gap 30 min, allowed lateness 2 h.

eventevent timearrives ateffect
e110:0010:00S1 = [10:00, 10:42)
e210:1210:12merges into S1
e310:5010:5038 min after e2 → new S2 = [10:50, 11:35)
e411:0511:05merges into S2
——10:42watermark passes → S1 emits
——11:35watermark passes → S2 emits
e510:2511:4013 min after e2, 25 min before e3 → bridges S1 and S2 into S3 = [10:00, 11:35), which fires immediately

So the pipeline emitted S1 and S2 and then had to take both back. That is why sessionization needs retraction or upsert semantics downstream: emit (session_id, version, is_retraction) and let the sink upsert, or write to a table keyed by session_id. An append-only sink double-counts.

State. Live state is bounded by the gap plus allowed lateness, not by the day. 50M DAU × ~3 sessions/day = 150M sessions/day; retaining ~2.5 h of them at ~200 bytes each is roughly 3 GB, which fits a RocksDB-backed job at moderate parallelism. Raise allowed lateness and that grows linearly: 24 h of grace is ~30 GB, which is why Kafka Streams' 24 h default is generous for this workload.

Failure modes and detection.

  • Late bridge after emission → wrong session counts. Detect: retractions per hour; a spike means the watermark or lateness is misconfigured.
  • Future timestamps from skewed client clocks stall the watermark for every key. Detect: max event-time lag per source; clamp client timestamps to server receive time ± a few minutes.
  • Anonymous → logged-in. Keying on the device ID splits the session at login. Either accept the break or stitch in batch. Detect: sessions ending within a minute of a login event.
  • Shared devices (CTV, family iPad) put several humans behind one key. Not fixable in streaming; document it.
  • Bot keys with millions of events blow up one key's state. Detect: p99.9 events per key; cap events per session per key and route suspected bots to a separate stream.

Alternatives. Tumbling 30-minute buckets are cheap and merge-free but split long sessions and cannot represent them; use them if you only need activity counts. Batch-only sessionization with LAG over ordered events is exact and easy to reason about but hours behind; use it for the authoritative rollup. The usual answer is both: streaming for the live view, nightly batch restatement for anything that must be right, with live sessions flagged provisional.

Test. Exactly-30-minute gap (decide inclusive or exclusive and pin it), late bridge, duplicate event IDs, session with no end, midnight and DST boundaries (store UTC, convert at query time), identity merge and split, and a full replay from offset 0.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-16

Design streaming deduplication under retries and late arrivals.

Answer

Assumptions first. Three questions decide this design: does the source give me a stable identity, is the sink a store I control or an append-only log, and how long a replay must I survive. Kafka retention, a connector backfill, a disaster restore. I'll assume a Kafka producer I control, a Postgres sink, and a 7-day replay horizon.

Core answer. Identity comes from the producer, not the consumer. Kafka's idempotent producer (enable.idempotence=true, default since 3.0) stamps a producer ID and a per-partition sequence number, so broker-side retries inside one session are deduped for free. That covers producer retry and nothing else. For rebalance, connector replay and application retry I carry a business key plus a monotonic version: (account_id, seq), seq incrementing per account. Dedupe state is then one entry per key: the last committed seq. An event is a duplicate when seq <= last_seen[key].

Why not a set of event IDs? Arithmetic. At 50k events/s over a 7-day horizon that's 50,000 × 604,800 ≈ 3.0×10¹⁰ IDs. At roughly 100 bytes per key in RocksDB that's about 3 TB of state to checkpoint. Per-key sequence collapses it to one row per key: 10M accounts × ~100 bytes ≈ 1 GB. Same correctness, three orders of magnitude less state.

Why not a timestamp? A retry gets a fresh timestamp, so one event acquires two identities, and two distinct events in the same millisecond collide. Timestamps are for ordering and lateness, never identity.

The sink is the correctness boundary. Dedupe state is an optimization that keeps duplicates off the sink; it is not the guarantee, because state lives in the operator and operators lose state. So the sink write must be idempotent on its own: INSERT ... ON CONFLICT (account_id, seq) DO NOTHING in Postgres, or a conditional write WHERE version < :new_version. A duplicate that slips past the state set then becomes a no-op instead of a double-count.

Failure modes.

  • Checkpoint loss. Flink checkpoints every 10s; a crash restores state to the last checkpoint, so events processed in the final 10s replay. Their seqs aren't in the restored state, they pass dedupe, and the sink catches them. That is the entire reason the sink layer exists. With a two-phase-commit sink, state and output commit atomically and the window closes.
  • TTL expiry. State TTL must exceed the replay horizon. Kafka's log.retention.ms defaults to 604800000 (7 days) and offsets.retention.minutes to 10080, so 7 days is the floor. Set TTL to 8 days and alert on expiry rate; anything older is treated as new and the sink's unique constraint is the backstop.
  • Rescale. Keyed state moves with the key, so rescaling is safe when the partition key is the business key. Partition by event ID instead and one account's last-seen seq splits across subtasks: that's the bug to avoid.
  • Late beyond TTL. Route to a side output rather than dropping silently, then reconcile by replaying it against the sink's unique constraint.

Monitoring. Duplicate rate per source (expect well under 0.1% steady state, spiking during rebalances), state size per subtask, TTL expiry count, and sink conflict count: a nonzero conflict rate means dedupe state is behind, not that the sink is broken.

Test list: same ID different payload, same business action new ID, replay past TTL, rescale mid-stream, checkpoint restore, late update, two processors on one key. Reconcile logical effects, not consumed counts.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-3

Build an end-to-end exactly-once business outcome.

Answer

The 90-second answer. Assume the effect is "every order in Kafka topic orders produces exactly one row in Postgres order_totals." Source: Kafka 3.6, 3 partitions, 7-day retention (log.retention.hours=168). Job: Flink 1.18, checkpointing every 30s to S3. Sink: Postgres 16. End-to-end exactly-once means the committed source offset, the operator state, and the sink row move together or not at all. You get there one of two ways: make the sink transactional with the source progress, or make the effect idempotent so replay is harmless. Retries, crashes and ambiguous acks are all consequences of which one you picked.

Why the transactional path works. Flink's Kafka sink with DeliveryGuarantee.EXACTLY_ONCE wraps each checkpoint interval in a Kafka transaction. At the checkpoint barrier the sink flushes and pre-commits; when the checkpoint completes, it commits. The source offsets live in that same checkpoint, so the sink commit and the offset durability are ordered. Set transaction.timeout.ms (default 60000) below the broker's transaction.max.timeout.ms (default 900000), and give each job a stable transactional.id so a restarted job fences the old producer.

Worked crash. Partition 2 holds offsets 1000–1050. Checkpoint 42 starts at offset 1000; the sink writes those rows inside transaction T42 and pre-commits at the barrier. The job dies before the checkpoint-complete notification arrives. On restart Flink loads checkpoint 41, whose partition-2 offset is 1000, aborts T42, those rows were never visible, and re-reads 1000–1050 into T43. The rows appear once. If instead the job dies after the commit, checkpoint 42 is already durable, so it restores at offset 1051 and replays nothing. The ordering is what makes both branches safe.

When the sink can't enlist. For an HTTP API or a database outside the transaction, write with a stable key and an idempotent statement: INSERT ... ON CONFLICT (order_id) DO UPDATE SET total = EXCLUDED.total. The trap is DO UPDATE SET total = order_totals.total + EXCLUDED.total: replay doubles it. Keep a dedupe ledger keyed on (topic, partition, offset) with a unique index, and insert the ledger row in the same transaction as the effect, so a replay hits the unique violation and skips. For third-party APIs, Stripe retains idempotency keys for 24 hours; a retry inside that window is safe, a retry after it can double-charge, so your retry budget must be shorter than the key TTL.

Failure modes and how you see them.

  • Duplicate effect. Ledger row count exceeds distinct business keys. Alert on SELECT key, count(*) FROM ledger GROUP BY 1 HAVING count(*) > 1 returning anything.
  • Gap. Max committed offset per partition in the ledger lags the source high watermark by more than two checkpoint intervals (60s here). That's a stalled or silently failing sink, not a slow one.
  • Ambiguous ack. The producer's delivery.timeout.ms (default 120000) expires and you get a TimeoutException with an unknown outcome. Resolve it by reading the ledger key back, never by blind retry.
  • Zombie producer. Two jobs sharing a transactional.id: the restarted one fences the old, whose send throws ProducerFencedException. Without a stable id, both can commit and you get duplicates with no error at all.

What's excluded. Exactly-once holds inside the pipeline. Once the effect leaves your boundary (an email, a webhook to a partner with no idempotency key) you have at-least-once plus compensation. Write that sentence into the design doc instead of claiming universal exactly-once.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-20

Design a streaming aggregation sink for analytical queries.

Answer

Clarify before designing. Three questions decide the shape: is the consumer a BI tool running GROUP BY over a time range, or a dashboard reading one current value? What is the freshness target: seconds or minutes? And is exactly-once required, or is at-least-once with idempotent reads acceptable?

Assumptions I'll state. Kafka source, say 200k events/s, aggregate is count/sum/distinct by (tenant, page) over 1-minute tumbling windows, freshness target 60s, corrections accepted for events up to 10 minutes late, exactly-once into the table.

Core answer. Run a stateful processor (Flink) with keyed state keyed on (tenant, page, window_start). Each key lives on exactly one subtask, so the running aggregate needs no cross-worker coordination: that is the whole reason to key it this way. Emit a retractable changelog: +I on first emit, -U/+U on update, -D on retraction, into a table format that supports row-level upsert. Iceberg merge-on-read, Delta, or Hudi. Commit on checkpoint boundaries with two-phase commit: write data and delete files during pre-commit, publish the snapshot only after the checkpoint completes.

SQL
-- Flink SQL: retractable aggregate into an upsert sink
INSERT INTO page_counts
SELECT tenant, page, window_start, COUNT(*) AS cnt
FROM TABLE(TUMBLE(TABLE events, DESCRIPTOR(ts), INTERVAL '1' MINUTE))
GROUP BY tenant, page, window_start;

The sink table needs a primary key on (tenant, page, window_start) for upsert mode; without it Flink appends and the changelog is lost.

Alternatives, and when they lose.

designwrite costread costwins when
append-only paneslowest: no delete filesquery aggregates every paneconsumer already rolls up
upsert / merge-on-readdelete files + compactionone row per keyBI tools, point lookups
stage + atomic swapfull restatementtrivialsmall tables, batch only

Append-only panes are the trap: a retry duplicates a pane unless every row carries a deterministic id, and the read side pays for it forever. Upsert loses when the table is write-heavy and rarely read: you pay delete-file and compaction cost for a query nobody runs.

Failure modes.

  • Duplicate pane on retry. If the sink commits before the checkpoint is acknowledged, a restart re-emits. Detect by comparing count(distinct row_id) against the source count. Fix with two-phase commit, or an idempotent merge on row id.
  • Late retraction after the window closed. Events past allowed lateness either drop or go to a side output. Watch watermark lag; if it grows, the freshness target is already blown.
  • Small files. 200k events/s over 1-minute windows with 10k distinct keys is 10k rows/min. One file per partition per commit is 1,440 files/day/partition. Iceberg's write.target-file-size-bytes defaults to 512 MB; a compaction job rewrites small files on a schedule.
  • Batch restatement racing the stream. Iceberg commits are optimistic: commit.retry.num-retries defaults to 4, then the commit fails. The batch job and the stream both try to publish; one wins, the other retries and re-reads. Serialize them with a lock, or run restatement against a branch.

What decides the guarantee. The commit boundary is the checkpoint. Everything else (partitioning, compaction, retraction) is downstream of that one line.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-4

Handle backpressure in a high-volume streaming pipeline.

Answer

Core answer. Backpressure is a symptom, not a setting. Find the first stage whose arrival rate exceeds its service rate, then either raise that stage's capacity or lower the rate feeding it: without dropping correctness. Everything else (throttling, overflow topics, shedding) is a choice about where you absorb the excess, and each has a different cost.

Assume a Flink 1.18 job reading Kafka 3.x with exactly-once checkpoints, event-time windows, and a sink that is the suspected bottleneck.

Mechanism: how the pressure actually propagates. In Flink, a task stops reading from its input gate when it has no free buffers, and stops granting credits upstream. Credit-based flow control (default since 1.5) means each remote input channel may have at most taskmanager.network.memory.buffers-per-channel (default 2) buffers in flight, plus taskmanager.network.memory.floating-buffers-per-gate (default 8) shared across the gate. With the default 32 KB segment, that is ~64 KB per channel before the upstream task blocks. So backpressure travels one hop per buffer round-trip: milliseconds, not seconds.

The diagnostic asymmetry: the bottleneck operator shows high busyTimeMsPerSecond and low backPressuredTimeMsPerSecond (it is working, not waiting). The operator immediately upstream shows the reverse. The first operator with high busy time and low backpressure is your culprit.

On the Kafka side, Flink's source does not pause partitions by itself; the fetcher keeps pulling until max.partition.fetch.bytes (default 1 MB) per partition is buffered, so records-lag-max keeps climbing even while the job is backpressured. To genuinely stop pulling you call KafkaConsumer.pause(partitions): fetching stops, heartbeats continue, but you must keep calling poll() or max.poll.interval.ms (default 300 s) expires and the consumer is evicted from the group. On the producer side the built-in signal is send() blocking once buffer.memory (default 32 MB) fills, for up to max.block.ms (default 60 s), then throwing TimeoutException.

Choosing a remedy.

RemedyRight whenCost
Throttle/rate-limit sourcebottleneck is downstream and cannot scalelag grows; must be a product decision
Scale out parallelismCPU-bound operatorrescale pauses checkpoints, redistributes keyed state
Repartition/rebalance keysone subtask hotchanges keyed-state semantics
Batch/vectorize sinkper-record I/O overheadhigher latency, larger checkpoint state
Durable overflow topicsink outage, data must not be lostdoubles storage and adds a replay path
Shed/sampleexplicit product policy onlydata loss; must be counted and reported

Failure modes and how you see them.

  • Checkpoint alignment stall. Barriers queue behind in-flight data; checkpointAlignmentTime climbs and duration approaches execution.checkpointing.timeout (default 10 min), then the job fails after tolerable-failed-checkpoints (default 0). Unaligned checkpoints (execution.checkpointing.unaligned.enabled, off by default in Flink 1.x) buffer in-flight data into the checkpoint instead of waiting, trading state size for removing the stall.
  • Kafka retention exhaustion. If the source is paused while producers keep writing, offsets eventually fall off the log and you get OffsetOutOfRangeException: unrecoverable without a reset. Detect it as lag growing monotonically toward log-end-offset − log-start-offset under retention.ms (default 604800000, 7 days).
  • GC pause. Backpressure spikes on all operators at once rather than one; confirm against GC time, not throughput.
  • Hot key. One subtask's numRecordsInPerSecond is ~10× its peers and only that subtask is busy.

Arithmetic that decides the strategy. Input 200k records/s at 1 KB = 200 MB/s. The sink batches 500 records per write at 20 ms per write = 25k records/s. Deficit: 175k records/s, 175 MB/s. Buffering that for the 7-day retention window is 175 MB/s × 604800 s ≈ 106 TB: overflow is not free, so you scale the sink or shed under policy. Note the 32 KB buffer drains in ~0.2 ms at that rate, which is why the visible symptom is lag, not memory.

Drain gradually after the fix, and verify ordering, duplicates, late corrections and checkpoint success before declaring recovery.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-12

Handle poison events without stalling a stream.

Answer

The 90-second answer

I'd quarantine the bad record and keep the partition moving, but only after I've proven the failure is deterministic. That distinction decides everything. A timeout or a 503 from a downstream service is transient, and the right move is to retry in place with bounded backoff: eight attempts, 100 ms base doubling with a 30 s ceiling and jitter, so I've burned roughly 25 seconds before giving up. A record that fails schema validation, blows the size limit, or references a field that no longer exists will fail identically on attempt 10,000, and retrying it is just a slower way to stall.

So: validate the envelope at ingestion, classify the failure, and for deterministic poison write the original bytes plus source topic/partition/offset, schema ID, error class, consumer code version, timestamp and privacy classification to a quarantine topic, emit a metric, and commit the offset. The stream advances; the record is preserved and replayable.

FailureRetry?Action
Timeout, 503, connection resetYes, boundedRetry in place, then quarantine
Malformed or schema-incompatibleNoQuarantine, commit offset
Oversized (over the broker's 1 MiB default, message.max.bytes=1048588)NoQuarantine, alert the producer owner
Semantically invalid (unknown enum, dangling FK)NoQuarantine, hold that key's later events

Why not just skip it

Skip-with-alert is cheaper and I'd take it when the event is genuinely stateless: a click-tracking event, say. But if the record is a state change for a key, skipping it silently corrupts every later event for that key, so I hold that key's subsequent events until the record is fixed or policy says abandon it. That's the real trade-off: advancing the partition and preserving per-key order are in direct conflict, and the deciding question is whether the downstream consumer is keyed state or a stateless sink. I'd also promise consistent recovery of supported operator state, not exactly-once effects in every external sink: that promise is what makes replay safe to design.

Where it goes wrong in practice

The classic failure is the consumer that retries in place forever. Kafka's max.poll.interval.ms defaults to 300000 ms, five minutes, and if your handler blocks longer, the broker evicts the consumer, the partition is reassigned, and you get a rebalance loop that looks like a throughput problem but is one bad record. Second: quarantine retention shorter than source retention. Kafka topics default to log.retention.hours=168, seven days, so a 30-day quarantine outlives the source and you can still replay after the source is gone. Third: replaying a fixed record into a non-idempotent sink and double-counting.

Concrete mechanisms

Kafka Connect has this built in: errors.tolerance defaults to none, and setting it to all with errors.deadletterqueue.topic.name routes failures to a DLQ whose headers carry the original topic, partition and offset. Kafka Streams defaults to LogAndFailExceptionHandler; LogAndContinueExceptionHandler is the skip-with-alert option, and choosing it is a deliberate decision, not a default. In Flink the equivalent is a side output from a ProcessFunction rather than throwing, because throwing triggers the job's restart strategy and replays the whole checkpoint interval.

What I'd test

Repeated poison on the same key, quarantine topic unavailable, a payload carrying PII, a schema rollout mid-stream, replay producing duplicates, and a burst where 30% of a partition is invalid. That last one tells you whether alerting is per-record or per-window: per-record alerting will page you 50,000 times.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-18

Design stream retention, replay, and consumer recovery.

Answer

Before I size anything I'd pin down three inputs: the longest a consumer or checkpoint can be lost, the worst correction window we must replay, and what compliance requires us to keep or delete. Retention follows from those; storage cost is a consequence, not the input. If the answer is "we don't know," I'd default to the longest plausible window and revisit, because under-retaining is unrecoverable while over-retaining is just money.

Concretely, on Kafka the defaults are log.retention.hours=168 (seven days) and log.retention.bytes=-1 (no size cap), with a five-minute retention check (log.retention.check.interval.ms=300000) and 1 GiB segments. If the longest realistic outage is 72 hours and the correction window is 30 days, seven days is too short. I'd set retention per topic to the max of those windows plus margin, say 30 days, and where the topic is keyed and only the latest value matters, use cleanup.policy=compact with delete.retention.ms=86400000 so tombstones outlive slow consumers. Sizing check: a topic at 5 MB/s for 30 days is 5e6 × 86400 × 30 ≈ 12.96 TB, so I'd confirm the brokers can hold that before promising the window.

Every record carries immutable identity (event id), schema version, key, event time, ingestion time, and source provenance. Event time and ingestion time are separate fields because replay must preserve event-time ordering while ingestion time tells you when the system actually saw it. Sensitive payloads get encrypted or tokenized, and deletion obligations are honored by compaction or by a tombstone plus a retention bound, not by hoping the log rolls.

Consumers own durable state. On Kafka that's the group offset in __consumer_offsets (50 partitions by default), and I'd leave enable.auto.commit at its default true only if the sink is idempotent; otherwise set it false and commit after the effect lands. That gives at-least-once with idempotent outputs rather than silent loss.

Replay has distinct modes, and I'd name which one is running:

modewhenmechanism
same-group recoveryconsumer crashed, offsets intactseek to committed offset
shadow groupvalidate a new versionnew group id, read from earliest
bounded repairfix a key/time rangeseek by timestamp, filter by key
full rebuildstate store lostreplay from snapshot + log

Replay runs on isolated capacity (a separate consumer group with its own quotas, or a dedicated cluster) so it can't starve live traffic. Sinks get throttled and ordering requirements preserved; outputs are idempotent or versioned so reprocessing doesn't duplicate effects.

Monitoring is where this usually fails. I track retention headroom as oldest required offset versus the log start offset, plus consumer lag and stalled groups. Alert when lag approaches the retention window, if retention is 30 days and a group is 20 days behind, that's 66% of the window and I want a page well before the data expires. A group that stops advancing while lag stays flat is a stall, not a slow consumer.

I'd test long outage, offset corruption or reset, partition increase, schema evolution, a deleted event, checkpoint loss, and sink downtime: each against the retention window, not in isolation. If history has already expired, the honest move is to restore from a trusted snapshot plus whatever remains in the log and state the gap we can't prove, rather than reconstructing silently.

The failure mode to avoid is treating retention as a storage-cost knob. The second is committing offsets before the effect lands, which turns a replay into a data-loss event.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-21

Evolve a streaming event schema without breaking producers, consumers, or state.

Answer

What I'd say in the first two minutes

Two questions decide the design: which schema system (Avro with Confluent Schema Registry, Protobuf, or JSON Schema), and whether any consumer holds durable state keyed off the event. Then:

Wire compatibility is the easy half. Semantic compatibility is what pages you. Adding an optional field with a default is BACKWARD-compatible in Avro and every consumer decodes it, but if that field is currency and a downstream job summed raw amounts, you just changed the meaning of every historical row.

So the shape is expand-and-contract: tolerant consumers and state migrations first, producers second, mixed-version traffic observed, old version retired only after retention has expired.

Compatibility modes

Registry modeNew schema reads old dataOld schema reads new dataChange allowed
BACKWARD (default)yesnoadd field with default; delete field
FORWARDnoyesadd field; delete field with default
FULLyesyesadd or remove optional field with default

Confluent Schema Registry defaults to BACKWARD at the subject level. Set FULL when both directions must hold, and FULL_TRANSITIVE when consumers are pinned to more than one prior version.

Avro: the default is the contract

JSON
// v1
{"type":"record","name":"Order","fields":[
  {"name":"id","type":"string"},
  {"name":"amount_cents","type":"long"}]}

// v2 — BACKWARD compatible
{"type":"record","name":"Order","fields":[
  {"name":"id","type":"string"},
  {"name":"amount_cents","type":"long"},
  {"name":"currency","type":"string","default":"USD"}]}

Avro resolves the reader schema against the writer schema, so an added field needs a default or old data fails to decode. That default is also the trap: every pre-v2 event now claims USD. Count events where the field equals the default before trusting an aggregate built on it.

Protobuf: reserve, don't reuse

Protobuf
message Order {
  reserved 4, 7 to 9;
  reserved "legacy_total";
  string id = 1;
  int64 amount_cents = 2;
  string currency = 3;
}

Field numbers are the wire contract; reusing 4 for a new field silently mis-decodes old bytes. Proto3 has preserved unknown fields since 3.5, so a new field survives a round trip through an old consumer that re-emits the message. JSON Schema does not: unknown fields are dropped unless you keep them explicitly.

State and replay

Kafka Streams serializes state stores with the configured value serde, so changing the serde changes the on-disk format. upgrade.from (e.g. 2.4) holds the old format during a rolling upgrade. Changing the key schema is worse: it repartitions, rebuilds state, and breaks joins.

Retention bounds your replay. retention.ms defaults to 604800000 (7 days). At 50,000 events/s that is 50,000 × 86,400 × 7 = 30.24 billion events. If you need to replay further back, you need tiered storage or a compacted topic, and you need to know that before the producer ships.

Failure modes to watch

  • Silent unit or timezone drift: run a canary consumer asserting invariants against both versions.
  • Default poisoning: alert on the fraction of events equal to the new default.
  • Unknown-field stripping: round-trip a message through the oldest deployed consumer in CI.
  • Rollback: keep the old producer deployable until the new version's retention window has passed.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-15

Perform a safe stateful streaming application upgrade.

Answer

Assume Flink 1.18, RocksDB state backend with incremental checkpoints, a Kafka source and a two-phase-commit Kafka sink, and keyed state. One question decides the whole plan: can the new code read the old state? If yes, restore in place from a savepoint. If the state schema or keying changes incompatibly, migrate with a StateProcessor or rebuild from the source. If only output semantics change, dual-write and diff. Everything below is the in-place path, with the other two as fallbacks.

Classify the change before touching the cluster.

changemechanismwhat breaks if ignored
stateless operator logicno state readnothing, but the operator still needs a stable uid()
add/remove a POJO fieldTypeSerializerSnapshot reads old bytes, new field takes its defaultno snapshot → StateMigrationException on restore
change key type or keyBykey groups re-hashstate lands on the wrong key, silently wrong results
change maxParallelismkey group count changessavepoint cannot be restored at all
change watermark or timer semanticstimers live in statepending windows never fire, or fire twice
change sink transactionalIdPrefixold transactions are never abortedduplicate records downstream

Runbook. Set uid() on every operator and freeze maxParallelism: Flink 1.17 lowered the default from 32768 to 128, and a savepoint taken under one value will not restore under another. Then flink stop --savepointPath s3://bucket/sp --drain <jobId>: drain sends MAX_WATERMARK so event-time windows emit before the job stops. Deploy the new jar with flink run -s s3://bucket/sp/savepoint-<id> -d new.jar. Add --allowNonRestoredState only for operators you deliberately deleted; using it to paper over a serializer mismatch loses state silently. Validate per-key-group state counts, timer count, the Kafka offsets held in state, the restored watermark, and that the sink committed.

Budget the stop window from full state, not checkpoint size. 40 GB of keyed state with a 1.2 GB incremental checkpoint still reads all 40 GB on restore: at ~200 MB/s from local SSD that is ~200 s of downtime, and a full 40 GB checkpoint over a 1 Gbps link is ~5.5 min. Incremental checkpoints make steady-state cheap; they do not make restore cheap.

Alternatives and when to pick them. In-place savepoint restore costs minutes of downtime and produces no duplicate output, but requires compatible state: use it when serializer snapshots exist and keying is unchanged. Dual-write runs the new job against the same source into a shadow sink and diffs outputs; no downtime, roughly double compute, and the sink must be idempotent or separate: use it when output semantics change. Rebuild replays from Kafka retention or a lake; only when state is not migratable, and it costs the full replay time plus whatever the source still holds.

Failure modes. A savepoint that fails mid-write leaves the job running: retry, do not stop. A restore that throws StateMigrationException means a missing serializer snapshot; fix the snapshot and re-savepoint rather than forcing. After a rescale, check per-key-group state counts before accepting, because a bad redistribution is invisible in throughput. A sink commit failure after restore usually means the transactionalIdPrefix changed or old transactions are pending; abort the orphans with KafkaAdminClient.listTransactions before retrying.

Rollback. Keep the old savepoint and old jar until the new job has committed at least one checkpoint and outputs match. Past that point the old code can no longer read the new state, so rollback means replaying from the source, not restoring.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-11

Recover a streaming job after checkpoint corruption.

Answer

Assume Flink 1.18+, a Kafka source, an exactly-once sink, checkpoints every 60s to S3, and Kafka retention at its 7-day default.

Answer directly: don't restore from the newest checkpoint directory. Flink writes the _metadata file last, after every subtask has uploaded its state handles, so a directory that exists without a parseable _metadata is an incomplete checkpoint rather than a corrupt one. List the checkpoint directories, parse _metadata newest-first, and take the first whose referenced state files still exist. Then check the sink independently: a Flink checkpoint can be complete while the sink's external transaction for it never committed, because the commit fires only after the JobManager notifies the sinks.

Restore with flink run -s s3://bucket/chk-<n> or by setting execution.savepoint.path. Flink seeks the Kafka source to the offsets stored in that checkpoint. If those offsets are older than the topic's earliest offset, startup fails with OffsetOutOfRangeException: that is retention having moved past your checkpoint.

Why checkpoints go bad. Three causes dominate. An S3 lifecycle rule deletes state files while _metadata survives. A truncated multipart upload leaves a state handle that 404s. A RocksDB state file fails deserialization after a Flink upgrade changed the serializer. The first two show up in an existence check; the third only appears when a task reads the state, so restore into a staging cluster before you touch production.

Replay and sinks. On restore Flink recovers the sink's pending transactions from the checkpoint state: transactions belonging to a completed checkpoint are committed, and transactions started after it are aborted. Records written after the last completed checkpoint replay from the stored offsets. A Kafka transactional sink absorbs this: consumers at isolation.level=read_committed never see the aborted transaction's records. A non-idempotent sink does not, so you need a stable event key to dedup.

Failure modes and how you see them.

  • Offsets expired → OffsetOutOfRangeException at startup. Reset scan.startup.mode to earliest and accept a gap, or rebuild.
  • Sink transaction aborted → the broker drops any transaction whose transaction.timeout.ms elapsed. Kafka's producer default is 60s; keep the effective value above checkpoint interval plus maximum expected downtime or you lose the commit silently.
  • Two active writers → the old job still running when you restore. Cancel it and confirm the sink's transactional IDs are free first.

Choosing the restore point.

OptionRight whenCost
Newest valid checkpointSame job version, offsets still in retentionMinutes of replay
SavepointJob version changed, operators remappedManual trigger; --allowNonRestoredState can silently drop state
Snapshot + log positionNo checkpoint trustworthyHours; needs an authoritative snapshot

A savepoint is the wrong tool when the source offsets are already expired: it carries the same offsets and fails identically.

Trace. Checkpoint 42 completes at 10:00:00. The sink commits transaction 42 at 10:00:03. Records keep flowing into transaction 43. The job dies at 10:00:30, before checkpoint 43 completes. Restore from 42: Flink commits transaction 42 if the notification was lost, aborts transaction 43, and seeks Kafka to the offsets stored in 42, so 10:00:00–10:00:30 replays into a fresh transaction. With a transactional sink each record is visible once; with a plain sink that 30-second window appears twice.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-8

Build a streaming fraud-detection decision path.

Answer

Assume a card-not-present authorization stream: peak 5k events/s, p99 budget 150 ms from event ingest to decision. The decision is allow, deny, or review. False allow costs chargebacks and fees; false deny costs lost sales and customer friction; review costs analyst time. I'd set thresholds from a cost matrix, not from a generic 0.5.

The path: ingest from Kafka, validate schema, dedupe by event ID in a windowed store (Redis with 10-minute TTL or Flink keyed state). Use event time, not processing time, because mobile networks reorder and late authorizations arrive. Watermark with allowed lateness of 2 minutes; events later than that go to a side output for batch reconciliation. Why event time? A card authorization can arrive 30 seconds late due to network retries; processing time would count it in the wrong velocity window and miss a burst.

Features: velocity (count per card in last 1h, 24h), session, device, account. Use bounded keyed state: Flink keyed state with TTL, RocksDB backend, state size per key capped at, say, 10k entries. For hot accounts, salt the key or use two-level aggregation. A single card with 100k events/min would skew one task manager; salting spreads across subtasks. Bounded state bounds memory: without TTL, state grows unbounded and causes GC pauses or OOM.

Scoring: model or rules. Version everything. Emit risk score, reason codes, model version, evidence to an idempotent decision service keyed by transaction ID. Idempotency prevents double charging, blocking, or notifying on retry. Use a unique constraint in Postgres or Redis SETNX with TTL.

Failure modes: if Kafka source lags, fallback to last known good model and rule-only. If state store unavailable, degrade to stateless features (only current transaction attributes) and lower thresholds to review more. If model service times out, default to conservative deny for high-value transactions. Detect via: feature missingness rate > 5% alerts; late event rate > 1% alerts; p99 latency > 150 ms alerts; hot key latency > 500 ms alerts. A hot-key skew can push p99 from 150 ms to 2 s, causing timeouts and fallback.

Trade-offs: streaming vs batch features. Streaming gives low latency but approximate counts; batch gives exact but delayed. Use streaming for velocity, batch for long-term aggregates. Thresholds vs review: if review cost is $5 and false deny cost is $50, set threshold to review when expected fraud probability is between 0.1 and 0.5. Monitor segment-level precision/recall proxies, drift, appeals.

Artefact: a table of thresholds and actions (hypothetical).

| Risk score | Action | Rationale | | 0-0.2 | Allow | Low fraud probability | | 0.2-0.6 | Review | Uncertain, human can decide | | 0.6-1.0 | Deny | High fraud probability |

Trace: event arrives at t=0. Ingest 5ms, dedupe 2ms, feature lookup 20ms, model 30ms, decision 5ms, total 62ms. If state store misses, feature lookup 5ms, total 47ms but lower accuracy. Replay historical logs for regression, shadow/canary changes, reconcile low-latency decisions with later labels.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-9

Build a hybrid streaming and batch reconciliation architecture.

Answer

Assumptions. CDC (Debezium on Postgres) into Kafka; stable primary key, source LSN, event-time column, delete flag. Stream: Flink 1.18, 12 partitions, watermark = max event time − 10 min, allowed lateness 10 min, checkpoint every 60 s. Batch: Spark 3.5 over the same bronze log in Iceberg, hourly at :05 with a 3-hour lookback. Serving store: Postgres. No stable key or no event time means reconciliation is impossible: fix that before anything else.

Core. One durable bronze log is the source of truth; both paths read it. The stream writes provisional rows tagged with a stream epoch; the batch writes authoritative rows tagged with a batch epoch. The serving layer resolves per key: authoritative wins once its batch epoch ≥ the stream epoch that produced the provisional row. Reconciliation compares the two per key and window and classifies each difference as expected lateness or logic drift.

Why double counting happens. Batch cutover at 14:05 reads a snapshot at Kafka offset O; the stream has already emitted up to O+δ. Without epochs, keys in the overlap are counted twice. With epochs, the batch's atomic partition swap replaces the provisional rows for 13:00–14:00, and the serving layer ignores stream writes below the batch epoch for that key. The stream checkpoint and the batch snapshot offset are recorded together so a restart replays from the same point.

Serving resolution.

SQL
SELECT COALESCE(p.key, a.key) AS key,
       CASE WHEN a.key IS NULL THEN p.amount
            WHEN p.key IS NULL THEN a.amount
            WHEN a.batch_epoch >= p.stream_epoch THEN a.amount
            ELSE p.amount END AS amount
FROM provisional p
FULL OUTER JOIN authoritative a USING (key);

Five keys, batch_epoch 8, stream_epoch 7:

keyprovisionalauthoritativeresolved
k1100100100
k2250250250
k3404040
k490130130
k5—6060

k4's provisional value is superseded; k5 exists only on the batch side.

Reconciliation query. stream_marks holds the per-key max event_time and max arrival_time the stream observed, including events routed to Flink's late-data side output, so a key the stream dropped still has a row.

SQL
WITH diffs AS (
  SELECT COALESCE(p.key, a.key) AS key,
         p.amount AS stream_amount, a.amount AS batch_amount
  FROM provisional p FULL OUTER JOIN authoritative a USING (key)
  WHERE p.amount IS DISTINCT FROM a.amount
)
SELECT d.key, d.stream_amount, d.batch_amount,
       s.max_event_time, s.max_arrival_time,
       CASE WHEN s.max_event_time IS NULL
                 OR s.max_event_time >= TIMESTAMP '2024-03-05 13:50:00'
              THEN 'not_yet_in_window'
            WHEN s.max_arrival_time > TIMESTAMP '2024-03-05 13:50:00'
              THEN 'expected_lateness'
            ELSE 'logic_drift' END AS classification
FROM diffs d LEFT JOIN stream_marks s USING (key)
ORDER BY d.key;

The watermark at 13:50 means the stream assumes no more events with event_time < 13:50. Running it on the sample above:

keystream_amountbatch_amountmax_event_timemax_arrival_timeclassification
k49013013:4213:44logic_drift
k5null6013:4714:02expected_lateness

k4 arrived at 13:44, before the watermark, and the stream still got it wrong. Page on-call. k5 arrived at 14:02, after the window closed, so the stream never saw it. At production scale the same query on a 13:00–14:00 recompute returned 1,000,240 batch rows against 1,000,000 provisional: 240 diff keys, 238 late, 2 logic drift. The alert fires on any logic-drift key, not on the 0.024% rate.

Failure modes.

  • Stream outage: consumer lag climbs; on restart Flink replays from checkpoint. A 30-min outage across 12 partitions catches up in ~5 min at ~2k events/s per partition. Provisional views are stale for the outage; batch stays correct.
  • Late delete: reconciliation shows the key present in provisional, absent in batch. Provisional serves a deleted entity until the next batch: a compliance problem for user deletions, so route deletes to a high-priority tombstone path.
  • Dimension correction: a customer segment is restated and historical facts are keyed to the old segment. Detection: a batch recompute of affected partitions changes aggregates. Cost: restating N partitions and re-keying joins.
  • Code skew: stream and batch run different UDF versions. Detection: every diff key arrived before the watermark → logic drift. Cost: silent wrong numbers until reconciliation runs.

Trade-off: shared library vs unified engine. A shared library (one package of aggregation logic used by both Flink and Spark) wins when teams are separate, languages differ, or you need independent scaling; cost is version skew and duplicated I/O. A unified engine (Flink batch mode, or Spark Structured Streaming with a batch backfill) wins when one team owns both and semantics are complex; cost is a single point of failure and the engine's latency floor. Deciding criteria: number of owning teams, whether the streaming engine can do bounded batch at acceptable cost, and how often semantics change. If the two implementations drift continually, collapse to one engine rather than normalizing the inconsistency.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-10

Migrate a batch pipeline to lower-latency streaming.

Answer

What I'd say first (60–120 s)

Before touching code I'd pin two things: the freshness target and whether business semantics must be bit-identical. "Lower latency" is not a spec: I'd ask for a number, e.g. p99 end-to-end freshness ≤ 60 s against today's 15-minute batch, and whether a late correction may change an already-published number. If corrections must be reconciled, batch stays as the repair path and streaming becomes the live path, not a replacement.

Assumptions I'd state: events carry a business timestamp and a stable key; the source can be replayed from a durable log; consumers tolerate at-least-once with idempotent writes.

Core answer

The migration is a semantics-preservation exercise, not a rewrite. Four moves, in order.

  1. Freeze the contract. Write down the batch's identity rule, dedupe key, join keys, business-time definition and publication boundary. That is the spec the streaming job must match, and what you diff against later.

  2. Make the source replayable. A bounded snapshot becomes an unbounded log. Kafka with 7-day retention (log.retention.hours=168) gives replay for backfill; needing longer is a decision, not a default.

  3. Bound the state. Streaming joins and dedupe hold state forever unless you bound them: keyed dedupe with a TTL, windowed joins with allowed lateness (Flink's default is 0. Set it explicitly, say 2 min), and a watermark trailing max event time by the observed disorder (say 30 s).

  4. Make the sink idempotent. Replays and checkpoint restarts re-emit. Guard with a version:

SQL
-- Postgres 16
MERGE INTO orders_current AS t
USING staged_orders AS s ON t.order_id = s.order_id
WHEN MATCHED AND s.version > t.version
  THEN UPDATE SET amount = s.amount, version = s.version
WHEN NOT MATCHED
  THEN INSERT (order_id, amount, version)
       VALUES (s.order_id, s.amount, s.version);

Replaying the same batch twice is a no-op: the second pass has s.version == t.version, so nothing updates. That property is what makes at-least-once safe.

Artefacts

State arithmetic: 20M active keys × ~300 B per keyed entry ≈ 6 GB, which fits a RocksDB state backend with incremental checkpoints; at a 60 s checkpoint interval that is the steady write load you are adding.

ConcernBatchStreaming
Snapshotbounded partitionunbounded, offset-tracked
Orderingglobal sort by business timeper-key only
DedupeDISTINCT over batchkeyed state + TTL
Late dataall presentallowed lateness, side output
Backfillrerun partitionreplay from offset

Failure modes and detection

  • Watermark stalls (a source partition goes quiet): no window fires and output freshness climbs. Detect with a watermark-vs-wall-clock metric and alert on output lag, not job liveness.
  • Hot key: one subtask's checkpoint balloons and backpressures the job. Detect via per-subtask checkpoint size and busyTime.
  • Checkpoint failure: the job restarts from the last good checkpoint and reprocesses. Detect via the checkpoint-failure counter; bound the blast radius with a short interval.
  • Duplicate publication: sink retry after a partial commit. Detect by comparing output row count to distinct keys per period.
  • Late correction after window close: silently dropped unless routed to a side output. Detect via the late-event counter.

Cutover

Replay representative history through the streaming logic and diff against batch by key and period: that is the equivalence gate. Then shadow live, canary consumers with versioned output and rollback, and decommission the batch live path only after stable equivalence and a tested checkpoint restore.

When not to

If the freshness target is minutes and batch already runs every 15, the continuous state, checkpointing and on-call surface are not worth it. Stay batch.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-17

Control cost in a continuously running streaming platform.

Answer

Assumptions. Pin the SLO first (p99 event-time freshness under 5 s, no data loss) and define cost as dollars per million useful events, not the monthly bill. Three drivers dominate: retained bytes, cross-AZ replication, and compute that idles because of skew.

Attribute per operator. Tag every stream with tenant, job, and operator; emit bytes in, bytes out, state size, and checkpoint duration per operator. A cluster-level number hides the join window that should have been a TTL'd dedup set.

Skew is usually the biggest single line. Worked example: one 500 MB/s topic, 48 partitions, 6 brokers, one tenant key carrying 30% of traffic.

PartitionsMB/s eachBroker total
Hot broker1 hot + 7 normal150 + 7×7.4202
Other 5 brokers8 each7.459
Cluster mean4810.483

The hot broker runs at 2.4× the mean, and the partition can't split, so you size all six brokers for 202 MB/s: 1.2 GB/s provisioned for 500 MB/s of traffic. Salt the key (tenantId + 8 buckets) and re-aggregate downstream, or use a custom partitioner when the distribution is known. Salting costs per-key ordering, so only do it where the downstream aggregation is order-insensitive.

Replication and retention are the storage bill. RF=3 across three AZs copies each byte to two remote AZs at $0.01/GB in and $0.01/GB out: $0.02/GB per remote copy. Monthly, for the same topic:

LineQuantityUnit price$/month
Cross-AZ replication43.2 TB/day × 2 copies × 30 = 2,592 TB$0.02/GB~$52k
Broker disk, 7-day retention, RF=3907 TB$0.08/GB-mo (gp3)~$73k
Checkpoints, 50 GB state, 1-min, non-incremental72 TB/day × 30 = 2,160 TB$0.023/GB-mo (S3)~$50k

Kafka's default log.retention.hours is 168 (7 days), so the topic retains 43.2 TB/day × 7 = 302 TB, 907 TB at RF=3. Tiered storage moving all of it to S3 at $0.023/GB-month drops that line to ~$21k, saving ~$52k/month, at the cost of read latency during catch-up.

Checkpointing and state. Flink's default backend is HashMapStateBackend (heap): fine to a few GB, then GC pauses dominate. EmbeddedRocksDBStateBackend spills to disk and supports incremental checkpoints, uploading only new SST files instead of the full state each interval. State TTL is off by default; a sessionization key set needing 30 minutes of history but keeping 7 days is pure waste. Checkpoint interval is the other half: 1 minute on 50 GB of non-incremental state writes 72 TB/day to object storage.

Trade-offs. If the product's useful latency is 5 minutes, a 1-minute micro-batch (Spark Structured Streaming) beats a continuously running job on idle compute. Compaction on analytical sinks trades write amplification for read cost.

Failure modes. Never cut cost by dropping events, committing offsets past unprocessed data, disabling checkpointing, or widening watermark lateness to hide late data. Detect them with consumer lag (produced minus committed offset) climbing, checkpoint duration approaching the interval, checkpoint failures, and watermark lag.

Report cost per million useful events, p99 freshness, recovery time, and on-call pages, not the lowest infrastructure bill.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-22

Design disaster recovery and regional failover for a streaming pipeline.

Answer

Assumptions. Kafka 3.6, RF=3, min.insync.replicas=2, acks=all, unclean.leader.election.enable=false. Flink 1.18, RocksDB incremental checkpoints every 60s to S3. Sink is an idempotent upsert keyed on event_id. Primary us-east-1, DR us-west-2. Targets: RPO ≤ 60s, RTO ≤ 30 min.

Core answer. Active-passive, and the key move is recognising that the log is the source of truth while state is derived. That decouples the two numbers: RPO is set by replication lag on the log, not by how often Flink checkpoints. So replicate topics with MirrorMaker 2 (or Cluster Linking), keep the DR cluster read-only to consumers until promotion, fence the primary by rotating producer credentials before you promote, then start Flink from the newest checkpoint that actually exists in the DR region and replay the log from that checkpoint's source offsets. Sinks must be idempotent, because both consumer offsets and checkpoints arrive minutes stale.

Worked failover trace.

  • t=0: us-east-1 lost.
  • t=0–90s: Route 53 health check (30s interval, 3 consecutive failures) flips the failover record to us-west-2. Producers holding open TCP connections do not re-resolve DNS; they need both regions in bootstrap.servers and enough retries to survive the switch, or they stall until restarted.
  • t=90–150s: Fence. Rotate the SCRAM credential the primary's producers use, on the DR cluster only, and delete the old user on the primary: kafka-configs --bootstrap-server <dr> --alter --entity-type users --entity-name svc-producer --add-config 'SCRAM-SHA-256=[password=...]'. Confirm with a probe producer that must fail with SASL authentication failed. Do not enable the reverse MM2 flow until that probe fails.
  • t=150s: Promote. MM2's sync.group.offsets.enabled defaults to false; if you left it off, every consumer group starts at auto.offset.reset, which defaults to latest, and you silently drop the entire backlog. Turn it on and accept that refresh.groups.interval.seconds (default 600) means committed offsets can be up to 10 minutes stale.
  • t=150s–~4min: Start Flink from the newest checkpoint in the DR bucket. Checkpoints survive job cancellation only if execution.checkpointing.externalized-checkpoint-retention=RETAIN_ON_CANCELLATION; the default is NO_EXTERNALIZED_CHECKPOINTS, which deletes them the moment the job stops. Take a savepoint before any planned failover.
  • Replay, if the newest replicated checkpoint is 8 minutes old and the stream runs 20k events/s, that is 9.6M events. The sink sustains 20k/s, so replay costs ~8 minutes. RTO ≈ 90s + 60s + 3min + 8min ≈ 13.5 min, inside the 30-minute target. RPO is the MM2 replication lag at the instant of failure: seconds at steady state, not 8 minutes. Kafka retains 168h by default, so the gap is replayable.

Failure modes.

FailureDetectionMitigation
Primary returns and accepts writes (split brain)Producer throughput reported from both regionsCredential rotation above; stamp a region epoch on events and have the sink reject stale epochs
Topic created shortly before the outage is missing in DRMM2 lag metric absent for that topicrefresh.topics.interval.seconds defaults to 600: pre-create topics in DR or lower it
Checkpoints deleted on job stopRestore finds no checkpointSet RETAIN_ON_CANCELLATION; savepoint before planned failover
Encrypted state unreadable in DRRestore fails on key lookupKMS keys are region-scoped; use multi-Region keys or re-encrypt

Trade-offs. Active-active with per-key write fencing gives RTO near zero but only per-key ordering and no cross-region exactly-once: you cannot get global exactly-once across two regions. Active-passive costs a warm standby but keeps one writer. If RPO can be hours, skip all of this: S3 cross-region replication plus a nightly restore is enough, and CRR's own worst case is 15 minutes for 99.99% of objects anyway.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-23

Honor privacy deletion when immutable events feed batch and streaming systems.

Answer

Core answer

Assume GDPR/CCPA scope, a Kafka backbone feeding both a streaming job and a nightly batch load into a lakehouse, and the one-month statutory clock (GDPR Art. 12(3)). The honest answer: you cannot delete in place from an immutable log. You make deletion a read-time property enforced by a ledger, and you pay for physical erasure only where law or contract actually demands it.

Three tiers.

Tier 1: mutable serving stores (Postgres, Redis, Elasticsearch). Hard delete plus tombstone. Postgres DELETE then VACUUM; the row still sits in WAL and in any PITR base backup until that backup expires.

Tier 2: the immutable log and lakehouse. Kafka has no per-record delete. Either rely on log compaction with a null-value tombstone, which drops the key after delete.retention.ms (default 24h), only if the topic is compacted and the subject is the key, or rewrite the partition. Iceberg and Delta Lake both give row-level deletes: Iceberg v2 position-delete files, Delta 3.0 deletion vectors. Both are logical until you rewrite the data files.

Tier 3: derived state: Flink checkpoints and savepoints, aggregates, caches, exports.

The ledger is what makes tier 2 safe: a compacted deletions topic keyed by subject ID, read into Flink broadcast state and joined against every event before publication. Replay from an old checkpoint then re-applies the ledger and the subject never re-emerges.

LayerMechanismLogical deletePhysical
PostgresDELETE + VACUUMmsbackup expiry (e.g. 35d PITR)
Kafka (compacted)null tombstone≤ delete.retention.ms (24h default)segment deletion
Iceberg / Deltaposition delete / deletion vectorminutesnext rewrite job
Flink statesavepoint with state droppedminutesn/a
S3 archivedelete marker + lifecyclemslifecycle expiry

Trace: the ledger filter:

// broadcast state: subjectId -> DeletionRequest{requestedAt}
if (ledger.contains(event.subjectId)
    && event.occurredAt <= ledger.get(event.subjectId).requestedAt) {
    drop(event);   // never reaches the sink
} else {
    emit(event);
}

Note the comparison. Only events at or before the request time are suppressed. Events after it are new processing under a new basis and must flow: suppress everything and you silently break the product for a returning user.

Trade-offs

  • Ledger filter vs. physical rewrite. Filtering costs one broadcast lookup per event and is reversible; rewriting is expensive but is the only thing that satisfies a regulator who wants the bytes gone. Decide by jurisdiction and data class, not engineering preference.
  • Tokenize at ingestion vs. delete later. HMAC the subject ID with a per-tenant key and "deletion" is often just destroying the key. It fails when you need the raw ID for a lawful purpose, and fails hard if the key lives in a KMS you cannot audit.
  • Compaction vs. partition rewrite. Compaction is free but requires the subject to be the key on a compacted topic. Key by device or session and you must rewrite.

Failure modes

  • Replay from a checkpoint older than the ledger → the subject reappears. Detect with a canary subject deleted in staging, then replay seven days of checkpoints and assert zero emissions.
  • A downstream processor that acks but never applies. Measure per-sink lag on the deletion topic; alert past one hour.
  • Backup restore that skips ledger reapplication. That is a reportable incident, not a bug.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-25

Define and monitor a freshness and end-to-end latency SLO for a pipeline that mixes batch and streaming stages: what do you measure, where do you measure it, and how do you detect and alert on consumer lag before the SLO is breached?

Answer

Pin the SLO to event time, not to how busy the pipeline looks. Freshness = now − event_time of the newest record visible in the serving table, reported as p50/p99 per dataset. Batch stages get a partition-availability SLA instead: "the 10:00 UTC hourly partition is queryable by 10:10". Both are user-visible; consumer lag is only a leading indicator of the first.

Measure at four boundaries, because each one fails differently:

BoundaryMetricWhat it catches
Produceremit timestamp vs broker append timeclock skew, producer backlog
Brokerlog-end offset per partition, append timeingest-side stall
Stream stageFlink currentWatermark per operator; consumer group lag per partitionslow consumer vs idle partition
Sink/commitIceberg snapshot commit duration, max event_time in the new snapshot; batch partition readiness timecommit-bound latency, late batch partition

The trap is that lag is in records, not seconds. Convert it: for each partition, look up the timestamp of the committed offset and of the log-end offset (Kafka offsetsForTimes), then lag_seconds = ts(LEO) − ts(committed). Aggregate lag hides a hot partition, so alert on the per-partition max, never the mean. A partition at 2M records of lag on a 50k/s topic is 40s; the same 2M on a 5k/s topic is 400s.

Alert on projected breach, not a fixed threshold. With lag L seconds, drain rate r and arrival rate a (both measured over 5 min): time-to-clear = L/(r−a) when r>a. If r≤a the backlog never clears: page immediately regardless of L. Otherwise page when L + horizon exceeds the freshness objective.

Use multi-window burn rate on the SLO. Objective: 99% of minutes have p99 freshness ≤ 60s over 28 days → error budget 1% = 403 min. A 1h window burning 14.4× exhausts that in ~2 days. Page on (1h burn > 14.4 AND 5m burn > 14.4); ticket on (6h > 6 AND 30m > 6). Two windows stop a single slow minute from paging.

Watermarks need their own alert. Flink's watermark advances to the minimum across inputs, so one idle Kafka partition stalls it forever while consumer lag stays at zero. Set withIdleness(...) and alert on watermark_lag = max_event_time − currentWatermark per operator. Zero consumer lag plus a stalled watermark means an idle or stuck partition, not a slow consumer.

At the batch boundary, alert on partition readiness (did the 10:00 partition land by 10:10?) and on freshness regression: a backfill that rewrites older data makes max event_time go backwards. Track it as a gauge and alert on any decrease.

Failure modes worth instrumenting: a consumer-group rebalance resets committed offsets and fakes a lag spike. Correlate with group generation before paging. Producer clock skew inflates freshness; watch emit-to-append delta. Sink commit latency can dominate end-to-end even when the stream is fully caught up, so measure commit duration separately from lag.

Curated: · Written: · Reviewed:

Difficulty: Hard