All posts
System Design Mastermind · F17
  • System design
  • Interview prep
  • Data pipelines
  • Streaming

Data pipelines: batch and stream

Foundations F17. The system behind every dashboard, fraud check and report: batch vs stream, MapReduce and Spark and the shuffle, data lakes, warehouses and lakehouses on Parquet, change data capture and schema evolution, event time, windows and watermarks, late data, state, checkpoints and exactly-once, Lambda vs Kappa and reprocessing, and orchestration, backfills and data quality. Each idea is told as a story you'll remember, with a lab that shows how long a pipeline should wait for late events.

23 Oct 2026 · 28 min read · interactive

Share

Start here

Every product you design has a second system behind it: the data pipeline that moves events and database changes into the places where they are counted, joined and served. Dashboards, fraud checks, search indexes, recommendations, finance reports and ML training data all come out of it. In interviews it shows up as "how would you count clicks per ad?", "how does the dashboard stay fresh?" or "how do you rebuild this after a bug?".

This page covers nine ideas: batch vs stream; batch processing with MapReduce and Spark; where pipeline data lives (lake, warehouse, lakehouse, columnar files); getting data in with change data capture and schemas; event time, windows and watermarks; late data; state, checkpoints and exactly-once; Lambda, Kappa and reprocessing; and orchestration, backfills and data quality. They belong together because of one trade-off the Google Dataflow paper put at the centre: correctness, latency and cost. You can't know when you've seen all the data, so every pipeline decides how long to wait, what to do with stragglers and how to fix the past.

Queues, partitions and delivery guarantees are on the queues page; what exactly-once really means is on the idempotency page. This page builds on both.

The one story for this page

Monsoon month at a dairy cooperative near Anand

A village dairy cooperative in Gujarat collects milk twice a day from four hundred farmers. Kanubhai tests every can at the counter; Bhavnaben, the society secretary, keeps the books; trucks take the milk to the district union's plant, which pays farmers every ten days and sends the head office its figures. Everything on this page happens in one rainy July:

  • The fat test at the counter vs the payment sheet every ten days. (batch vs stream)
  • Totalling a district's milk: each society adds up its own, then sends slips to the right clerk. (batch processing)
  • The raw-milk silo, the labelled godown and the register kept column by column. (lake, warehouse, columnar files)
  • Bhavnaben's carbon copies, and the day the slip got a new column. (CDC and schemas)
  • The morning shift, counted by when the milk was poured, not when the truck arrived. (event time, windows, watermarks)
  • The tractor stuck at the flooded causeway. (late data)
  • The clerk's bookmark in the tally book. (state, checkpoints, exactly-once)
  • The quick evening estimate and the accountant's exact recount. (Lambda and Kappa)
  • Pasteurise before packing, test before mixing, redo the three days the meter was wrong. (orchestration, backfills, data quality)

The cooperative and its people are a teaching story; the companies, papers, docs and numbers cited on this page are real.

✅ Seen: a company said so (cited)🔶 Inferred / typical🧭 Interview choice

Batch vs stream: bounded and unbounded data

