Stream Processing and State Management

Batch vs. Stream

How data arrivesNatural processing model
Periodic dumps (files, exports)Batch
Continuous events (clicks, DB changes)Stream

Most internet company data arrives continuously. A "daily batch job" is continuous data artificially delayed by 24 hours.

Data Flow Graphs

A data flow graph. The raw clicks log feeds processor 1, which joins with the user DB and writes the enriched clicks log. That feeds processor 2, which counts per user per hour and writes the hourly counts log. The hourly counts log is read by the fraud model and the dashboard. Logs and processors alternate: every node is either a log, which is storage, or a processor, which is a transformation. The enriched log is derived, yet looks identical to a primary log.
Logs and processors alternate — the whole graph is built from those two parts

Each arrow is a Kafka topic. Each box reads from one topic and writes to another. A derived log (output of a processor) looks identical to a primary log (direct from a database). Downstream processors don't know or care how the data was produced.

At the org level, everything is either a log (storage) or a processor (transformation). Nothing else.

What these are: stream processing frameworks, the software that runs the "processor" boxes in the diagram above. Kafka only stores and delivers events; it computes nothing. A framework reads events from a topic, does work on them (filter, join, count), writes the results to another topic, and keeps doing that across many machines, even when some of them crash.

Why not just write a plain consumer loop? For a simple filter, you can. Take a real rule instead: flag any user who spends more than ₹1 lakh within 10 minutes. Now you need to:

  • Keep state: a running total per user, which must survive a crash.
  • Handle time windows: "within 10 minutes" by when the order happened, even if events arrive late or out of order.
  • Spread the work: millions of users across many machines, with each user's events landing on the same machine.
  • Not double-count: after a restart, events already processed must not be added to the total again.

Writing that by hand is hard and easy to get wrong. A framework does it for you; you write only the rule. The three below are generations of the same idea:

  • Storm was the first popular one. Twitter used it for things like trending topics. It's fast, but it leaves state and "not double-counting" to you.
  • Samza was built at LinkedIn alongside Kafka. It uses Kafka for its input, its output and to back up its state.
  • Flink is today's default. It handles state, windows and exactly-once for you, and runs as its own cluster.

You'll also see Kafka Streams elsewhere in this guide. It's a library you add to your own app rather than a separate cluster, and it carries the same Samza-style ideas.

FrameworkOriginKey characteristic
Apache StormTwitter, 2011Low-latency, stateless-style. No native Kafka offset integration — you manage state yourself.
Apache SamzaLinkedIn, 2013Built directly on Kafka. Local state via RocksDB, changelog-backed recovery.
Apache FlinkCurrent standardStateful, exactly-once, rich windowing. Millisecond latency at high throughput; Storm can still be faster for simple stateless jobs. What most teams use today.
FeatureStormSamzaFlink
Exactly-once deliveryHard (manual)At-least-onceNative
State managementManualRocksDBRocksDB, managed
WindowingManualLimitedRich built-in support
Fault toleranceAck-basedOffset replayDistributed checkpoints

The framework matters less than the log. All three share the same pattern: [Producer] → Kafka Topic → [Processing Stage] → Kafka Topic → [Consumer]. The framework decides how to process. Kafka decides what gets processed and how recovery works.

How Flink achieves exactly-once: distributed checkpoints, based on the Chandy-Lamport algorithm. Flink periodically snapshots the state of the whole job across all machines; on failure, every machine rolls back to the last snapshot and resumes. ◆ Side read: How Exactly-Once Is Actually Achieved →

Stateful Real-Time Processing

The core question: where does state live when a processor can crash?

OptionProblem
In-memory onlyLost on crash. Replaying an hour of data to rebuild state is often infeasible.
Remote store (Redis)Every state read is a network round-trip. At 500k events/sec, this is the bottleneck.
Local co-partitioned indexState lives on the same machine as the processor. Fast local reads. Fault tolerance via a changelog. This is the right model.

How the Local Index + Changelog Works

Say the job is counting impressions per user_id. Two separate things named "state" are in play, and mixing them up is where this gets confusing:

  • RocksDB — a local key-value cache on disk, user_42 → 1042. Fast to read, but lives on one machine only. Not replicated, not backed up. Dies with the disk.
  • Changelog topic — an ordinary Kafka topic, auto-created, that Streams writes state updates to: key=user_42, value=1042. Note the value: the current total, not "user_42 clicked". This is a normal replicated Kafka topic, so it survives machine failure. It is the source of truth; RocksDB is just a fast cache of it. (Writes are buffered and batched, not one per event — see Does Every Event Write to the Changelog? below.)
The impressions topic, the input of real events, feeds the processor, which writes counts to the output topic. For its state, the processor writes to two places: RocksDB, a local cache on disk that dies with the machine, and counts-changelog, a replicated Kafka topic that is the source of truth.
One processor, two copies of its state — and only one of them is the truth

Co-partitioned means the state is split the same way as the input, so each processor instance only needs its own slice of state — never another machine's. No network calls for state reads, ever.

The Task as Unit of State

