Summary#
Batch processing runs a job over a bounded, already-collected dataset (yesterday's clicks, last hour's logs) and produces a complete result, typically minutes to hours after the data arrived. MapReduce introduced it at scale, and Spark is the standard tool today. Stream processing handles an unbounded flow of events continuously, producing results within milliseconds to seconds, with Flink and Kafka Streams as the main engines. Streams are harder because events arrive late and out of order, so stream processors group events into windows (tumbling, sliding, session) by event time, and use watermarks to decide when a window is complete. They keep state per key and protect it with checkpoints. The lambda architecture runs both a batch path and a streaming path. Kappa uses only a stream and replays the log to reprocess. Choose streaming only when fresh results are actually worth the extra complexity.
Why It Exists#
Raw events are useless until someone computes something from them: clicks per ad per minute, revenue per country per day, a fraud score per card, the top videos this hour. Two questions decide how to compute it. How fresh must the answer be? And how much data must each answer look at?
For a long time, the only practical answer was "overnight, over everything". Load the day's data, run a big job, publish the report in the morning. That works for monthly invoices, and it fails for a card-fraud check that must decide in 100 ms whether to approve a payment, or for an ad dashboard where advertisers expect to see a campaign's clicks a minute after launch.
Doing it naively in real time also fails. Suppose a service reads clicks from Kafka and keeps a counter per ad in memory for "clicks in the last 5 minutes". It works until:
- The process crashes, and five minutes of counts vanish. Rebuilding them means rereading the topic from the right offset, which the service now has to track itself.
- Traffic grows, and you add a second instance. The counters for some ads must move to the new instance, without double counting or losing updates in between.
- Events arrive late or out of order. A phone in a tunnel sends a 10:03 click at 10:09. Should it count in the 10:03 minute, which was already reported, or the 10:09 minute, which is wrong?
Batch and stream processing frameworks exist so that each team does not have to re-solve these problems. Batch frameworks make huge, bounded computations reliable and parallel. Stream frameworks make continuous, stateful computations reliable, rescalable and correct in the face of disorder.
How It Works#
The key difference is bounded versus unbounded data. A batch job's input has an end: it is "all clicks with a timestamp on 1 December". The job can read all of it, sort it, join it and output a final answer. A stream job's input never ends. It must produce answers while data keeps arriving, so it has to decide which events belong together and when an answer is complete enough to publish.
The two ends of a spectrum, with a middle ground:
| Style | Typical latency | Unit of work | Examples |
|---|---|---|---|
| Batch | Minutes to hours | A whole dataset or partition (a day, an hour) | MapReduce, Spark, Hive, BigQuery scheduled queries |
| Micro-batch | About 1 to 10 seconds | A small batch of recent events | Spark Structured Streaming (default mode) |
| Streaming | Milliseconds to about a second | One event at a time | Flink, Kafka Streams, Google Dataflow (Apache Beam) |
Batch processing#
A batch job takes a large, fixed input, splits it into pieces, processes the pieces in parallel on many machines, and combines the results. The model that made this practical is MapReduce, described by Jeffrey Dean and Sanjay Ghemawat in "MapReduce: Simplified Data Processing on Large Clusters" (OSDI 2004). You write two functions:
- map takes one input record and emits zero or more key-value pairs. For click counting, it reads one click and emits
(ad_id, 1). - reduce receives one key and all of its values, and emits the result. For
ad_id = 7, it receives[1, 1, 1, ...]and emits(7, 15230).
Between them, the framework runs the shuffle: it routes every pair with the same key to the same reducer, sorting and grouping them on the way. The framework handles splitting the input, scheduling tasks on machines close to the data, retrying failed tasks, and writing output.
Hadoop brought MapReduce, together with the HDFS distributed file system, to the open-source world. Hadoop MapReduce wrote intermediate results to disk between every stage, which made multi-step jobs slow. Apache Spark, introduced by Matei Zaharia and colleagues ("Resilient Distributed Datasets: A Fault-Tolerant Abstraction for In-Memory Cluster Computing", NSDI 2012), keeps intermediate data in memory where possible, plans a whole multi-stage job as a graph of steps (a DAG, directed acyclic graph), and exposes high-level APIs: DataFrames and SQL. A job that would have been five chained MapReduce jobs becomes one Spark job, often many times faster. Today, "batch processing" usually means Spark, or SQL run on a warehouse engine such as BigQuery, Snowflake or Trino.
Batch processing, in depth#
Sizing a batch job. Take an ad platform with 10,000 clicks per second at peak, averaging about 10,000 per second for simplicity. A day is about 864 million clicks. At about 100 bytes per click that is roughly 86 GB of raw data per day, much less in a compressed columnar format. A job that runs every 5 minutes processes about 3 million events, or 300 MB, which a single machine can aggregate in seconds. A framework like Spark is not required at that size. It earns its place when data grows, when jobs join several large datasets, or when the team wants one well-understood programming model across many jobs. The lesson: estimate before choosing a cluster, because many "big data" jobs fit on one large machine.
The shuffle is the expensive part. Map tasks read local data in parallel, which scales almost perfectly. The shuffle moves data across the network, so that every key's values meet in one place, and it often dominates a job's run time. Three techniques cut it down:
- Combiners (map-side aggregation). Each map task pre-sums its own pairs, emitting
(7, 812)instead of 812 separate(7, 1)records. For counting, this shrinks shuffle data by orders of magnitude. Spark does this automatically for aggregations likereduceByKeyandgroupBy().sum(). - Broadcast joins. Joining 86 GB of clicks with a 50 MB table of ads? Send the small table to every executor and join locally, with no shuffle of the large side. Spark does this automatically below a size threshold.
- Partition pruning. Store data partitioned by date (and maybe hour) so that a job over one day reads only that day's files. Columnar formats like Parquet also let a job read only the columns it needs.
Data skew. If one key has far more records than others, such as one viral ad or one huge customer, one reducer receives a large share of the data and the whole job waits for it. A job with 200 reducers where 199 finish in 2 minutes and one takes 40 minutes runs for 40 minutes. Fixes: salting (append a random suffix 0 to N to hot keys, aggregate per salted key, then aggregate again without the salt), adaptive query execution (Spark 3 can split skewed partitions automatically at run time), or handling known hot keys separately.
Fault tolerance by recomputation. Batch inputs are immutable, and tasks are deterministic functions of their inputs. So when a machine dies, the framework simply reruns its tasks elsewhere. Spark tracks each dataset's lineage, the chain of transformations that produced it, so that it can recompute a lost partition from its parents. Slow machines (stragglers) are handled with speculative execution: launch a duplicate copy of a slow task and take whichever finishes first. This only works because tasks are side-effect free. A task that sends emails or calls an API cannot be safely retried or duplicated.
Idempotent outputs and backfills. A good batch job writes its result for a time partition by replacing that partition, for example "overwrite date=2026-12-01", never by appending. Rerunning it then produces the same result, and that makes the operations that batch is famous for safe:
- Backfills: rerun the job for the last 90 days after fixing a bug.
- Reprocessing: recompute history with a new definition of a metric.
- Recovery: rerun a failed day without manual clean-up.
This rerun-from-raw-data property is the main reason batch remains the backbone of analytics, even in organisations with mature streaming. It is the easiest place to get a provably complete and correct answer.
Scheduling and dependencies. Batch jobs form pipelines: the "clicks per ad per day" job must wait for the "raw clicks ingested" step for that day. Orchestrators such as Apache Airflow, Dagster or cloud schedulers run jobs on schedules, track dependencies, retry failures and record which partitions are complete. The orchestrator is covered on Data Pipelines, Warehouses and Lakes.
Stream processing#
A stream processor runs a long-lived job that reads events from a source (usually Kafka or Kinesis), passes them through a graph of operators (filter, map, join, aggregate), and writes results to sinks (a database, a cache, another topic, an alerting system). The job never "finishes". It processes each event, or small group of events, as it arrives.
The basic building blocks:
- Sources and sinks: where events come from and where results go.
- Streams: the unbounded sequences of events flowing between operators.
- Operators: the transformations. Stateless operators, like filter or map, look at one event at a time. Stateful operators, like counts, joins or deduplication, remember things across events.
- Keyed streams: a
keyBy(ad_id)step partitions the stream so that all events for one key go to the same parallel operator instance. That instance owns the state for its keys, just as a Kafka partition owns its keys. This is how a stream job scales: ten instances each handle a tenth of the keys. - State: per-key data the job keeps, such as running counts, the contents of an open window, or the last seen value. The framework stores and protects it.
- Time and windows: rules for grouping an infinite stream into finite chunks, covered below.
A stateless job (read clicks, reformat, write to a database) is easy with a plain Kafka consumer. The engines earn their keep for stateful work, because they solve exactly the three problems listed in Why It Exists: state survives crashes through checkpoints, it is redistributed when you rescale, and it is computed by event time with watermarks, so out-of-order events land in the correct window.
The main engines:
- Apache Flink is a distributed stream processor with first-class event time, windows, large keyed state (stored in RocksDB on local disk), and exactly-once state through checkpoints. It runs as its own cluster, or as a managed service such as Amazon Managed Service for Apache Flink. It offers Java and Python APIs plus Flink SQL. See Flink.
- Kafka Streams is a library, not a cluster. You embed it in an ordinary Java application, and it reads from and writes to Kafka. State lives in local RocksDB stores, backed up to Kafka changelog topics, and the application scales by running more instances in a consumer group. It suits teams that already run Kafka and want processing without operating another cluster.
- Spark Structured Streaming runs streaming queries as a series of small batches (micro-batches), using the same DataFrame API as batch Spark. Latency is typically a second or more. It is attractive when a team already writes Spark batch jobs.
- Google Cloud Dataflow, running Apache Beam pipelines, is a managed service with one programming model for both batch and streaming. Beam pipelines can also run on Flink or Spark.
Stream processing, in depth#
Inside a Flink cluster. A JobManager coordinates the job. It schedules tasks, triggers checkpoints and handles failures. TaskManagers are the worker processes. Each one offers a number of slots, and each slot runs one parallel slice of the job. Each operator has a parallelism. A window operator with parallelism 32 runs 32 instances, each owning the state for a subset of keys. Flink groups keys into key groups, a fixed number set by the job's maximum parallelism, and assigns key groups to instances. Rescaling moves whole key groups between instances, which is why maximum parallelism must be chosen up front: it is the limit of how far you can scale out later. Consecutive operators with the same parallelism are chained into one task, so records pass between them as function calls rather than over the network.
Back-pressure. If a sink slows down, such as a database struggling, a stream job must not buffer without limit. Flink uses credit-based flow control: a downstream task grants its upstream task credits for buffers it can accept. When the credits run out, the upstream task stops sending, and the slowdown propagates back to the source, which simply reads Kafka more slowly. Kafka absorbs the difference, so consumer lag rises but nothing is lost. This is one of the strongest reasons to put a durable log in front of a stream processor: back-pressure turns a downstream outage into lag instead of data loss.
Kafka Streams' design. A Kafka Streams application models data as KStreams (every record is an event) and KTables (every record is an update to the latest value for its key, the stream-table duality from Change Data Capture). When a step changes the key, such as grouping clicks by advertiser instead of by ad, Kafka Streams writes the data to an internal repartition topic, so that the next step's partitions hold the right keys. State stores are RocksDB on local disk, with every update also written to a compacted changelog topic. If an instance dies, another instance rebuilds its stores by replaying the changelog. Standby replicas keep warm copies of the stores on other instances to make that failover fast.
Throughput expectations. A well-written Flink or Kafka Streams job commonly processes from tens of thousands to a few hundred thousand simple events per second per CPU core. Heavier serialisation, large state or remote calls drop that sharply. Scaling is by partitions: a 32-partition source supports up to 32 parallel source instances, so choose partition counts for growth. The usual bottlenecks are serialisation cost, state access (RocksDB reads on cache misses), skewed keys, and slow sinks. Remote calls per event, such as "look up the user in a database for every click", are the classic mistake. Use local state, async I/O with bounded concurrency, or a broadcast of slowly changing reference data instead.
Why not a plain consumer? For a mid-level design, "Kafka consumers that keep counts in memory and flush every minute" is a reasonable first answer. It stops being reasonable once you need correct event-time windows, durable state larger than memory, rescaling without losing counts, or exactly-once results. Building each of those by hand is possible, but error-prone. Saying exactly which of those properties the problem needs is how to justify bringing in Flink.
Windows#
A window turns an infinite stream into finite groups that can be aggregated. "Clicks per minute" groups events into one-minute windows, and each window produces one result per key.
- Tumbling windows are fixed-size and non-overlapping. Every event belongs to exactly one window, for example 10:00 to 10:01, then 10:01 to 10:02.
- Sliding windows (also called hopping windows) are fixed-size and overlapping, starting at a regular slide interval. A 10-minute window sliding every minute covers 10:00 to 10:10, 10:01 to 10:11, and so on. Each event belongs to window size divided by slide windows, here 10.
- Session windows are dynamic. They group a key's events that are close together, and close after a gap of inactivity. A user's clicks form one session until they are idle for 30 minutes. Each key has its own windows, of varying length.
- Global and count windows have no time boundary. They emit after every N events for a key, or by a custom trigger. These are less common, but useful for "every 100 readings, compute the average".
| Window type | Shape | Example question | Typical setting |
|---|---|---|---|
| Tumbling | Fixed size, no overlap | Clicks per ad per minute for billing | 1 minute, 1 hour, 1 day |
| Sliding (hopping) | Fixed size, overlapping, regular slide | Average latency over the last 5 minutes, updated every 10 seconds | Size 5 min, slide 10 s |
| Session | Per key, closes after an idle gap | Pages viewed per user visit | Gap 30 minutes |
| Count or global | Every N events or a custom trigger | Average of every 100 sensor readings | N = 100 |
Windows, in depth#
Incremental versus buffered aggregation. For aggregates that can be combined step by step, such as count, sum, min, max and average (stored as sum and count), the engine keeps a single running value per key per window, and updates it as each event arrives. Memory per window is tiny. For aggregates that need all the values, such as an exact median or an arbitrary function over the whole window, the engine must buffer every event until the window closes. That can be enormous. Prefer incremental aggregate functions, and use approximate structures (t-digest for percentiles, HyperLogLog for distinct counts) when you need distributions.
Sliding windows multiply state. Because each event belongs to size divided by slide windows, a naive sliding window keeps that many copies of the state. A 1-hour window sliding every minute keeps 60 running aggregates per key. A 30-day window sliding every minute keeps 30 x 24 x 60 = 43,200. For millions of keys, that is impractical. Three better approaches:
- Panes. Aggregate per slide interval (one-minute buckets) once, and compute each sliding window as the sum of its buckets. For sums and counts, maintain the window total incrementally: add the newest bucket and subtract the bucket that just fell out of the window. That is one addition and one subtraction per key per slide, no matter how long the window is.
- Two readers of the log. For a 30-day sliding count, one consumer group increments counters as events arrive, and a second consumer group reads the same topic 30 days behind and decrements. This needs 30-plus days of topic retention, but no stored buckets.
- Negotiate the product requirement. "Last hour" may need to slide, but "last month" rarely needs minute-level freshness. A tumbling daily window for "last month" changes almost nothing for users and costs far less. Suggesting this trade is a mark of seniority.
Session windows merge. When a new event arrives for a key, the engine creates a tiny session around it, of event time plus the gap. It merges that session with any existing session it overlaps. A late event can bridge two sessions into one. Session state therefore lives until the gap has passed in event time, which can be long for high-gap settings.
Emitting early, then final. A one-minute window normally emits once, when it closes. Dashboards often want partial results sooner. Triggers control when results are emitted: emit an early result every few seconds while the window is open, then a final result when the watermark passes the window's end, then corrected results if late events arrive. Consumers must then treat results as updates to a key (ad 7, minute 10:07) rather than as new facts, which means upserts in the sink. This is how a streaming design gets both a minute-level metric and near-real-time freshness: the current minute is simply incomplete until it closes.
Top-K per window. A common pattern, used for trending videos and popular hashtags, is to count per key per window and then keep the K largest. Do it in two stages. First, keyed count per item per window. Then a second keyed operator, keyed by window, maintains a min-heap of size K. If the input is partitioned by item ID, each partition's local top K can be merged into the exact global top K. Each item's full count lives in exactly one partition, so any item in the global top K must also be in its own partition's top K.
Event time versus processing time#
Every event has (at least) two timestamps:
- Event time: when the thing actually happened, such as when the user tapped the ad, recorded by the device or the first server that saw it.
- Processing time: when the stream processor handles the event, according to its own clock.
A third, ingestion time, is when the event entered the broker. It sits in between.
In a perfect world, they would be the same. In reality, the gap varies from milliseconds to days:
- Mobile devices go offline and upload a batch of events when they reconnect.
- Network retries and producer back-off delay some events by seconds.
- A consumer restarts, or a job is redeployed, and processes a backlog of 20 minutes of events in 2 minutes.
- A backfill replays last week's events today.
If you group by processing time, every one of these distorts the results. A backlog drained in 2 minutes makes those 2 minutes show 10 times the normal traffic, and the 20 minutes during the outage show almost nothing. Worse, processing-time results are not reproducible. Replaying the same events tomorrow gives different numbers, because they are processed at different times. Grouping by event time puts each event in the window it belongs to, however late it is processed, so a replay produces the same answer. That is why billing, metrics and analytics use event time.
Processing time still has uses: it is simpler, it never waits, and it is correct for questions that really are about now, like "how many requests did this server handle in the last 10 seconds?", used for load shedding.
Where event time comes from. Assign it as close to the source as possible, on the device or at the first server. Device clocks can be wrong, sometimes by hours or more. Production systems often record both the device time and the server receipt time, and clamp or correct device times that are implausibly far from the receipt time.
Watermarks and late data#
If events can arrive late, when is the 10:07 to 10:08 window complete? Waiting forever gives no results. Closing the window at 10:08 by the wall clock misses every late event. Stream processors answer with a watermark: a moving marker in event time that says "I believe all events with timestamps up to T have now arrived". When the watermark passes a window's end, the window fires.
The most common strategy is bounded out-of-orderness. Track the largest event timestamp seen so far, and set the watermark a fixed delay behind it, for example 30 seconds. The assumption is that events are at most 30 seconds out of order.
Late data. An event that arrives after the watermark has already passed the end of its window is late: its window has fired. There are three ways to handle it:
- Drop it, the default in many engines. This is simple, and fine when a few late events do not matter.
- Allowed lateness: keep the window's state for an extra period after it fires, for example 10 minutes. Late events within that period update the window and emit a corrected result. Sinks must accept upserts.
- Side output: send late events to a separate stream (a "late" topic) to be handled separately, for example merged by a batch correction job, or simply counted to monitor lateness.
The trade-off is latency against completeness. A short watermark delay (5 seconds) gives fast results, but more events arrive late. A long delay (5 minutes) captures almost everything, but every result is 5 minutes behind. Measure the actual distribution of event lateness (the gap between event time and ingestion time) and pick a delay that covers, say, 99.9% of events. Then handle the rest with allowed lateness or a batch correction.
Watermarks, in depth#
Watermarks across partitions. A source reading 32 Kafka partitions tracks a watermark per partition. The operator's watermark is the minimum across its inputs, because it can only claim completeness up to the slowest input. One consequence surprises people: an idle partition stalls everything. If one partition receives no events, its watermark never advances, so no window ever fires. Engines let you mark a source as idle after a timeout, so that it is excluded from the minimum until it receives data again.
Skewed sources. If one partition's events are hours behind the others, for example because it is replaying a backlog, the minimum watermark holds back all windows while the fast partitions' state piles up. Flink's watermark alignment can pause the fast sources until the slow one catches up, which bounds state growth.
Watermarks are heuristics. A watermark is a guess about completeness, not a guarantee, unless the source can genuinely know (for example, a file that is fully written). This framing comes from Google's work: Tyler Akidau and colleagues described it in "MillWheel: Fault-Tolerant Stream Processing at Internet Scale" (VLDB 2013), and then "The Dataflow Model: A Practical Approach to Balancing Correctness, Latency, and Cost in Massive-Scale, Unbounded, Out-of-Order Data Processing" (VLDB 2015). The Dataflow paper's key insight is to separate four questions:
- What is computed (the aggregation)?
- Where in event time is it grouped (the windows)?
- When in processing time are results emitted (watermarks and triggers)?
- How do refinements relate (do later results replace, add to, or retract earlier ones)?
Apache Beam implements that model directly, and Flink's design follows the same ideas.
A worked example of the trade-off. A mobile app's events have this lateness profile: 95% arrive within 5 seconds, 99.5% within 60 seconds, and 99.99% within 2 hours (phones that were offline). For a live dashboard, use a 10-second watermark delay, so that results appear about 70 seconds after each minute starts, and about 1% of events are late. Then allow 2 hours of lateness with upserts, so that the stored numbers converge to 99.99% complete. A nightly batch job recomputes each day exactly from the raw events, for billing. Each consumer sees the precision it needs, at the latency it needs.
Stateful processing and checkpoints#
Stateful operators hold data across events: counts per window, the contents of a join, the last value per key, a deduplication set of recently seen IDs. In Flink, this keyed state is partitioned with the stream, so each parallel instance holds the state for its own keys. State backends decide where it lives:
- Heap state stores objects in the JVM heap. It is fastest, but limited by memory and garbage collection.
- RocksDB state stores state in an embedded key-value store on local disk, with a memory cache. It can hold terabytes per job, at the cost of serialisation on every access.
State must survive failures. Flink takes periodic checkpoints: consistent snapshots of all operator state, together with the source offsets that state corresponds to, written to durable storage like S3 or HDFS. After a failure, Flink restarts the job, loads the latest checkpoint, rewinds the Kafka sources to the offsets recorded in it, and continues. Each event's effect on state is counted exactly once, because the state and the offsets were captured together. You can think of it like a tape recorder. Kafka is the tape, and the checkpoint records both the position on the tape and everything the job had computed up to that position.
A savepoint is a checkpoint you trigger manually and keep. It lets you stop a job, deploy new code, change parallelism, or move clusters, then resume from exactly where you left off.
Do you always need checkpoints? No, and saying so can show judgement. For a job with one-minute windows reading from a Kafka topic with 7 days of retention, losing in-flight state costs at most a minute or two of partial windows. The job could restart, rewind its consumer to a few minutes before the failure, and recompute, with an idempotent sink overwriting the affected minutes. Checkpoints matter most when state is large or long-lived, for example daily or weekly windows, large join state or deduplication sets, where recomputing from the log would take hours.
Stateful processing, in depth#
How Flink snapshots a running job. Pausing a whole distributed job to take a snapshot would stall it. Flink uses a variant of the Chandy-Lamport algorithm (K. Mani Chandy and Leslie Lamport, "Distributed Snapshots: Determining Global States of Distributed Systems", 1985), described for Flink by Paris Carbone and colleagues in "Lightweight Asynchronous Snapshots for Distributed Dataflows" (2015). Sources inject a checkpoint barrier into their output streams, a special marker that flows along with the records. When an operator has received barrier n on all of its inputs, it snapshots its state and forwards the barrier. Every record before the barrier is reflected in the snapshot, and every record after it is not. That gives a consistent cut through the job without ever stopping it.
- Alignment. An operator with several inputs must wait until the barrier arrives on all of them, buffering records from the inputs that are already past it. Under back-pressure, alignment can take a long time, so checkpoints take longer.
- Unaligned checkpoints let barriers overtake buffered records, and store those in-flight records as part of the snapshot. Checkpoints finish quickly even under back-pressure, at the cost of larger snapshots.
- Asynchronous and incremental snapshots. The state backend takes a quick local snapshot and uploads it in the background. With RocksDB, incremental checkpoints upload only the files that changed since the last checkpoint, so checkpointing a 1 TB state can mean uploading only a few GB.
Checkpoint interval trade-offs. A shorter interval (10 seconds) means less to reprocess after a failure, but more overhead and more load on the storage. A longer interval (5 minutes) is cheaper, but means more replay. With transactional sinks (below), the interval also sets output latency, because results are committed only when the checkpoint completes. A typical setting is 30 seconds to a few minutes.
End-to-end exactly-once. Checkpoints make state exactly-once. Making output exactly-once needs the sink's cooperation. There are two standard patterns:
- Idempotent sinks: upserts keyed by a deterministic ID, such as ad 7 and minute 10:07. Replays overwrite the same rows with the same values.
- Transactional sinks with two-phase commit: the sink writes into an open transaction, pre-commits when the checkpoint barrier arrives, and commits only when the JobManager reports the checkpoint complete. Flink's Kafka sink does this with Kafka transactions. Downstream consumers must read with
isolation.level=read_committed, and they see results only after each checkpoint.
See Delivery Semantics for the general theory. The same idea runs through all of it: replay plus idempotence, or replay plus atomic commit.
Deduplication state. Streams commonly deduplicate by event ID, for example dropping a duplicate click with the same impression ID. The dedup set is keyed state with a TTL, such as 24 hours. Size it from the numbers: 100 million unique IDs a day at 16 bytes each is about 1.6 GB of raw IDs, more with overhead, which is comfortable in RocksDB. Note that deduplication inside windowed processing only catches duplicates within its TTL. If duplicates can straddle window boundaries, dedup in a step before windowing, or dedupe at ingestion before events enter the stream.
Joins in streams. Joining two unbounded streams needs a bound, or state grows forever. Window joins match events that fall in the same window. Interval joins match an event with events from the other stream within a time range, for example "a click within 30 minutes after an impression". Temporal (lookup) joins enrich each event with the version of a table that was current at the event's time, such as currency rates or product data fed by CDC. Every join's state retention follows directly from its time bound.
Lambda versus kappa architecture#
When a system needs both fresh results and fully correct ones, two architectures are common.
Lambda architecture. Nathan Marz, who created Apache Storm, described it, and it is laid out in the book "Big Data" by Nathan Marz and James Warren (2015). It runs two paths over the same raw events:
- A batch layer stores the immutable master dataset of all raw events, and periodically recomputes complete, accurate views from scratch, for example with Spark every night.
- A speed layer processes recent events as a stream, for fast but possibly approximate or incomplete results.
- A serving layer answers queries by merging the batch view (accurate up to the last batch run) with the speed view (covering the time since).
The batch layer corrects whatever the speed layer got wrong: late events, bugs, dropped data. The cost is that every computation is written twice, once for batch and once for streaming, often in different frameworks. The two implementations must agree, and in practice they drift apart.
Kappa architecture. Jay Kreps proposed it in "Questioning the Lambda Architecture" (2014). The idea is to keep only the streaming path. Make the log (Kafka) the store of raw events, with enough retention to replay history, or with tiered storage to object storage. When the logic changes, or a bug needs fixing, start a second instance of the new job version reading from the beginning of the log, writing to a new output table. Once it catches up, switch readers to the new table and stop the old job. One codebase, and reprocessing is just "replay the log".
Lambda and kappa, in depth#
The modern "lambda-lite": stream for freshness, batch for reconciliation. Many production systems keep the spirit of lambda, but not its full serving-layer merge. Take an ad click aggregator. Flink writes per-minute counts to an OLAP store within seconds. Meanwhile, a connector (such as the Kafka Connect S3 sink, or Kinesis Data Firehose) archives every raw click into a data lake. Every hour or day, a Spark job recomputes the counts exactly from the archive and compares them with what Flink wrote. Discrepancies are investigated and the stored values are corrected. Advertisers get fresh numbers, and the money is ultimately computed from the batch truth. The streaming code and the batch code still both exist, but the batch job is a simple "recount everything", which is easy to get right.
When kappa struggles.
- Replay cost and time. Replaying a year of events at 1 million events per second takes long and costs compute. Plan for replay throughput well above live throughput, for example 10 times live speed, so that a reprocessing run finishes in days rather than weeks.
- Retention. Kafka was not originally built to keep years of data cheaply. Tiered storage, which offloads old segments to object storage, makes long retention practical. Alternatively, archive to a lakehouse table and replay from there, which blends back towards batch.
- Some computations are naturally batch. Training a model on a year of data, or a large join across history, is simpler and cheaper as a batch job than as a replayed stream.
Unified engines blur the line. Beam, Flink and Spark all treat batch as a special case of streaming: a bounded stream, where the watermark jumps to "infinity" at the end of the input. The same pipeline code can run in both modes. That makes a disciplined kappa-style design (one codebase, replay for backfills) achievable without the operational problems of a pure log, because the replay can read from files instead of Kafka. Lakehouse table formats such as Iceberg, Delta and Hudi support incremental reads, so a single job can consume "new rows since last time" from a table in near real time.
How to explain the choice. If correctness is critical and computations are simple, lambda-lite reconciliation is easy to justify. If the team wants one codebase and the log can be replayed affordably, use kappa. If neither fresh results nor reprocessing are required, use batch alone.
Choosing between batch and stream#
Start with the most important question: do you actually need real-time results? Stream processing is harder to build, test, debug and operate than batch. Many problems that sound like streaming are batch problems with a short schedule.
| Question | Points towards batch | Points towards streaming |
|---|---|---|
| How fresh must results be? | Hours or a day is fine | Seconds or less |
| Who or what consumes the result? | Reports, training data, invoices | Alerts, user-facing counters, fraud decisions, personalisation |
| Does the computation need all the data? | Yes: global sorts, large joins, exact distinct counts over years | No: per-key aggregates over bounded windows |
| How costly are errors? | High, and an exact, rerunnable answer is needed | Some approximation is tolerable, or reconciled later |
| What does the team know? | SQL and Spark | Has operated Kafka and Flink before |
| How spiky is the input? | Spikes only lengthen a job | Spikes need back-pressure and headroom |
The latency levers argument. A batch job every minute and a stream job with one-minute windows look similar on latency. The difference is how far each can go. Shrinking a stream job's windows, or emitting early results every few seconds, is a configuration change. Running Spark every few seconds is impractical, because job start-up and scheduling overhead dominate. So if the requirement may tighten, from minutes to seconds, streaming gives headroom that batch does not. And if it will not tighten, batch is often the cheaper, simpler and more correct answer.
Spikes behave differently. A burst of traffic makes a batch job's next window much larger, so the job may run longer than its interval, and runs start overlapping, falling further behind exactly when the data matters most (a big launch, a sale). A stream job with a durable log in front absorbs a spike as consumer lag. It falls behind smoothly, and catches up when the spike passes, if it has some headroom.
Micro-batch is a middle ground. Spark Structured Streaming's micro-batches give second-level latency with batch-style semantics and the same API as batch Spark. For dashboards refreshed every few seconds, it is often enough, and it avoids a second engine.
When to Use It#
Use batch when:
- Results are needed hourly or daily: reports, invoices, warehouse tables, model training sets, search index rebuilds.
- The computation needs the full dataset: global sorts, large joins, exact distinct counts over long periods.
- You need a provably complete answer that can be rerun: billing, reconciliation, regulatory reports.
- Data arrives in bulk anyway, such as nightly partner files or daily exports.
Use streaming when:
- A decision must be made within seconds: fraud checks, anomaly alerts, rate limits based on behaviour, surge pricing.
- Users see the number live: view counts, live leaderboards, delivery-time dashboards, trending topics.
- Downstream stores must be updated continuously from events or CDC: search indexes, feature stores, materialised views.
- The write rate is high enough that pre-aggregating in the stream saves the database. For example, 700,000 view events per second collapse into far fewer per-minute counts per video before reaching storage.
When NOT to Use It#
- Do not stream when batch is fresh enough. A daily report does not need Flink. A Spark job, or a scheduled SQL query in the warehouse, is cheaper to build and run.
- Do not reach for a cluster for small data. A few hundred MB per run fits on one machine. Use a single process or the database's own aggregation.
- Do not build exactly-once streaming when approximate is fine. For a "trending" widget, a small error is invisible. A count-min sketch, or dropping late events, is enough.
- Do not use stream processing as a general job runner. Long-running tasks with side effects, such as sending emails or calling APIs, belong in a job queue or a workflow engine (see Long-Running Tasks), not in a stream operator that may replay them.
- Do not route high-frequency ephemeral data through batch. A driver's location every few seconds, needed for matching right now, should be written to an in-memory store. Batching it into a database every 30 seconds makes matches use stale locations.
How to Implement It#
- Write down the freshness and correctness requirements, with numbers: "per-minute clicks per ad, visible within 10 seconds, billing-grade exact by the next morning".
- Pick the shape: batch only, stream only, or stream plus batch reconciliation.
- Define the event schema, including a reliable event time and a unique event ID for deduplication.
- Partition by the aggregation key (ad ID, video ID) all the way through: topic, stream job and output store. Plan for hot keys, with salted keys for known hot items.
- Choose windows and watermarks from the measured lateness distribution. Decide what happens to late events: drop, allowed lateness with upserts, or a side output.
- Make the sinks idempotent (upsert by key and window) or transactional, so that replays are safe.
- Configure state and checkpoints to match the state size and the acceptable recovery time. Use savepoints for deployments.
- Archive raw events to a data lake for backfills, audits and batch reconciliation.
- Monitor consumer lag, watermark delay (wall-clock time minus watermark), checkpoint duration and size, back-pressure, late-event counts, and output freshness.
-- Flink SQL: clicks per ad per minute, by event time, tolerating 30 s of disorder
CREATE TABLE clicks (
ad_id BIGINT,
click_id STRING,
event_time TIMESTAMP(3),
WATERMARK FOR event_time AS event_time - INTERVAL '30' SECOND
) WITH ('connector' = 'kafka', 'topic' = 'clicks', 'format' = 'json'
-- plus bootstrap servers and group id
);
INSERT INTO ad_clicks_per_minute -- an upsert sink keyed by (ad_id, window_start)
SELECT ad_id,
window_start,
COUNT(*) AS clicks
FROM TABLE(
TUMBLE(TABLE clicks, DESCRIPTOR(event_time), INTERVAL '1' MINUTE))
GROUP BY ad_id, window_start, window_end;| Technology | Fits when |
|---|---|
| Apache Spark (batch) | Large batch ETL, joins and aggregations over a data lake; the default batch engine |
| Warehouse SQL (BigQuery, Snowflake, Redshift, Trino) | Batch transformations that are naturally SQL, scheduled inside the warehouse |
| Apache Flink | Low-latency stateful streaming with event time, large state and exactly-once results |
| Kafka Streams | Streaming inside ordinary Java services, input and output in Kafka, no separate cluster |
| Spark Structured Streaming | Second-level latency is enough, and the team already uses Spark |
| Google Cloud Dataflow (Apache Beam) | Managed, unified batch and streaming on GCP; portable pipelines |
| Amazon Managed Service for Apache Flink, Kinesis Data Firehose | Managed Flink on AWS; Firehose for simple delivery of streams into S3 or warehouses |
| ksqlDB, Flink SQL, RisingWave, Materialize | Streaming SQL and continuously updated materialised views |
| Apache Airflow, Dagster | Orchestrating batch pipelines and their dependencies |
Trade-offs#
| Option | Pros | Cons | Pick when |
|---|---|---|---|
| Batch only (Spark, warehouse SQL) | Simplest to build and test; complete, exact, rerunnable results; cheap per event | Results are minutes to a day old; spikes lengthen runs | Reports, billing, training data, anything where hours of delay is fine |
| Micro-batch (Spark Structured Streaming) | Second-level latency with the batch API; one engine for both | Latency floor of about a second; less flexible event-time control than Flink | The team uses Spark and seconds of delay is fine |
| True streaming (Flink, Kafka Streams) | Millisecond to second latency; event time, large state, exactly-once state | Harder to operate, test and reason about; state and checkpoints to manage | Decisions or user-visible numbers needed within seconds |
| Lambda (stream plus batch) | Fresh numbers plus exact batch truth; batch corrects stream errors | Two codebases that must agree; more infrastructure | Money or contracts depend on the numbers, and they must also be live |
| Kappa (stream plus replay) | One codebase; reprocessing is a replay | Needs long log retention; replays can be slow and costly | Logic changes often and the log can be retained and replayed affordably |
| Exact aggregation | Correct answers | Memory and state grow with distinct keys | Billing, compliance, small key spaces |
| Approximate aggregation (sketches) | Fixed, small memory; mergeable across partitions | Bounded error, harder to explain | Trending, top-K, distinct counts for dashboards |
Common Pitfalls#
- Grouping by processing time when the question is about event time. Every restart or backlog distorts the results, and replays give different answers.
- An idle partition stalls the watermark. A topic with a quiet partition stops every window from firing. Configure idleness timeouts, and alert on watermark lag.
- Unbounded state. A join or deduplication with no time bound or TTL grows until the job runs out of disk. Every stateful operator needs a retention rule.
- Non-idempotent sinks. Appending results means every replay after a failure duplicates them. Upsert by key and window, or use a transactional sink.
- Remote calls per event. Looking up a database for every event caps throughput at what that database can serve, and makes the database part of the job's failure domain. Enrich from local state, CDC-fed tables or async I/O.
- Hot keys. One viral item sends most of the traffic to one parallel instance. Salt hot keys and aggregate in two stages.
- Choosing maximum parallelism too low. In Flink, it sets how far you can ever rescale without restarting from scratch.
- Ignoring late data silently. Dropping late events with no metric hides a growing data-quality problem. At least count them, and better, send them to a side output.
- Using streaming because it sounds modern. If nobody looks at the number more than once a day, batch is cheaper and more correct.
- Batch jobs that append instead of overwrite. Reruns double the data. Overwrite whole partitions.
Real-World Examples#
- Google published MapReduce (2004), which made large-scale batch processing a commodity, and later MillWheel (2013) and the Dataflow Model (2015), which shaped how modern engines reason about event time, watermarks and triggers. Google Cloud Dataflow and Apache Beam implement that model.
- Apache Spark came out of UC Berkeley's AMPLab, and the RDD paper (2012) explains its in-memory, lineage-based design. It is the most widely used open-source batch engine.
- Apache Flink grew out of the Stratosphere research project at TU Berlin and its partner institutions. It became the standard engine for stateful stream processing with event time.
- LinkedIn built Kafka as a durable log for activity data, and Jay Kreps, one of its creators, wrote "Questioning the Lambda Architecture" (2014), arguing for kappa. LinkedIn also built the Samza stream processor on top of Kafka.
- Twitter used Apache Storm, which Nathan Marz created at BackType before Twitter acquired the company, for real-time processing. It later replaced Storm with Heron, described in "Twitter Heron: Stream Processing at Scale" (SIGMOD 2015).
- Typical scenario: an ad platform runs Flink for per-minute click counts on dashboards and a daily Spark job over the raw click archive in S3 for billing, reconciling the two every morning.
In the Interview#
Deep Dive: Top-K and approximate aggregation in streamsShow
The problem. "Show the 100 most viewed videos in the last hour" sounds simple. At 700,000 view events per second across hundreds of millions of distinct videos, it is not. Exact per-video counts for every video are possible, but costly, and the long tail of videos with one or two views dominates the state while never appearing in the answer.
Exact top-K by partitioning. Partition the stream by video ID, so each video's count lives in exactly one instance. Each instance keeps per-minute counts for its videos, maintains a rolling one-hour total by adding the newest minute and subtracting the one that dropped out, and tracks its local top 100 in a min-heap. A final single operator merges, for example, 64 local lists of 100 into the global top 100. As shown in the windows section, merging local top-K lists is exact here, because no video's count is split across partitions. The merge step handles only 6,400 candidates, however many events arrive.
Approximate counts with a Count-Min Sketch. Graham Cormode and S. Muthukrishnan introduced the structure in "An Improved Data Stream Summary: The Count-Min Sketch and its Applications" (Journal of Algorithms, 2005). It is a grid of counters with d rows and w columns, and one independent hash function per row.
- Update: for item x, increment one counter in each row, at column hash_i(x).
- Query: return the minimum of the d counters for x.
Collisions only ever add, so the estimate never undercounts. Taking the minimum across rows picks the row with the fewest collisions. The guarantee: with width w = ceil(e / epsilon) and depth d = ceil(ln(1 / delta)), the overestimate is at most epsilon times the total count N, with probability at least 1 minus delta.
A worked size. Suppose an hour has N = 2.5 billion views and you accept an error of 0.01% of N, which is epsilon = 0.0001, or 250,000 views. That needs w = 27,183 columns. With delta = 0.001, d = 7 rows. That is about 190,000 counters, or about 760 KB at 4 bytes each, whatever the number of distinct videos. Since a top-100 video in an hour will have millions of views, an error of 250,000 does not change which videos are in the list in most cases. It may reorder close neighbours, which is why a sketch suits a "trending" widget but not billing.
Sketch plus heap. A sketch answers "how many?" for a given item, but cannot list the heavy items. So pair it with a heap: on each update, query the sketch for the item's estimate, and if it beats the heap's minimum, insert or update the item in the heap. Sketches with the same dimensions and hash functions are mergeable by adding their counters cell by cell, so per-partition sketches combine into a global one, and per-minute sketches combine into hourly ones. The Space-Saving algorithm (Ahmed Metwally, Divyakant Agrawal and Amr El Abbadi, "Efficient Computation of Frequent and Top-k Elements in Data Streams", ICDT 2005) is an alternative that directly keeps a fixed number of counters for candidate heavy hitters.
Distinct counts and percentiles. For "unique viewers per video", HyperLogLog (Philippe Flajolet and colleagues, 2007) estimates a distinct count with about 1 to 2% error in a few KB, and is also mergeable. For latency percentiles, t-digest keeps a compressed summary that is most accurate at the tails, where p99 lives. Both turn a state that would grow with the data into a fixed-size one, at a known cost in accuracy. See Probabilistic Data Structures for the internals.
Hot keys in the counting stage. When one video goes viral, its key lands on one instance. Salt it: route events for known hot keys to key plus a random suffix from 0 to 15, count per salted key, then a second stage sums the 16 partial counts. Detect hot keys dynamically by counting per-key rates in the first stage, or keep a list of known hot keys refreshed every few minutes.
Deep Dive: An ad click aggregator, end to endShow
This walk-through ties every section of the page together, with numbers.
Requirements. 10,000 clicks per second on average, 50,000 at peak during big campaigns. Advertisers want per-ad, per-minute click counts on a dashboard within about 15 seconds. Billing must be exact by the next morning. Fraudulent and duplicate clicks must not be billed.
Ingestion. A click service redirects the user to the advertiser and publishes a click event to Kafka, keyed by ad ID, with the click's event time and a unique impression ID that was signed into the ad when it was served. With 64 partitions, each partition sees about 800 events per second at peak, which is comfortable.
Deduplication by impression ID. A user double-clicks, a browser retries, or a bot replays the same link. The impression ID makes each legitimate click unique, and the signature prevents forged IDs. The click service checks a short-TTL set of recently seen impression IDs (in Redis, or in Flink keyed state with a TTL of a few hours) and drops repeats before counting. At 864 million clicks a day and 16-byte IDs, 24 hours of IDs is about 14 GB raw, so a TTL of a few hours keeps it to a few GB, sized per partition.
Aggregation. Flink reads the topic, assigns event time, drops clicks flagged by the fraud filter, keys by ad ID, and counts in one-minute tumbling windows with a 10-second watermark delay. It emits early results every 5 seconds for the open minute, and a final one when the watermark passes. Allowed lateness is 30 minutes with upserts. Later events go to a side output topic.
Hot shards. A single huge campaign can receive a large share of all clicks. If one ad exceeds a threshold, such as 2,000 clicks per second, the job salts its key into 16 sub-keys in the first stage and sums them in a second stage. The OLAP store sees one row per ad per minute either way.
Sink. Upserts into ClickHouse (or Druid or Pinot) keyed by ad ID and minute. At 1 million active ads, that is at most about 1.4 billion rows per day, and much fewer in practice, because most ads are idle in most minutes. Queries for "this campaign, last 7 days, per hour" run in milliseconds with pre-aggregated hourly rollups.
Checkpoints. Every 30 seconds, to S3, with RocksDB incremental checkpoints. State is small: one counter per active ad per open window. On a crash, the job restores and replays about 30 seconds of events, and upserts make the replay harmless.
Reconciliation. Kafka Connect's S3 sink archives every raw click as Parquet, partitioned by hour. A nightly Spark job dedupes by impression ID, applies the final fraud model, which may be stricter than the real-time one, and computes exact daily counts per ad. It compares them with the stream's sums. Differences above a small threshold page the on-call engineer, and the batch numbers are what invoices use.
What each choice buys. Event time makes counts correct across restarts and backlogs. Watermarks with early triggers give 5-second freshness with a final answer within about 70 seconds. Checkpoints plus upserts give exactly-once counts without transactions. The batch path gives billing-grade correctness and a way to fix any bug in the stream job by recomputing history. The impression ID gives dedup, and salting removes the hot shard.
Deep Dive: Testing and operating stream jobsShow
Testing time. A stream job's logic depends on event time and watermarks, so tests must control time. Flink and Kafka Streams both ship test harnesses that let a test push events with chosen timestamps, advance the watermark explicitly, and assert what the job emits. Write tests for the hard cases: an event exactly at a window boundary, an event just inside and just outside the allowed lateness, an idle partition, a duplicate ID, and a restart from a checkpoint in the middle of a window.
Comparing with batch. The strongest test of a streaming aggregate is to run the same logic as a batch job over the same archived events and compare. Unified engines make this cheap, because the same code can run in bounded mode. In production, the reconciliation job in the previous deep dive is this test running continuously.
Upgrading a running job. Take a savepoint, stop the job, deploy the new version and start it from the savepoint. Two things can break this. First, operator identity: give every stateful operator a stable ID (in Flink, uid()), or the new job cannot match the saved state to its operators. Second, state schema: changing the type of stored state needs a compatible serializer, or a migration. For a change that alters results, such as a new definition of a valid click, use the kappa approach instead: run the new version side by side into a new table and switch over.
The metrics that matter.
- Consumer lag per partition: how far behind the source the job is. Rising lag means the job cannot keep up.
- Watermark lag: wall-clock time minus the current watermark. This is the real freshness of results, and it catches stalled watermarks that consumer lag misses.
- Checkpoint duration, size and failures: checkpoints that keep getting slower usually mean back-pressure or state growth.
- Back-pressure per operator: shows which step is the bottleneck.
- Late-event rate: a jump means a source's clocks or delivery changed.
- Output freshness: the newest window in the sink, checked from outside the job.
Capacity planning. Size for peak, plus catch-up headroom. If peak is 50,000 events per second and you want to recover a 10-minute outage within 10 minutes, the job must sustain about 100,000 per second, twice the peak. Measure the throughput per core with a load test, divide, and add a margin. Keep partition counts and maximum parallelism well above today's needs, because both are hard to change later.
Key Takeaways#
- Batch processes bounded data on a schedule and gives complete, rerunnable answers. Streaming processes unbounded data continuously and gives fresh answers at the cost of complexity.
- MapReduce introduced the map, shuffle and reduce model, and Spark made it fast and high-level. The shuffle is the expensive step: use combiners, broadcast joins, pruning and salting for skew.
- Stream processors key the stream, keep per-key state, group events into tumbling, sliding or session windows, and must survive crashes and rescaling.
- Use event time for anything that must be correct or reproducible. Watermarks decide when a window is complete, trading latency against completeness, and late data is dropped, corrected with allowed lateness, or sent to a side output.
- Checkpoints, based on distributed snapshots, make state exactly-once. Exactly-once output also needs idempotent or transactional sinks.
- Lambda runs a stream for freshness and a batch for truth. Kappa keeps one stream and replays the log to reprocess. Stream plus batch reconciliation is a common, practical middle.
- Always ask whether real-time is really needed, and estimate the data size before choosing a cluster.