Batch processes a bounded chunk of data after it has all arrived (yesterday's orders), so it's simple, cheap and easy to re-run; stream processing handles an unbounded flow as it arrives, so answers take seconds instead of hours, at the price of always-on jobs and harder questions about time; pick by how fresh the answer must be.

The story · remember it like this

The fat test and the payment sheet

When Ramesh pours his can at the counter, Kanubhai tests the fat and SNF right there and the screen shows the rate. If the milk is watered down, Ramesh hears about it now, not next week. That's stream processing: each event handled as it arrives, answer in seconds.

Every ten days, Bhavnaben closes the books: she takes all the slips for those ten days, adds up each farmer's litres and fat, applies the rate chart and prints the payment sheet. She waits until the period is over, so nothing is missing, and if the rate chart was wrong she simply prints the sheet again. That's batch.

Nobody would pay farmers from the counter screen, and nobody would wait ten days to learn the milk was watered down. Same milk, same slips: what differs is how soon the answer is needed.

What it really is
  • Bounded data has an end (yesterday's files); unbounded data never ends (clicks, orders, GPS pings). The Dataflow paper's point: treat everything as unbounded and choose how long to wait, rather than pretending a stream is a pile of files.
  • Batch: a scheduled job reads a complete partition (an hour, a day), computes, writes the result. Simple to reason about, cheap (runs then stops), easy to re-run after a bug. Latency = schedule + wait + run time: hours.
  • Micro-batch: small batches every few seconds to minutes (Spark Structured Streaming's default trigger model, Uber's 1–2 minute Hudi ingestion). A middle ground for "minutes is fine".
  • Stream: a long-running job processes each event as it arrives and keeps running state. Latency of seconds or less; the job must handle out-of-order events, late data, state and failure while running forever.
  • How to choose: ask how stale the answer may be before it loses value. Fraud check before payment, surge price, live ops dashboard: seconds, so stream. Payouts, finance reports, training data: hours or a day, so batch. Many systems run both over the same events.
In a real system ✅ Seen · Uber; Zomato

Uber's 2018 post on its data platform describes moving from data that was 24+ hours old to "less than one hour" for derived tables, by switching from full reloads to incremental ingestion (Hudi).

Zomato's data platform team wrote in November 2024 that its Flink stream jobs have handled "a peak ingestion rate of more than 250M events per minute", for uses such as restaurant stress monitoring, ads delivery and abandoned-cart recovery: jobs that can't wait for a nightly batch.

Trade-offs
  • Batch: cheap, simple, complete and easy to re-run; answers are hours old and a bug is found a day late.
  • Stream: fresh answers and instant reactions; always-on cost, harder testing, and you must decide what to do about events that arrive late or out of order.
Say it in the interview

First I'd ask how fresh each output needs to be. The fraud score and the live dashboard need seconds, so they're stream jobs on Kafka with Flink. Payouts and the finance report can be a day old, so they're batch jobs over the same events in the lake, which also makes them easy to re-run.

Trap

Choosing streaming because it sounds more advanced, without a freshness requirement that needs it. Interviewers want the number that justifies the cost.

Batch processing: MapReduce, Spark and the shuffle

Big batch jobs split the input into partitions, run the same function on each in parallel (map), move all records with the same key to the same worker (the shuffle, usually the costly part), and combine them (reduce); failures are handled by re-running a task, which only works because tasks are deterministic and their inputs are kept.

The story · remember it like this

Totalling the district's milk

The district union wants total milk per farmer category (small, medium, large) across three hundred village societies.

One clerk reading three hundred registers would take a month. So each society totals its own register first: "small farmers 4,200 litres, medium 3,100, large 900" (map, done in parallel in every village). Then each society sends its "small" slip to the clerk handling small farmers, "medium" to the medium clerk, and so on (shuffle: every slip with the same key goes to the same desk). Each clerk adds up the slips on their desk (reduce).

If a clerk falls ill halfway, the union doesn't panic: the slips are still there, so another clerk redoes that pile. And when one desk is slow, the union gives a copy of the pile to a second clerk and takes whichever finishes first.

What it really is
  • Partitioned input: files split into chunks (for example 128 MB), one task per chunk, run where the data is when possible.
  • Map → shuffle → reduce: map emits (key, value) pairs; the shuffle sorts and moves them over the network so all values for a key meet on one worker; reduce combines them. Group-by, joins and distinct counts all need a shuffle; filters and per-record transforms don't.
  • The shuffle is the cost: network and disk. Data skew (one huge key, like one city with most orders) makes one task run for hours while the rest wait; fix with salting the key or pre-aggregating.
  • Fault tolerance by re-execution: tasks are deterministic and inputs are kept, so a failed task is simply run again; slow tasks (stragglers) get a backup copy.
  • Spark keeps intermediate data in memory across steps and remembers how each partition was computed (lineage), so a lost partition is recomputed instead of replicated. Much faster for multi-step and iterative jobs; SQL engines (Spark SQL, Trino, BigQuery) do the same planning for you.
In a real system ✅ Seen · MapReduce; Spark

Google's MapReduce paper (Dean and Ghemawat, OSDI 2004) sorted 10¹⁰ 100-byte records (about 1 TB) on about 1,700 machines in 891 seconds; the same sort took 44% longer with backup tasks disabled. It reported more than a thousand MapReduce jobs a day at Google.

The Spark paper (Zaharia et al., NSDI 2012) reports Spark "up to 20× faster than Hadoop for iterative applications" and scanning a 1 TB dataset interactively "with 5–7s latency"; lost data is rebuilt from lineage "without requiring costly replication".

Trade-offs
  • More partitions mean more parallelism but more scheduling overhead and more small files; aim for tasks of a few hundred MB.
  • In-memory engines (Spark) are fast but need RAM sized to the data being cached; spilling to disk keeps big jobs alive at a cost in speed.
Say it in the interview

The daily job reads yesterday's partition of order events, maps each to (restaurant_id, amount), shuffles by restaurant and sums. The shuffle is the expensive step, so I'd pre-aggregate before it and watch for skew from a few huge restaurants. Tasks are deterministic, so a failed task just re-runs.

Trap

Forgetting skew. "Group by city" where one city has 40% of orders means one task does 40% of the work; say how you'd split the hot key.

Where pipeline data lives: lake, warehouse, lakehouse

Raw events land cheaply in a data lake (files in object storage), cleaned and modelled tables live in a warehouse for fast SQL, and a lakehouse puts warehouse-style tables (ACID commits, schemas, time travel) directly on the lake's files; all three store data in columnar formats like Parquet, partitioned by date, so a query reads only the columns and days it needs.

The story · remember it like this

The silo, the godown and the register by column

At the plant, all the incoming milk first goes into the raw-milk silo: everything, untreated, kept so it can be processed any way later. Packed products go to the godown, sorted on labelled shelves (toned milk, ghee, paneer) so a shop's order is picked in minutes.

Bhavnaben's old register had one line per can: date, farmer, litres, fat, SNF, rate. To find the month's total fat she had to read every line. Her new register keeps each column on its own sheet: one sheet of litres, one of fat. Totalling fat now means reading one thin sheet, and a column of similar numbers is easy to abbreviate. She also starts a new book every month, so "July's fat" never touches June's pages.

Then the plant adds a rule: shelves change only when the godown keeper signs the entry book, so nobody ever sees a half-stocked shelf.

What it really is
  • Data lake: raw and lightly cleaned files in object storage (S3, GCS, ADLS). Cheap, any format, keep everything; on its own, no transactions, so readers can see half-written data.
  • Warehouse: modelled tables (facts and dimensions) in a SQL engine built for scans and aggregations (BigQuery, Snowflake, Redshift). Fast and governed; costs more per TB.
  • Lakehouse / table formats: Delta Lake, Apache Iceberg and Apache Hudi add a transaction log or metadata layer over Parquet files: atomic commits, schema enforcement and evolution, time travel, and upserts and deletes on the lake.
  • ETL vs ELT: transform before loading (ETL) or load raw data first and transform with SQL inside the warehouse or lakehouse (ELT, common today because storage is cheap and raw data lets you re-derive).
  • Columnar files (Parquet, ORC): values stored column by column in row groups, compressed per column; a query reading 3 of 80 columns reads a few percent of the bytes, and min/max stats let it skip row groups.
  • Partitioning by date (and sometimes region) lets a query on one day skip the rest. Too many tiny files or partitions is a classic slowdown; compact them.
  • OLTP vs OLAP: never run heavy analytics on the production database; copy the data out (next concept).
In a real system ✅ Seen · Delta paper; Uber

Parquet's docs describe a file as row groups, each split into one column chunk per column, divided into pages, and recommend "large row groups (512MB - 1GB)" and 8 KB pages.

The Delta Lake paper (Armbrust et al., PVLDB 2020) explains why plain object stores aren't enough: they offer per-key eventual consistency and "multi-object updates are not atomic", and a LIST returns at most 1,000 keys per call. Delta adds a transaction log over Parquet for ACID tables and time travel, and the paper says it ran at thousands of Databricks customers processing "exabytes of data per day".

Uber's 2018 data-platform post: before incremental ingestion, each run rewrote a whole table of over 100 TB, taking over 20 hours on more than 1,000 Spark executors, though only about 100 GB of new data arrived per table per day. Hudi's upserts let it ingest just the changes.

Trade-offs
  • Lake: cheapest and most flexible, but without a table format you get half-written reads and no updates; warehouse: fastest SQL and governance, but data is copied in and costs more.
  • Fine partitions make single-day queries cheap but create many small files and slow planning; partition by what queries filter on, usually date.
Say it in the interview

Raw events land in S3 as Parquet, partitioned by date, in Iceberg tables so writes are atomic and we can time-travel and upsert. Cleaned and modelled tables are built from those with SQL (ELT), and dashboards query them through the warehouse engine. The production database is never used for analytics.

Trap

Running reporting queries on the production OLTP database, or storing analytics as row-oriented JSON that every query must read in full.

Getting data in: change data capture and schemas

To copy a database into the pipeline, don't dump whole tables nightly or dual-write from the app: read the database's own change log (CDC), starting from a consistent snapshot, and publish every insert, update and delete as an event; and agree on schemas that can evolve without breaking the readers.

The story · remember it like this

Bhavnaben's carbon copies, and the new column

The district office used to send a man every night to photocopy Bhavnaben's whole register. It took hours, the photocopy was a day old, and a correction she made at 7 pm to a morning entry was easy to miss.

Now she writes every entry, and every correction, on a slip with a carbon copy. The carbons go to the district office in order, every few minutes. To start, the office copied the register once, and since then it just applies carbons in sequence. Nothing is missed, and her day isn't interrupted.

In July the union adds a new column to the slip: SNF. The district clerks still have to read last week's slips, which don't have it. So the rule is: new columns must have a sensible blank value, and the clerks learn the new slip before the villages start using it.

What it really is
  • Why not dual writes: an app that writes the database and then Kafka will, on some failures, do one and not the other; the copies drift (the queues page covers the outbox fix).
  • Why not nightly dumps: slow, heavy on production, a day stale, and they miss intermediate changes and hard deletes.
  • Log-based CDC: read the database's replication log (PostgreSQL WAL via logical decoding, MySQL binlog) and emit one event per committed row change, with before/after values, in commit order per key. Tools: Debezium on Kafka Connect, cloud DMS services.
  • Snapshot, then stream: take a consistent snapshot of the tables, then continue from the log position where the snapshot was taken, so the copy is complete and nothing is double-applied.
  • Operational catch: the database keeps log segments until the CDC reader confirms them; if the connector stops, the log (and disk use) grows. Monitor replication lag.
  • Schemas and evolution: put a schema on every topic (Avro, Protobuf, JSON Schema) in a schema registry, and enforce a compatibility rule so producers can't break consumers: add fields with defaults, don't rename or change types. A data contract is that agreement made explicit with the producing team.
In a real system ✅ Seen · Debezium; Confluent

Debezium's PostgreSQL connector docs (stable release 3.7, checked Oct 2026) say it uses PostgreSQL's logical decoding, which "allows the extraction of the changes that were committed to the transaction log", through a replication slot; on first connection "the connector takes a consistent snapshot", then "continuously captures row-level changes that insert, update, and delete database content".

Confluent's Schema Registry docs (Platform 8.3) say the default compatibility type is BACKWARD (consumers on the new schema can read data written with the previous one) and advise that you "upgrade all consumers before you start producing new events".

Trade-offs
  • Log-based CDC is complete and light on the database, but ties consumers to the table's internal shape; publishing curated domain events (via an outbox) is cleaner for other teams but more work.
  • Strict schema compatibility blocks some changes outright; loose schemas let bad data flow downstream and break jobs at 3 am.
Say it in the interview

Orders live in Postgres. Debezium snapshots the table once and then streams every committed insert, update and delete from the WAL into Kafka, keyed by order ID, with Avro schemas in a registry set to backward compatibility. The lake and the search index both consume that topic. We alert on replication-slot lag so the WAL can't fill the disk.

Trap

"A cron job runs SELECT * every night" or "the service writes to the database and to Kafka". Both lose or skew changes; name CDC or the outbox.

Event time, windows and watermarks

Group events by when they happened (event time), not when they reached you (processing time), into windows (tumbling, sliding or session); since events arrive out of order, a watermark is the pipeline's estimate that "nothing older than T is still coming", and a window's result is published when the watermark passes its end.

The story · remember it like this

The morning shift, counted by when the milk was poured

The plant reports milk per shift: morning (6 to 9 am) and evening. Most societies' trucks arrive by 9:30. Societies across the river send a tractor that reaches the plant around 10:15.

If the plant counted milk by when it arrived, the far villages' morning milk would land in the "late morning" count, and on a day the tractor is slow it would even fall into the afternoon. So every can is counted by when it was poured at the village, written on the slip.

But when can the plant manager close the morning count? Never waiting means always missing the river villages. Waiting till evening means the morning report is useless. So she sets a rule: "close the morning count at 10:30; by then nearly everything poured before 9 has arrived." That 10:30 rule is a watermark.

What it really is

Two clocks. Event time: when it happened, stamped by the producer (phone, server). Processing time: when the pipeline sees it. They differ by network delay, retries, batching and phones that were offline, and the gap varies.

Windows cut an endless stream into pieces you can count:

  • Tumbling: fixed, non-overlapping (orders per minute).
  • Sliding (hopping): fixed length, overlapping (last 10 minutes, every minute); one event lands in several windows.
  • Session: per key, closed by a gap of inactivity (a user's visit ends after 30 idle minutes).
  • Global with custom triggers, for "emit every 1,000 events".

Watermarks decide when a window is done:

  • Watermark: a moving timestamp W meaning "events with time ≤ W are not expected any more". Usually "largest event time seen minus a bound" (bounded out-of-orderness). When it passes a window's end, the window fires.
  • The trade-off: a watermark that lags a lot is complete but slow; one that hugs real time is fast but leaves late events out. It's a heuristic, not a guarantee, which is why late data needs its own policy (next concept).
  • Processing-time windows are simpler and fine for operational metrics like "requests per second right now", but results change if you replay the data.
In a real system ✅ Seen · Dataflow; Flink docs

The Dataflow Model paper (Akidau et al., PVLDB 2015, from Google) argues that pipelines must stop trying to "groom unbounded datasets into finite pools of information" and instead give explicit choices among correctness, latency and cost; Apache Beam implements this model, and Flink's event-time model works the same way.

Flink's docs define event time as "the time that each individual event occurred on its producing device", and say "a Watermark(t) declares that event time has reached time t", meaning no more elements with timestamp ≤ t should arrive; they note event-time processing "incurs some latency while waiting for out-of-order events". The window docs define tumbling, sliding and session windows as above.

Trade-offs
  • Event time gives correct, replayable results but needs watermarks and buffering; processing time is instant and simple but wrong whenever delays vary, and changes on replay.
  • Small windows are fresh but noisy and create more results to store; large windows are smoother and later.
Say it in the interview

We count clicks per ad in one-minute tumbling windows by event time, the timestamp from the client, with a watermark of max event time minus 10 seconds. So each minute's count is published about 10 seconds after the minute ends, and replaying the same events gives the same counts.

Trap

Bucketing by arrival time ("the server's clock when the message was consumed"). A consumer lag spike or a replay then moves events into the wrong minutes.

Late data: wait, correct or drop

Some events always arrive after the watermark; you choose per output whether to wait longer (slower), publish early and send corrections as late events arrive (allowed lateness, so the sink must accept updates), or drop them and reconcile in batch later, and you measure how many arrive late.

The story · remember it like this

The tractor at the flooded causeway

One morning the river crossing floods and the tractor from three villages reaches the plant at 1 pm. The morning count closed at 10:30.

The manager has three choices:

  • Wait: on monsoon days, close the morning count at 1:30 instead. Complete, but the head office gets its numbers three hours late, every day it rains.
  • Correct: send the 10:30 count as usual, then, when the tractor arrives, send a corrected morning total. The head office must replace the old number, not add a second one. She stops accepting corrections for a shift after two days and puts the register for that shift away.
  • Note it separately: write the tractor's milk in a side register; the accountant folds it into the ten-day payment sheet, which is exact anyway.

What she must not do is quietly pour the tractor's milk into the afternoon count.

What it really is
  • Late event: its event time is already behind the watermark when it arrives.
  • Allowed lateness: keep a window's state for an extra period after it fires; each late event updates it and re-emits the result. Downstream must treat re-emitted results as updates (upsert by window and key), not new rows.
  • Drop: after allowed lateness, events are discarded; capture them in a side output (dead-letter style) and count them, so "how much did we drop?" has an answer.
  • Triggers: emit early speculative results (every 10 seconds), the on-time result at the watermark, and late corrections; Beam calls these early, on-time and late panes.
  • Reconcile in batch: a nightly job recomputes yesterday from the stored events (now complete) and overwrites the day; the stream gives fast numbers, the batch gives final ones.
  • Measure: track the event-time vs arrival-time gap; it tells you the right wait and lateness. Mobile clients that buffer offline produce the long tail.
In a real system ✅ Seen · Flink docs

Flink's window docs: "by default, the allowed lateness is set to 0" and "late elements are dropped when the watermark is past the end of the window". With lateness set, a late element "may cause the window to fire again", and those results "should be treated as updated results of a previous computation"; to do this, "Flink keeps the state of windows until their allowed lateness expires". Dropped elements can be captured with a side output.

The Dataflow paper's own framing is the lab below: waiting longer buys correctness with latency, keeping windows open buys it with cost (state), and dropping trades correctness away.

Trade-offs
  • Waiting longer: simple, one final answer, but every result is later.
  • Corrections: fast and eventually complete, but every consumer must handle updates, and window state grows with the lateness you allow; dropping is cheapest and quietly wrong unless counted.
Say it in the interview

Most click events arrive within seconds, but app events from phones that were offline can be hours late. So the dashboard gets an on-time result 10 seconds after each minute, late events update that minute for 24 hours (the sink upserts by ad and minute), anything later goes to a side output, and billing uses the nightly batch recount, not the stream.

Trap

Saying nothing about late events, or having late corrections appended as new rows so totals double count.

Try it: how long should the pipeline wait?

Pick a pipeline. The lab works out how old each result is when first published, what share of events make it, how many arrive later as corrections or are never counted, and how much window state a stream job must hold, then says which limit you hit first. Switch between stream and batch to see the same trade-off from both sides.

Start from

Screen views per minute from a mobile app, by screen and city. About 8% of events come from phones that were offline (in a metro tunnel, on a flight) and arrive half an hour late on average. Wait 5 s, publish, and drop anything later.

Run it as
What we're sizingNumberHow we got itSo we decide
1 · Freshness
Oldest event in a result, when first publishedA window can't be reported before it ends, and the pipeline then waits a little for stragglers. Long windows and long waits buy completeness with freshness.1.1 min
window 1.0 min + wait 5.0 s = 1.1 min (target 2.0 min)
Meets the freshness target.
2 · Completeness
Events in the first result, corrected later, never countedMost events arrive in seconds; the few from phones that were offline arrive much later, and they decide how complete a fast answer can be.91% · 0% · 8.7%
first result 91% corrections 0% dropped 8.7%
an event is late if its delay is longer than the time left in its window + the wait. Averaged over the window: share × (mean ÷ window) × e^(−wait ÷ mean) × (1 − e^(−window ÷ mean)), for each kind of event
normal: 92% × (3 s ÷ 60 s) × e^(−5 ÷ 3) × … = 0.87%
offline phones: 8.0% × (1,800 s ÷ 60 s) × e^(−5 ÷ 1,800) × … = 7.8%
no allowed lateness: the 8.7% that miss the first result are dropped
Too many lost (17K/s): wait longer, or allow lateness and send corrections.
3 · Cost of waiting
Window state held in the stream jobA stream job must remember every window that can still change. Long allowed lateness on many keys is what makes state, and checkpoints, huge.1.39 MB
windows open per key = 1 + (wait 5 s + lateness 0 s) ÷ window 60 s = 1.08
20K keys × 1.08 × 64 B = 1.39 MB (budget 50.0 GB)
Fits.
4 · Verdict for this setup
What you getAnswers stay short: 8.7% of events are never countedWaiting 5.0 s after each window catches 91% of events; with no allowed lateness, 8.7% (17K events a second) arrive after the window has closed and are dropped, against a limit of 0.50%. Or publish early and keep windows open for late data (allowed lateness), sending corrected results downstream; send anything later still to a side output for a batch fix.

Try: on App events, eager, raise the wait to 60 s (barely helps: the offline phones are half an hour behind, not seconds), then to 3,600 s (complete, but now too stale). On Live orders, set the target to 30 s. On Per-user, a week late, cut allowed lateness to 1 day (86,400 s). On Daily report, set the target to 1 hour (3,600 s): no schedule fixes that, so switch to Stream job with 60 s windows, a 30 s wait and 1 day (86,400 s) of allowed lateness. Model: rounded teaching values; arrival delays are a mix of two exponential curves (real tails are often heavier), every key has data in every window, and state is a small fixed summary per key, not raw events.

State, checkpoints and exactly-once

Stream jobs keep state (counts, windows, join buffers) and survive crashes by periodically checkpointing that state together with their input positions; after a failure they restore and replay from there, so each event affects the state exactly once even though some are processed twice, and the guarantee reaches the outside world only if the sink is transactional or idempotent.

The story · remember it like this

The clerk's bookmark in the tally book

At the plant, a clerk keeps a running tally of litres per society as slips come in. Every hour he draws a line and writes, together, the totals so far and the number of the last slip he counted.

At 3:40 the power goes. When it's back, he doesn't start from zero, and he doesn't guess. He goes to the 3 pm line, takes those totals, and re-reads the slips after the one noted there. Some slips get read twice (the ones between 3 and 3:40), but each is counted once in the totals, because the totals and the bookmark were saved together.

He also used to phone the head office after every slip. Those calls can't be un-made: after the power cut, they made some calls twice. So now he writes the figures on a sheet and only sends the sheet when the hourly line is drawn.

What it really is
  • State: anything a job remembers between events (per-key counts, open windows, the other side of a join). Kept in memory or on local disk (RocksDB), sharded by key like the input.
  • Checkpoints: the job periodically snapshots all operator state plus the source offsets, consistently. Flink injects barriers into the stream so each operator snapshots at the same logical point without stopping.
  • Recovery: restore the last checkpoint, rewind the sources to the saved offsets, replay. Events after the checkpoint are processed again, but the restored state hasn't seen them, so the state ends up as if each event was applied once. Needs a replayable source (Kafka, Kinesis), not a fire-and-forget socket.
  • End to end: outputs written since the last checkpoint will be written again on replay. Either the sink takes part in the checkpoint (a transactional sink: pre-commit, then commit when the checkpoint completes, like Kafka transactions), or writes are idempotent (upsert by key, deterministic IDs).
  • The precise claim: "exactly-once" in stream processing means exactly-once effect on state and transactional outputs, not that code ran once; external side effects (emails, payment calls) still need idempotency keys.
  • Costs: checkpoint interval vs replay time; transactional outputs are visible only at commit, so downstream latency is at least the checkpoint interval.
In a real system ✅ Seen · Flink; Kafka

Flink's checkpointing docs say checkpoints let Flink "recover state and positions in the streams", need "a persistent (or durable) data source that can replay records", and that "exactly-once is preferable for most applications", with at-least-once only for consistently few-millisecond latency needs.

Flink's 2018 post on end-to-end exactly-once (Nowojski and Winters) defines the goal as "each incoming event affects the final results exactly once", and explains the two-phase commit sink: pre-commit when a checkpoint starts, commit when it completes, built on the transactions Kafka added in 0.11.

Confluent's 2017 post on Kafka transactions (Mehta and Gustafson) measured about a 3% throughput drop for 1 KB records committing every 100 ms, and says that with side effects in other systems these APIs "are not sufficient to guarantee exactly-once processing".

Trade-offs
  • Frequent checkpoints mean less replay after a crash but more overhead and, for transactional sinks, lower output latency; rare checkpoints are cheap but recover slowly and delay committed output.
  • Transactional sinks give clean results but add latency and only work with systems that support transactions; idempotent upserts work almost anywhere but need a natural key.
Say it in the interview

The Flink job checkpoints its state and Kafka offsets every 30 seconds to S3. On a crash it restores and replays from those offsets, so counts are exactly-once in state. Output goes to Kafka with transactions, committed on each checkpoint, and the database sink upserts by (ad_id, minute), so replays overwrite rather than add. Sending alerts is a side effect, so it carries an idempotency key.

Trap

"Kafka gives exactly-once, so we're covered." It covers Kafka-to-Kafka read-process-write; a database write, an email or a payment call outside that boundary still repeats on replay.

Lambda, Kappa and reprocessing

Lambda runs a batch path (exact, slow) and a stream path (fast, approximate) side by side and merges them, at the cost of writing the logic twice; Kappa keeps one stream path and reprocesses by replaying the retained log into a new output and switching over; either way, plan how you'll recompute history when code changes.

The story · remember it like this

The quick evening estimate and the accountant's recount

Every evening Kanubhai phones the union with a quick estimate of the day's milk from the counter screen. Every ten days the accountant recounts from the slips, exactly, and that number is the one farmers are paid on. The union reads both: today's estimate, the accountant's figure for older days.

It works until the union changes the bonus rule. Now Kanubhai's screen and the accountant's ledger must both change, the same way, on the same day. One of them always gets it slightly different, and the two numbers stop matching.

So the union tries something else: keep every slip for a month. When a rule changes, a second clerk recounts from the first slip of the month with the new rule into a fresh ledger. When he has caught up to today, everyone switches to his ledger and the old one is thrown away. One set of rules, one way of counting.

What it really is
  • Lambda architecture: every event goes into a batch layer (recomputes everything from the master dataset, exact) and a speed layer (stream, covers only the last few hours); queries merge both. Robust, but two codebases computing "the same" thing in two engines drift.
  • Kappa: only a stream processor; keep the input log long enough (days to forever, with tiered or compacted storage). To change logic, start a second job from the beginning of the log writing to a new table, let it catch up, switch readers, delete the old job and table.
  • Today's common shape: one engine or one SQL definition for both (Flink and Spark run batch and stream; Beam's model is the same for both), events kept in a lakehouse table, and batch jobs used for backfills and reconciliation rather than a full parallel layer.
  • Reprocessing is a requirement: bugs, new metrics and changed definitions all need history recomputed. Ask: is the raw input kept, for how long, and can the job be re-run deterministically?
In a real system ✅ Seen · Kreps; Uber

Jay Kreps's July 2014 O'Reilly post "Questioning the Lambda Architecture" describes Lambda as records fed "into a batch system and a stream processing system in parallel", argues that keeping the same logic in two systems is the real problem ("I don't think this problem is fixable"), and proposes reprocessing by replaying a retained Kafka log into a new output table, then switching; to reprocess 30 days, keep 30 days. He notes LinkedIn kept "more than a petabyte of Kafka storage online".

Uber's 2017 Hudi post describes Lambda-style batch pipelines running "once every few hours" with a stream layer to cover that gap, and Hudi's incremental mini-batches of "one to two minutes" as a way to need less of both.

Trade-offs
  • Lambda: an exact batch safety net and simple batch code, but two implementations that must agree.
  • Kappa: one codebase, but needs long log retention, a stream engine that can replay fast, and enough spare capacity to run two copies of a job during reprocessing.
Say it in the interview

I'd avoid two codebases. Events are kept in Kafka for 7 days and permanently in an Iceberg table. The Flink job serves fresh results; to change logic we run the new version from the table and the log into a new output, compare, then switch the alias. A nightly batch over the table reconciles billing-grade numbers with the same SQL.

Trap

Proposing Lambda without mentioning the cost of keeping two implementations in sync, or Kappa without saying how long the log is retained.

Orchestration, backfills and data quality

Batch pipelines are DAGs of tasks run by a scheduler; each task should process one fixed time partition and overwrite its output (idempotent), so retries and backfills are safe, and quality checks (row counts, nulls, freshness, schema) stop bad data before it spreads to every table downstream.

The story · remember it like this

Pasteurise before packing; redo the three bad days

The plant's day has an order nobody argues with: test the tanker, then pasteurise, then pack, then dispatch. Packing can't start because it's 8 o'clock; it starts when pasteurising for that batch is done.

The lab tests every tanker before it's emptied into the silo. One tanker shows urea: it's turned away at the gate. If it had gone in, the whole silo, and everything made from it, would be thrown away.

In August they find the fat meter at one society was mis-calibrated for three days. The accountant doesn't add correction entries on top of the old sheets: she reprints those three days' sheets from the slips, and each new sheet replaces the old one. Doing it twice by mistake gives the same sheets, not double payments.

What it really is
  • DAG and scheduler: tasks with dependencies (extract → clean → join → aggregate → publish) run by Airflow, Dagster, Argo or a cloud scheduler; a task starts when its inputs are ready (data-aware or sensor triggers), not just at a clock time.
  • Idempotent tasks: each run handles one logical partition (for example data_interval_start = 2026-10-22) and overwrites that partition (INSERT OVERWRITE, MERGE/upsert), never appends. Never read "the latest data" or call now() for business logic, or a re-run computes something different.
  • Backfill: re-run a range of past partitions after a bug fix or a new metric; idempotent tasks make it a loop, and downstream tables re-run in dependency order.
  • Data quality checks: row counts vs yesterday, null and duplicate rates on keys, allowed values, referential checks, freshness ("today's partition landed by 6 am"). Block publishing on failure (write-audit-publish: write to staging, test, then swap) and alert the owner.
  • SLAs and lineage: each output has an owner and a landing time; lineage shows which dashboards a broken table feeds, so you know who to warn.
In a real system ✅ Seen · Airflow docs

Airflow's best-practices page (3.3.2, checked Oct 2026) says tasks "should produce the same outcome on every re-run", warns "Do not use INSERT during a task re-run" because it can duplicate rows and says to use UPSERT instead, advises "Never read the latest available data in a task" and to use data_interval_start as the partition, and says now() should never be used inside a task for critical computation.

MapReduce's re-execution model (above) relies on the same property: a task that is deterministic over a fixed input can be run again safely.

Trade-offs
  • Strict quality gates stop bad data but can block a whole morning's dashboards on one noisy check; tier checks into blocking and warning.
  • Time-triggered schedules are simple but run on incomplete inputs when upstream is late; data-triggered runs are correct but need upstream completeness signals.
Say it in the interview

The daily DAG runs per date partition: each task reads only that day and overwrites that day's output, so retries and backfills are safe. Before publishing, checks compare row counts with the last 7 days, null rates on keys and freshness; failures block the swap and page the owner. To fix last week, we backfill those seven partitions in order.

Trap

A job that appends to the output table, so a retry or backfill double counts; or a job that uses today's date instead of the partition it was asked to process.

Remember it

One line per idea. Read this the night before.

  1. Batch vs stream: choose by how fresh the answer must be; batch is cheap, complete and re-runnable, stream is fresh and always on.
  2. Batch processing: partition → map → shuffle by key → reduce; the shuffle and skew are the cost; failed tasks just re-run.
  3. Storage: raw in a lake, modelled in a warehouse, or both via a lakehouse table format (Iceberg, Delta, Hudi) over Parquet partitioned by date.
  4. Getting data in: log-based CDC (snapshot, then the WAL), never nightly dumps or dual writes; schemas in a registry with backward compatibility.
  5. Time: window by event time; a watermark says "nothing older is coming" and fires the window; it's a heuristic, not a promise.
  6. Late data: wait longer, publish and correct (allowed lateness, sinks upsert), or drop to a side output and reconcile in batch; measure it.
  7. Exactly-once: checkpoint state + offsets, replay after a crash; reaches outside only with transactional or idempotent sinks.
  8. Lambda = batch + speed layers, logic twice; Kappa = one stream job, replay the retained log into a new output; plan reprocessing either way.
  9. Orchestration: DAG of tasks, each overwriting one partition; backfills are a loop; quality checks block bad data before publishing.

Check yourself

Answer out loud, then open.

Design "ad clicks per ad per minute" for an advertiser dashboard and for billing. Batch or stream?

Both, over the same events.

  • Dashboard: stream. Clicks into Kafka, a Flink job with one-minute event-time windows, a watermark of a few seconds, allowed lateness of a few hours, results upserted by (ad, minute) into an OLAP store.
  • Billing: batch. A daily job over the complete day in the lake, de-duplicating by click ID and filtering fraud, overwrites that day's billing partition. It's the number of record.
  • Store raw clicks so both can be recomputed.

Say it stream for freshness, batch for the money; the same raw events feed both.

Your nightly job reloads a 100 TB table from the production database and takes 20 hours. What do you change?

Stop copying the whole table.

  • Use log-based CDC (Debezium on the WAL or binlog): snapshot once, then stream only inserts, updates and deletes.
  • Write them into a lakehouse table format that supports upserts (Hudi, Iceberg or Delta), merging changes in small batches.
  • Downstream jobs read only changed partitions or records (incremental), not the whole table.

That's the change Uber described in 2018: 100 TB rewrites of which only about 100 GB a day was new, replaced by incremental ingestion with latency under an hour.

A mobile analytics count per minute is always 5–8% lower than the nightly batch number. Why, and what are your options?

Late events. Phones that were offline send events minutes or hours later; once the watermark has passed their minute, the stream job drops them.

  • Measure the gap between event time and arrival time first.
  • Options: wait longer (later results); allowed lateness with corrections (sink must upsert, state grows); or keep dropping but send late events to a side output and treat the nightly batch as the final number.
  • Label recent minutes as provisional on the dashboard.

Say it the watermark is a heuristic; decide per output whether it's better late, corrected or dropped.

The interviewer says: "Your Flink job is exactly-once, so the emails it sends are exactly-once, right?"

No.

  • Flink's exactly-once covers its state: after a crash it restores the last checkpoint and replays, so each event affects the state once.
  • Anything the job did to the outside world since that checkpoint happens again on replay. Kafka sinks can join the checkpoint with transactions; databases can be written idempotently by key.
  • An email or a payment call can't be rolled back, so it needs an idempotency key checked by the sender (or by the provider), or it happens twice.

Say it exactly-once effect on state and transactional sinks; side effects still need idempotency.

Lambda or Kappa for a new metrics pipeline? Defend your choice.

Usually Kappa-style with a batch safety net, not two full layers.

  • One codebase: a stream job (Flink or Spark) defines the metric; events are kept in Kafka for days and in a lakehouse table for good.
  • Changing logic: run the new version over retained data into a new table, compare, switch.
  • Billing-grade or regulatory numbers: a nightly batch over the table with the same SQL, overwriting the day.
  • Lambda only if the batch side needs something the stream engine can't do; then budget for keeping both in sync.

Say it Kreps's point stands: the cost of Lambda is maintaining the logic twice.

A bug in the cleaning step corrupted the last seven days of a revenue table. How do you fix it, and what design makes that easy?

Fix the code, then backfill the seven date partitions.

  • Each task processes one date partition and overwrites it, so re-running 22–28 October replaces those days without touching others and without duplicates.
  • Run downstream tables for the same dates in dependency order (the orchestrator's backfill does this).
  • Add the check that would have caught it (null rate, revenue vs last week) as a blocking quality gate, and tell the owners of affected dashboards (lineage).

What makes it easy: raw inputs kept, deterministic tasks keyed by partition, INSERT OVERWRITE or MERGE instead of INSERT, no now() in business logic.

Why does the lab's "Per-user, a week late" pipeline run out of memory, and how would you fix it?

Every window that might still change has to stay in state.

  • 50 million users × (1 + (60 s + 7 days) ÷ 30 minutes ≈ 337 windows) × 200 bytes ≈ 3.4 TB.
  • Shorten allowed lateness to a day in the stream job (about 49 windows per user, roughly 490 GB) or less, and handle the long tail with a nightly batch recompute from stored events.
  • Or reduce state per window (sketches like HyperLogLog), or keep state on disk with RocksDB and accept slower checkpoints.

Say it allowed lateness is paid for in state; keep it short in the stream and let batch handle the stragglers.

Where you'll use this in the series

Sources

Checked October 2026. Mechanisms come from papers (MapReduce 2004, Spark RDDs 2012, the Dataflow Model 2015, Delta Lake 2020) and official docs (Apache Flink time, windows and checkpointing; Debezium 3.7 PostgreSQL connector; Confluent Schema Registry 8.3; Apache Parquet; Airflow 3.3.2 best practices). Company figures are as published on the dates shown: Jay Kreps / LinkedIn (2014), Uber (2017, 2018), Confluent (2017), the Flink project (2018) and Zomato (2024). Design Gurus is a third-party prep site, used only to cross-check what interviewers expect. The lab uses rounded teaching values and a simple model of arrival delays.

System Design Mastermind · Foundations

Series home

All of Foundations

18 publishedStart here: the concepts every design uses, each told as a story you'll remember.

F01

How a request travels: DNS, load balancers, gateways and open connections

Name → address (DNS) → open a secure line once and reuse it (TCP, TLS) → nearby copies for static files (CDN) → spread and guard the work (load balancer, gateway) → find colleagues inside (discovery) → keep a line open for live updates.

20 min · interactive Preview
F02

The interview framework: requirements, numbers and scope before boxes

Agree what users must do (three core requirements) → put numbers on how well (p99 latency, availability, durability, staleness) → say what's out of scope → sketch the simple end-to-end design → go deep only where a number breaks it.

22 min · interactive Preview
F03

Back-of-envelope estimation: from users to servers in one minute

Users × actions ÷ 86,400 (≈10⁵) = average per second → × peak factor → split reads and writes → storage = count × size × time × copies → bandwidth × 8 bits → in flight = rate × latency → servers = peak ÷ (capacity × 60%) + 2 spares.

20 min · interactive Preview
F04

APIs and real-time communication: REST, gRPC, retries, webhooks and live updates

Nouns + HTTP verbs (user from the token) → REST outside, gRPC inside → cursor pagination → POST with an Idempotency-Key, retries with backoff and jitter → add, don't change → poll for rare updates, SSE for one-way live, WebSockets for both ways → webhooks are at-least-once → thin connection gateways with resume and push fallback.

22 min · interactive Preview
F05

Databases: data models, indexes and transactions

Relational by default (each fact once, keys, constraints) → key-value / document / wide-column / graph only for a named access pattern → B-tree for reads, LSM for heavy writes → composite index with equality columns first, then the sort → one transaction per local change, made durable by the write-ahead log → know your isolation level → win races with a conditional write and a unique constraint.

24 min · interactive Preview
F06

Replication and sharding: copying and splitting your data

Copies scale reads and survive failures (leader + followers); splits scale writes and size (shards). Replicate first; shard only when data size or write rate outgrows one leader → pick the shard key from the main query → hash it into many fixed slots so growth moves ~1/(N+1) → name your hot key and your one cross-shard query.

25 min · interactive Preview
F07

Caching: hit ratios, invalidation and stampedes

Cache what is read far more than it changes → say the expected hit ratio and size the database for the misses → cache-aside with a TTL; on writes, update the database then delete the key → coalesce misses on hot keys and jitter TTLs → plan for the cache failing or restarting empty, because by then the system depends on it.

24 min · interactive Preview
F08

Consistency, CAP and quorums: what replicas promise

Say what each operation needs, not what the system is: strong (linearizable) for money, stock, seats and uniqueness; read-your-writes for a user's own data; eventual for counts, feeds and pages → during a partition, strong operations fail on the minority side, the rest keep serving (CAP) → on a normal day, strong costs a round trip to a quorum (PACELC) → with N copies, W + R > N makes reads overlap the latest write, but it isn't linearizability.

25 min · interactive Preview
F09

Coordination: clocks, leaders, locks and consensus

Don't order events across machines by wall-clock time; let one leader assign the order → elect that leader by majority vote with increasing terms, so a split network can't elect two → give it a lease so a dead leader is replaced without anyone proving it died → and a fencing token the storage checks, so a paused old leader can't do harm → use consensus (Raft) for the few decisions that must be agreed, not for every request.

25 min · interactive Preview
F10

Queues and event streams

Put a queue between work that can wait and the caller, so a spike becomes lag instead of an outage → use a task queue for jobs and an event log (Kafka) when many consumers need every event, replay or per-key order → key by the entity whose order matters and size partitions for peak consumers → deliver at least once and make consumers idempotent → retry a few times with backoff, then dead-letter → scale on lag → publish through an outbox, never "save, then publish".

25 min · interactive Preview
F11

Idempotency, exactly-once and sagas

Treat a timeout as unknown, never as failed → make writes idempotent by design (set, don't add; client IDs; conditional writes) → for the rest, an idempotency key per intent, stored with the result in the same transaction as the effect → consumers deduplicate by message ID in the same transaction → exactly-once holds only inside one boundary → across services, use a saga of local steps with compensations, not 2PC → compensable steps first, the pivot (capture payment) next, retryable steps last, on a durable orchestrator.

25 min · interactive Preview
F12

Scaling and performance

State latency as a percentile at a stated load → size each tier to the utilisation where its p99 is still flat (pooled, least-request balancing lets you run hotter) → budget fan-out calls against the page deadline, hedge stragglers → scale up first, scale out stateless tiers → name the shared resource (database, lock, connections) that caps the speed-up → find the saturated resource and cut work per request → pre-scale known peaks, autoscale on the signal that saturates → under overload, shed the lowest-priority work fast and budget retries.

24 min · interactive Preview
F13

Reliability and disaster recovery

Turn the target into a downtime budget → cut hard dependencies, because chains multiply → spread copies across zones (cells for blast radius) → timeouts from the deadline, one layer of jittered retries under a budget → circuit breakers with fallbacks and a bulkhead per dependency → fast, non-flapping health checks (readiness checks dependencies, liveness doesn't) → statically stable: spare capacity already running, config cached → PITR plus tested restores, because replicas copy mistakes → the cheapest DR strategy that meets RTO and RPO, drilled.

25 min · interactive Preview
F14

Observability and safe deployments

Metrics to notice, traces to locate, logs to explain (joined by a trace ID) → watch latency percentiles, traffic, errors and saturation → set an SLO per user journey and treat 1 − SLO as an error budget → page on burn rate over two windows, not on CPU → canary every change on a slice with automated analysis against a baseline → keep every version compatible with its neighbours (expand, migrate, contract) so rollback is always possible → ship dark behind flags, and stage config like code → when it breaks: one commander, mitigate first, blameless postmortem.

25 min · interactive Preview
F15

Security essentials for system design

Prove who the caller is (slow salted hashes, MFA, passkeys, rate-limited login) → carry identity in short-lived signed tokens with revocable refresh tokens, or in sessions you look up → delegate with OAuth code flow + PKCE, sign in with OpenID Connect → check this user against this object on every request, least privilege for people and services, audit logs → TLS 1.3 at the edge, mTLS inside, no trust from network location → envelope encryption with a KMS, secrets in a vault, tokenise what you needn't keep → treat all input as data (parameterise, encode, CSRF tokens, no user-chosen fetches) → absorb floods and abuse at the edge.

26 min · interactive Preview
F16

Search, feeds and geo building blocks

Search: analyse text into terms → inverted index of sorted postings → BM25 or hybrid (BM25 + vectors via RRF) retrieval of ~1,000 candidates → learned ranker → shards with replicas, fed from the database by CDC, refreshed every second. Typeahead: precomputed top-k per prefix in memory. Feeds: push IDs into followers' timelines, pull celebrities at read time, hydrate, filter, rank, page with cursors. Geo: index by cell (geohash, S2, H3), search the cell plus neighbours, exact distance on the few candidates.

27 min · interactive Preview
F17

Data pipelines: batch and stream

Pick batch or stream by how fresh each output must be. Get data in with log-based CDC (snapshot, then the WAL) and schemas that evolve safely; land raw events as Parquet in lakehouse tables partitioned by date. Batch jobs map, shuffle and reduce one partition and overwrite it, so retries and backfills are safe. Stream jobs window by event time, fire on watermarks, decide whether late events wait, correct or drop, and checkpoint state with offsets for exactly-once effect, with transactional or idempotent sinks. Reprocess by replaying retained data (Kappa) rather than keeping two codebases (Lambda).

You're reading this Preview
F18

AI foundations: inference, RAG and agents

Latency is time to first token (prefill reads the prompt, compute-bound) plus output tokens × time per token (decode, memory-bound), so stream answers and limit by tokens. GPU memory is weights plus a KV cache per request; long prompts, not users, fill it. Continuous batching shares each weight read across many requests, cutting cost per token by 10× or more until time per token hits its target. Route easy requests to small models, cache shared prompt prefixes, quantize carefully. RAG retrieves, reranks and cites a few permission-filtered chunks; agents are tool-calling loops with budgets, idempotent tools and approval for irreversible steps. Evaluate every change on an eval set, and design so a model fooled by prompt injection still can't do damage.

30 min · interactive Preview

More posts