Kafka routes each event with hash(key) % num_partitions. If impressions is keyed by user_id, every event for user_42 lands on the same partition, say 7, forever. Kafka Streams then ties three things to that number:

PieceRole
impressions-7Inbox: the events for user_42 and the other keys that hash to 7
RocksDB .../0_7/Notebook: current state for exactly those keys, on local disk
counts-changelog-7Backup: a copy of that notebook, stored in Kafka

That bundle is a task (0_7: sub-topology 0, partition 7). It is the unit Kafka Streams assigns, moves and recovers. Think of a bank counter: clerk 7 serves only bucket-7 accounts and keeps their ledger in the drawer, so they never phone another counter.

The key user_42 hashes, by hash of key mod the partition count, to partition 7, every time. Task 0_7 is one bundle: the input partition impressions-7, the task itself, its RocksDB state slice under the directory dot dot dot slash 0_7 slash counts, and the changelog partition counts-changelog-7. All three share the number 7, and partition 7 is assigned to exactly one instance at a time.
Input partition, state slice and changelog partition share one number — that is the task

Three things follow:

  • No network lookups. Partition 7 has one owner at a time, so the instance that receives user_42 is guaranteed to hold its state. This is an invariant, not a lucky cache hit. A read costs ~1–10 µs from local RocksDB versus ~0.5–2 ms for a same-rack Redis round trip.
  • Failover moves the whole bundle. If that machine dies, another takes partition 7, rebuilds the notebook from counts-changelog-7, and carries on.
  • Partitions cap parallelism. 12 partitions means 12 tasks. They can spread over up to 12 instances; a 13th sits idle.

The Changelog Topic

Local RocksDB is not the durability story — the disk dies with the machine. Streams auto-creates an internal changelog topic that is:

  • Partition-matched to the input, so changelog partition 7 backs task 7 exactly.
  • cleanup.policy=compact, so its size is proportional to the number of distinct keys, not the number of events — 10M users stays ~10M entries across billions of impressions.
  • Written as key → full current value, never deltas — which is what makes replay safe to repeat (next section).

Does Every Event Write to the Changelog?

If 500k impressions/sec each bump a counter, is that 500k changelog writes/sec? Logically yes, in practice no. Three things keep it cheap and safe:

1. Updates are batched in memory. Streams keeps a write-back cache in front of RocksDB. Updates to the same key overwrite each other there, and only the final value is flushed, once per commit (every 30 s by default) or earlier when the cache fills. 50 impressions for user_1 become one changelog record, so writes track distinct keys per commit, not events.

2. Compaction cleans up behind you. cleanup.policy=compact keeps only the latest record per key, so 10M users stays ~10M records forever, no matter how many billions of impressions produced them.

3. The value is the total, never the delta. The changelog stores user_1 → 102, never user_1 → +1. This makes changelog replay idempotent: restoring the same record twice changes nothing. It does not protect against re-reading input events (see What a crash costs, below).

changelog holds:   user_1 → 101,  user_1 → 102

  replay both          → 102   ✓
  replay only the last → 102   ✓
  replay the last 2×   → 102   ✓

With deltas, every one of those lines gives a different answer, and recovery would need per-record deduplication. With full values, "read the topic top to bottom" is the entire algorithm.

What a crash costs. Each commit flushes state first and moves the input offset last, with no transaction between them. Under the default at_least_once, a crash never loses an event but can count some twice. exactly_once_v2 wraps the changelog, output and offset commit in one Kafka transaction. RocksDB stays outside it: it is a disposable copy, rebuilt from the changelog whenever in doubt.

◆ Side read: Inside the Streams Commit Cycle → the cache flush step by step, the four-step commit order, the double-count crash, and why RocksDB needs no transaction.

Fault Recovery via Changelog

What happens, step by step, when the machine holding a task's RocksDB dies:

  1. Detect. The dead instance stops sending heartbeats (session.timeout.ms). The coordinator notices and triggers a rebalance, handing its partitions to a surviving instance.
  2. Rebuild. The new instance has no local RocksDB — it died with the old machine. So it starts empty and replays the changelog partition from the beginning, reconstructing the key→value state entry by entry. This is the cold-start case. A restart that still has its state directory replays only the tail — see the checkpoint file side read.
  3. Resume. Once replay catches up, local state matches the last commit exactly. The new instance resumes consuming the input topic from the last committed offset, as if nothing happened.

Two takeaways: no separate backup mechanism is needed — Kafka itself (the changelog) is the recovery source. And because state is partitioned the same way as the input, scaling out relocates state automatically through this same replay path. The catch is that parallelism tops out at the partition count — with 12 partitions, a 13th instance just sits idle.

◆ Side read: Restore Internals — The Checkpoint File → where restore starts, why the restore position lives on local disk rather than in Kafka, when restore runs, and why exactly-once forces a full replay after a crash.

Commit-Cycle Failure Scenarios

Because state is flushed before the offset moves, only one direction of drift is possible:

DriftPossible?Consequence
Offset ahead of changelogNo — structurally prevented by the commit orderingWould be lost updates: silent under-counting, unrecoverable
Changelog ahead of offsetYes — happens continuously, by designReprocessing: over-counting, bounded by one commit interval

In practice that means three things:

  • Over-counting is silent. If the offset commit fails after the changelog is written, the new owner restores state that already includes those events and reads them again. No exception, no metric.
  • The zombie writer is worse. Instance A freezes in a long GC pause, so the group hands its task to B. B restores the count (10) from the changelog and moves it on to 15. Then A wakes up, unaware it was replaced, and finishes its old batch by writing a stale user42 → 11 to the changelog. Nothing stops that write. Under at-least-once, the group rejects only A's offset commit; the broker accepts its produce because it doesn't check group membership. Compaction keeps the last value, 11. B still holds 15 in memory and carries on, so nothing alerts. But the next restore, failover or standby rebuild reads 11. A duplicate is a one-time error; this stores the wrong value as the truth.
  • exactly_once_v2 closes both with one Kafka transaction over the changelog, output and offset. A zombie's transaction carries a stale group generation, so it is aborted, and restores read only committed records, so they never see the stale write. The cost: commits every 100 ms instead of 30 s (much less batching), and any unclean shutdown wipes RocksDB for a full restore, which makes standby replicas more important.

◆ Side read: Commit-Cycle Failure Scenarios, Traced → each failure step by step, the full table, why full values don't make reprocessing safe, and the zombie writer diagram.

Where Co-Partitioning Breaks

SituationWhat goes wrongFix
Lookup needs a field that isn't the partition keyThe key you need lives on another machine — the invariant is goneStreams inserts a repartition topic: re-key and reshuffle, then the local lookup holds again
Joining topics with different partition countshash % 10 and hash % 12 send the same key to different partitionsBoth sides must have equal partition counts — Streams fails at startup if not
Hot key (user_id=null, a celebrity account)One task saturates while the rest idle; adding instances does nothingComposite key, or a two-stage pre-aggregate
An external service wants to query the stateNo single machine holds all of itInteractive Queries — a metadata API reports which host owns a given key; proxy the request there

In one line: state isn't stored somewhere and fetched — it's partitioned by the same function as the work, so it's already wherever the work lands, and Kafka itself is the backup medium.

The Changelog Is Subscribable

The changelog isn't just a recovery tool — it's a live feed of state changes other processors can consume directly, without ever querying the original processor:

Clicks topic feeds Processor 1, which keeps its counts in a local LevelDB and also writes every state change to a changelog topic. Processor 2, which alerts when a count exceeds a threshold, and Processor 3, a dashboard aggregator, subscribe to that changelog directly and never query Processor 1.
The recovery log doubles as a public feed of state changes

CDC Joins — Enriching Streams with Database Data

CDC (Change Data Capture) extracts every row-level change from a database as a log — e.g. the users table in Postgres emits changes via Debezium into a users-changelog topic. A stream processor loads that changelog into its local index, then joins against it in real time:

Two topics feed one stream processor and are treated differently. The clicks topic delivers the event user_id=42, page="jobs", ts, and each click triggers the join. The users-changelog topic, produced by CDC from the users table, silently patches the local index entry user_id=42 → name="Alice", tier="premium" and produces no output. The join looks the user up in the local index, with no database query, and emits user_id=42, page="jobs", name="Alice", tier="premium", ts.
Two inputs, two roles — one triggers output, the other only patches the index Every click is enriched with the user’s current profile without touching the live database: the database’s changes were already streamed into the processor’s own index.

Every click is enriched with the user's current profile — without querying the live database. Two topics feed one processor, but it treats them differently: one triggers output, the other silently patches the local index.

clicks (KStream)users-changelog (KTable)
PurposeEvents to processLookup data
On startupResumes from last offsetReplayed fully to rebuild local index
On new messageTriggers join logicSilently updates local index — no output
KStream<String, Click> clicks = builder.stream("clicks");
KTable<String, User>   users  = builder.table("users-changelog"); // builds local index

clicks.join(users, (click, user) -> enrich(click, user))
      .to("enriched-clicks");

A new CDC event for user 42 produces no output — it just updates the cache so the next click for user 42 sees the latest profile. When Alice's tier changes in Postgres, that change flows through CDC into the local index within seconds.

Real-World Local Index State Examples

Each row below is expanded into a full deep dive — keying scheme, topology, and the specific gotcha — on the companion page.

Use caseWhat's in the local indexWhy local mattersDeep dive
Fraud detectionPer-card: txn count, total spend, last countryCard swiped in GB then DE 3 min later — must catch in <100ms→
Uber surge pricingPer-zone: live driver count, rider request countSupply/demand ratio recomputed on every driver location ping→
Netflix playbackPer-user: resume position, watch history"Continue watching" must reflect your last second watched→
LinkedIn feed rankingPer-user: engagement signals (likes, dwell time, skips)Feed reranks in real time as you interact — updated on every scroll→
Ad impression cappingPer-user per-ad: impression count"Show this ad max 3 times" enforced at millions/sec→
DoorDash ETAPer-order: live state machine (placed → confirmed → picked up → delivered)Every transition triggers downstream actions — order state must be local to the processor handling it→