Local State in Six Real Systems
Card Fraud Detection
The problem
A bank sees thousands of card payments every second. For each one it wants to ask questions like:
- Has this card made more than 10 payments in the last hour?
- Has it spent more than ₹50,000 in the last hour?
- Was this card used in London 3 minutes ago, and now it's being used in Berlin? No one can travel that fast, so one of the two payments is fake.
Every question is about one card's recent past. That tells us the key: card_id.
What we remember, per card
| Field | Example value | Why we need it |
|---|---|---|
recent | list of (time, amount) for the last 60 minutes | To count payments and add up spend in the last hour |
lastCity, lastLat/Lon | London, 51.5 / −0.1 | For the "impossible travel" rule |
lastTime | 10:00:00 | Same rule: how long ago was the last payment? |
This is small: a few hundred bytes per card. Even 100 million cards fit comfortably across a cluster's local disks.
The flow
A walk-through with real numbers
Card 4417. Its partition is owned by machine M2. The store already holds: 2 payments in the last hour totalling ₹1,800, last seen in London at 10:00:00.
- 10:03:00 — a ₹900 payment arrives from Berlin. Kafka sends it to M2, because that's where card
4417lives. - Read the state.
store.get("4417")returns the history. This is a local read — a few microseconds, no network. - Check the rules. Count: 3 payments (fine). Spend: ₹2,700 (fine). Travel: London → Berlin is about 930 km in 3 minutes. That's about 18,600 km/h. A plane flies at about 900 km/h. Rule fires.
- Update the state. Add (10:03, ₹900) to the list, drop anything older than 60 minutes, set last city to Berlin.
store.put("4417", newState). Kafka Streams also writes this to the changelog. - Send the alert. Write an event to the
fraud-alertstopic. A separate service reads it and blocks the card or texts the customer.
The code
This uses the Processor API, because the rules are custom logic, not a single count().
class FraudCheck implements Processor<String, Txn, String, Alert> {
private KeyValueStore<String, CardState> store;
private ProcessorContext<String, Alert> ctx;
public void init(ProcessorContext<String, Alert> ctx) {
this.ctx = ctx;
this.store = ctx.getStateStore("card-state");
// Once an hour, clean up cards that have gone quiet (see "the tricky part")
ctx.schedule(Duration.ofHours(1), PunctuationType.WALL_CLOCK_TIME, now -> sweepIdleCards(now));
}
public void process(Record<String, Txn> rec) {
String card = rec.key();
Txn txn = rec.value();
CardState s = store.get(card); // 1. local read
if (s == null) s = CardState.empty();
s.dropOlderThan(txn.time.minus(Duration.ofMinutes(60)));
List<String> hits = Rules.check(s, txn); // 2. pure logic, no I/O
s.add(txn); // 3. remember this payment
store.put(card, s); // (also goes to the changelog)
if (!hits.isEmpty()) // 4. tell someone else
ctx.forward(rec.withValue(new Alert(card, hits)));
}
}The tricky part
What happens on a crash
M2 dies. Its tasks move to M5. M5 replays the card-state changelog and rebuilds every card's history, then picks up the next unprocessed payment. With exactly-once turned on (processing.guarantee=exactly_once_v2), the store update, the alert and the "I've read up to here" marker are saved together, so no payment is counted twice and no alert is sent twice.
Takeaway: choose the key so that every question you ask is about one key. Then all the history you need is already on the machine, and each check is one local read.
Uber Surge Pricing
The problem
The city is split into small zones (Uber uses hexagons from its H3 grid, each a few hundred metres across). For each zone, we want to know two numbers right now:
- Supply: how many free drivers are in this zone?
- Demand: how many people asked for a ride here in the last 5 minutes?
If demand is much higher than supply, the price goes up (the "surge"). Every 30 seconds we publish a new price for each zone.
Why one store isn't enough
Each driver's phone sends a location ping every few seconds: {driver: D7, lat, lon}. These pings are keyed by driver_id. To count drivers per zone, we'd like to just do "+1 to the zone this ping is in". But that's wrong: driver D7 sends a ping every 4 seconds, so we'd count D7 hundreds of times.
What we really want to count is changes: when D7 moves from zone A to zone B, zone A gets −1 and zone B gets +1. To know that D7 was in zone A, we must remember each driver's last zone. That's a store keyed by driver_id. But the zone counts must be keyed by zone_id. Two different keys means two different stores, on possibly different machines.
What we remember
| Store | Key | Value | Shape |
|---|---|---|---|
driver-zone | driver_id | last zone, last ping time | Latest value |
zone-supply | zone_id | number of free drivers | Running total |
zone-demand | zone_id | ride requests per 5-minute window | Time window |
The flow
A walk-through with real numbers
Zone Z-Bandra has 4 free drivers and 0 requests. Zone Z-Khar (next door) has 6 drivers.
- Ping from driver D7, now in Khar. Step 1 reads
driver-zone["D7"]→Z-Bandra. The zone changed. - Step 1 sends two small events to the repartition topic:
(Z-Bandra, −1)and(Z-Khar, +1). These are keyed by zone now. Then it savesdriver-zone["D7"] = Z-Khar. - Step 2 receives them, on whichever machines own those zones. Bandra goes 4 → 3. Khar goes 6 → 7.
- Next ping from D7, still in Khar. Step 1 sees the same zone and sends nothing. This is what stops us counting D7 hundreds of times.
- Meanwhile, 9 ride requests come from Bandra in the next few minutes. They are re-keyed by zone too, and Step 2 counts them in the current 5-minute window: Bandra demand = 9.
- Every 30 seconds, a timer fires. For each zone: Bandra has 9 requests and 3 drivers. Ratio = 3. Price ×1.8 (say). Write
(Z-Bandra, 1.8)to thesurge-pricestopic. Khar: 2 requests, 7 drivers → ×1.0.
The code
// Step 1: driver_id-keyed. Turns "where is D7?" into "zone changes".
KStream<String, ZoneDelta> deltas = pings
.process(ZoneChangeDetector::new, "driver-zone") // emits (oldZone,-1), (newZone,+1)
.selectKey((driverId, delta) -> delta.zone); // new key = zone_id → repartition
// Step 2a: zone_id-keyed supply count.
KTable<String, Long> supply = deltas
.groupByKey()
.aggregate(() -> 0L, (zone, d, total) -> total + d.change,
Materialized.as("zone-supply"));
// Step 2b: zone_id-keyed demand, 5-minute windows.
KTable<Windowed<String>, Long> demand = requests
.selectKey((riderId, r) -> r.zone)
.groupByKey()
.windowedBy(TimeWindows.ofSizeWithNoGrace(Duration.ofMinutes(5)))
.count(Materialized.as("zone-demand"));
// A small processor with a 30-second timer reads both stores and emits prices.Notice the selectKey calls. Each one changes the key, so Kafka Streams automatically adds a repartition topic before the next groupByKey(). That's the "extra hop" from Idea 6.
The tricky parts
What happens on a crash
Each store has its own changelog. If the machine running Step 1 for some drivers dies, the new owner rebuilds driver-zone and keeps going. If the machine running Step 2 for some zones dies, the new owner rebuilds those zone counts. The repartition topic sits between them in Kafka, so no delta is lost while either side is down.
Takeaway: when the key you receive isn't the key you need to group by, split the job in two. Step 1 uses the incoming key to turn raw events into small "changes". A repartition re-keys them. Step 2 groups by the key you actually care about.
Netflix "Continue Watching"
The problem
While you watch, the app sends a heartbeat every few seconds: {profile: P42, title: "Dark S1E3", position: 31:20}. When you open the app later, the "Continue Watching" row must show every show you started, and where you stopped, in about 50 ms.
We only ever care about the newest position. If you're at 31:20 now, the heartbeat that said 31:10 is useless.
Choosing the key — this matters more than it looks
The obvious key is profile + title, because "position" belongs to one profile watching one title. But think about the read: the home screen asks "all titles for profile P42". With key P42|Dark, P42|Narcos, P42|Ozark, Kafka hashes each one separately, so P42's titles end up spread across many partitions and many machines. One screen load would need to ask every machine.
Better: key by profile_id, and store a small map of title → position as the value. Now all of P42's titles live together on one machine, and the home screen needs one lookup.
What we remember
| Key | Value |
|---|---|
P42 | { "Dark S1E3": 31:20 @ 21:14:05, "Narcos S2E1": 12:02 @ yesterday, ... } — keep the latest 50 titles |
The flow
A walk-through
- Write path. A heartbeat
(P42, Dark S1E3, 31:20)arrives. The processor reads P42's map, setsDark S1E3 = 31:20, writes it back. Nothing is sent to any output topic. The only job is to keep the store up to date. - Read path, next evening. P42 opens the app. The home-screen API asks Kafka Streams: "which machine owns key P42 in store
resume-positions?" The answer comes from local metadata — no network call. - The API calls that machine over HTTP (you build this small endpoint yourself; Kafka Streams doesn't include one). That machine does
store.get("P42")and returns the map. - The row is drawn. "Dark S1E3 — resume at 31:20". The data is at most a few seconds old.
The code
// Write side: the DSL is enough here.
KTable<String, ResumeMap> positions = heartbeats // already keyed by profile_id
.groupByKey()
.aggregate(ResumeMap::new,
(profile, hb, map) -> map.updateIfNewer(hb.title, hb.position, hb.time),
Materialized.as("resume-positions"));
// Read side: inside the API service.
KeyQueryMetadata meta = streams.queryMetadataForKey(
"resume-positions", "P42", Serdes.String().serializer());
HostInfo owner = meta.activeHost();
if (owner.equals(thisHost)) {
ReadOnlyKeyValueStore<String, ResumeMap> store = streams.store(
StoreQueryParameters.fromNameAndType("resume-positions",
QueryableStoreTypes.keyValueStore()));
return store.get("P42");
} else {
return http.get(owner, "/resume/P42"); // your own small endpoint
}The tricky parts
What happens on a crash
Same as always: a new owner replays the changelog. The difference here is that users are waiting on reads, so the rebuild time is visible to them. That's why standby replicas matter more for this example than for the others.
Takeaway: pick the key for the way the data will be read, not just the way it is written. And when people query the store directly, recovery time becomes user-facing downtime, so keep a warm standby.
LinkedIn Feed Ranking
The problem
You've just liked three posts about Kafka and scrolled past two about cricket. Your feed should notice now, not tomorrow. The main ranking model is trained offline, but it needs fresh inputs ("features") like "this user's interest in Kafka in the last hour". Our stream job keeps those fresh inputs up to date and uses them to re-score posts.
Recent actions should count more than old ones. A like from six months ago should matter far less than a skip from ten seconds ago.
What we remember, per user
| Key | Value |
|---|---|
user_id | A score per topic, plus when it was last updated: { kafka: 2.9, cricket: −1.0, hiring: 0.4, updated: 10:12 } |
How "recent counts more" works — decay
Instead of keeping every event, we keep one number per topic and let it fade over time. Rule: every hour that passes, a score is cut in half (a "half-life" of 1 hour). Then we add the new event's weight.
- Like = +1. Click = +0.5. Skip (scrolled past fast) = −0.5. Hide = −2.
- New score = old score × ½(hours since last update) + weight of this event.
Example: your Kafka score is 2.0 at 10:00. At 11:00 you like another Kafka post. 2.0 × ½ = 1.0, plus 1 = 2.0. If instead you'd liked it at 10:01, the old score barely fades: 2.0 × 0.99 + 1 ≈ 3.0. Fresh activity piles up; old activity fades away by itself. And the state stays tiny: one number per topic, no matter how many events.
The flow
A walk-through
- 10:10–10:12: user U9 likes 3 Kafka posts and skips 2 cricket posts. Each event updates U9's score sheet in the local store. Kafka ≈ 2.9, cricket ≈ −1.0.
- 10:12: the candidate service finds 200 new posts for U9 and sends them as events keyed by
U9. - The join. For each candidate, the processor reads U9's score sheet from the local store (same machine, because both topics are keyed by
user_id) and computesbaseScore + interest[post.topic]. - Output. A Kafka post that scored 0.6 now scores 3.5 and moves up. A cricket post drops. The re-scored list goes to
ranked-feed-updates, which the feed service reads the next time U9 scrolls.
The code
// 1. Build the per-user score sheet. Keyed by user_id.
KTable<String, Interests> interests = engagement // keyed by user_id
.groupByKey()
.aggregate(Interests::new,
(user, ev, sheet) -> sheet.decayTo(ev.time).add(ev.topic, ev.weight()),
Materialized.as("user-interests"));
// 2. Join each candidate post with the user's sheet. Also keyed by user_id.
candidates // keyed by user_id (the viewer)
.join(interests, (post, sheet) -> post.rescore(sheet.decayTo(post.time)))
.to("ranked-feed-updates");The tricky parts
What happens on a crash
The user-interests changelog holds one small record per active user. A new owner rebuilds it, and the join continues. Because scores decay, even slightly stale state is mostly harmless — it gets corrected by the next few events.
Takeaway: a stream–table join is "look up this key in a local table". It only works when both sides are keyed and partitioned the same way. And decaying scores let you keep "recent behaviour" in a few numbers instead of a growing list.
Ad Impression Capping
The problem
Advertisers pay per view, but they don't want one person to see the same ad 40 times. So each campaign has a frequency cap: "max 3 views per user per day". Every time we're about to show ad A to user U, we must ask: has U already seen A 3 times today? If not, show it and add 1. If yes, pick another ad.
Why the obvious design breaks
The obvious design: many ad servers, one shared Redis holding the counts. Each server does: read count → if under 3, show the ad → write count + 1. Now look at what happens when the user has two tabs open:
Both servers read "2" before either writes. Both think it's fine. The user sees the ad 4 times. This is a classic race condition: "read, check, write" is three steps, and someone else ran in between. Fixing it in Redis needs a Lua script or a lock, plus retries, and the Redis node becomes a hot spot for popular users.
The stream design
Send ad decisions through a stream keyed by user_id. All of U's requests go to one partition, which is handled by one thread, one event at a time. When that thread reads the count, nobody else can change it before the thread writes it back. The race is simply impossible.
Why key by user_id and not user_id + ad_id? Because many campaigns also have a cap across ads ("max 10 ads per user per hour"). Keying by user puts all of U's counts on one machine, so both kinds of cap can be checked in one place. Inside the store, the key can still be U|A|date.
What we remember
| Store key | Value | Kept for |
|---|---|---|
U77|ad-shoes|2026-10-03 | 2 | 1 day, then deleted |
U77|all-ads|2026-10-03T10 | 6 | 1 hour, then deleted |
A walk-through
- Request 1 (tab 1): "show ad-shoes to U77?" The thread reads the count: 2. Under 3, so: write 3, send
SHOW. - Request 2 (tab 2), a millisecond later: it is in the same partition, so it waits for request 1 to finish. Then it reads: 3. At the cap, so send
SKIP. The ad server picks a different ad. - Tomorrow: a new date in the key means a fresh count of 0. Yesterday's entries are deleted when their window's retention runs out. No cron job resets anything.
The code
public void process(Record<String, AdRequest> rec) {
AdRequest r = rec.value();
String k = r.userId + "|" + r.adId + "|" + r.localDate(); // the user's own date
Long seen = store.get(k); // read
if (seen == null) seen = 0L;
if (seen < r.capPerDay) { // check
store.put(k, seen + 1); // write — no one can run in between
ctx.forward(rec.withValue(Decision.show(r)));
} else {
ctx.forward(rec.withValue(Decision.skip(r)));
}
}The tricky parts
What happens on a crash
A new owner rebuilds today's counts from the changelog. Because old windows have already been deleted, the changelog only holds recent data, so the rebuild is quick.
Takeaway: "one key → one thread" is a lock you get for free. Any "read, check, then write" rule that needs to be exactly right can live inside one keyed task instead of behind a distributed lock.
DoorDash Order Tracking
The problem
An order moves through steps. Different systems report each step: the restaurant tablet, the driver's app, the payment system.
Events from these systems are messy:
- Duplicates: the driver app retries, so
picked_uparrives twice. - Out of order:
deliveredarrives beforepicked_up, because the driver app was offline and sent both at once. - Late: an old
preparingarrives after the order is alreadypicked_up.
Every time the order really changes step, we want to: update the ETA, and send the customer a push notification. Exactly once each.
What we remember, per order
| Key | Value |
|---|---|
order_id | current step, and the time each step happened: { step: PICKED_UP, placed: 19:02, confirmed: 19:03, ..., picked_up: 19:31 } |
The one rule: only move forward
Give each step a number: placed = 1, confirmed = 2, preparing = 3, ready = 4, picked up = 5, delivered = 6. Cancelled is special: it's allowed from steps 1–4 and ends the order.
- New step number bigger than the stored one → accept it, save it, announce it.
- New step number equal or smaller → it's a duplicate or a late event. Ignore it.
Look at what this one rule does to each messy case:
| Stored step | Event arrives | Result | Why |
|---|---|---|---|
| picked up (5) | picked up (5) again | Ignored | Duplicate — no second push notification |
| picked up (5) | preparing (3) | Ignored | Late event — the order can't go backwards |
| ready (4) | delivered (6) | Accepted | It skipped "picked up", but it's forward. The customer has the food; don't throw that away. |
| delivered (6) | picked up (5) | Ignored | The early "delivered" already moved us past this |
| delivered (6) | cancelled | Ignored, and flagged | Can't cancel a delivered order — send to a "needs a human" topic |
The flow
The code
public void process(Record<String, OrderEvent> rec) {
String orderId = rec.key();
OrderEvent ev = rec.value();
OrderState s = store.get(orderId);
if (s == null) s = OrderState.newOrder();
if (!s.canMoveTo(ev.step)) return; // duplicate, late, or impossible: ignore
s.moveTo(ev.step, ev.time);
store.put(orderId, s); // → changelog
ctx.forward(rec.withValue(new StepChanged(orderId, ev.step, ev.time)));
// No HTTP calls, no push notifications here. Just a fact, written to a topic.
}Why the side effects live outside
It's tempting to call the push-notification service right inside process(). Don't. With exactly-once, the store update and the output event are part of a Kafka transaction. If the transaction fails and is retried, Kafka can undo its own writes — but it cannot undo an HTTP call. The customer would get "Your order was picked up!" twice.
So the job only writes a fact: StepChanged(order 881, PICKED_UP). Separate services read that topic and do the real-world actions. Those services must protect themselves against repeats too. The simple way: use order_id + step as an idempotency key, and skip any key they've already handled.
A bonus: noticing when nothing happens
Because the job remembers each order's step and its time, it can also spot orders that are stuck. A timer runs every minute and looks for orders sitting in "preparing" for more than 30 minutes, and sends them to an orders-at-risk topic so support can step in. Detecting "something didn't happen" is impossible without state.
What happens on a crash
A new owner rebuilds each open order's state from the changelog. Delivered and cancelled orders can be deleted from the store a day after they finish (write a null value, called a tombstone), so compaction removes them from the changelog too and the store only holds orders that are still live.
Takeaway: a stored "current step" plus "only move forward" turns a messy event stream into clean, one-time changes. Keep the processor pure — decide and record — and let other services act on the outside world.
All Six, Side by Side
| Example | Key | Shape of state | The trick that makes it work | The trap |
|---|---|---|---|---|
| Fraud | card_id | Recent list + last location | All questions are about one card → one local read | Idle cards never get cleaned up |
| Surge | driver_id, then zone_id | Latest value → running total + window | Turn pings into ±1 changes, then repartition by zone | Drivers who vanish are never subtracted |
| Continue Watching | profile_id | Latest value (a small map) | Interactive query reads the store directly | Old heartbeats rewinding the position; rebuild = user-facing downtime |
| Feed ranking | user_id | Running totals that fade | Stream–table join, done locally | Topics not co-partitioned → join silently finds nothing |
| Ad capping | user_id | Time window counts | One thread per key = no race, no lock | Double counts after a crash without exactly-once |
| Order tracking | order_id | State machine | "Only move forward" removes duplicates and late events | Side effects inside the processor fire twice |
Three questions to ask when you design your own:
- What is the one key every decision is about? If there are two (driver and zone), you need two steps and a repartition.
- How does the state stop growing? Windows that expire, scores that fade, a timer that sweeps, or tombstones for finished items. If you can't answer this, the store will fill your disk.
- What touches the outside world? Keep it out of the processor. Write a fact to a topic and let another service act on it, safely, once.
Test Yourself
Question 1
Why doesn't the ad-capping processor need a lock, when the Redis design does?
Show answer
Because every request for one user has the same key, so it goes to the same partition, which is handled by one thread, one event at a time. The "read, check, write" for a user can't be interrupted by another request for that user. In the Redis design, many servers run the three steps at once against shared data, so two can read the same old value.
Question 2
In the surge example, why not just add +1 to a zone for every driver ping?
Show answer
A driver pings every few seconds, so they'd be counted hundreds of times. We need to count changes of zone, which means remembering each driver's last zone — a store keyed by driver_id. Only when the zone changes do we send −1 to the old zone and +1 to the new one.
Question 3
The "Continue Watching" store is keyed by profile + title. What goes wrong, and how do you fix it?
Show answer
Each profile+title key hashes to a different partition, so one profile's titles are spread across many machines. Loading the home screen would need to ask all of them. Key by profile_id and keep a small map of title → position as the value, so one lookup on one machine returns the whole row.
Question 4
A machine running the fraud job dies. Walk through how the new machine knows card 4417's history.
Show answer
Every store.put was also written to the card-state changelog topic in Kafka. The new owner of the partition reads that changelog from the start and writes each key into its own fresh RocksDB. Because the changelog is compacted, it holds about one record per card, so this is a bounded amount of work. When it reaches the end, it resumes processing payments from the last committed position. A standby replica can skip most of this wait.
Question 5
Why is "only move forward" better than "only allow the exact next step" for order tracking?
Show answer
"Exact next step" would reject a real delivered that arrived before picked_up, and the order would be stuck. "Only move forward" accepts any later step, and still rejects duplicates (same step) and late events (earlier step), which are the two things we actually want to filter out.
Question 6
The feed job's candidates topic has 12 partitions; the engagement topic has 24. What happens?
Show answer
The same user_id hashes to a different partition number on each side, so a user's candidates land on a task that doesn't hold their score sheet. The join would find nothing. Kafka Streams catches this at startup for topics in the topology and refuses to start. The fix is to give both topics the same partition count (or repartition one side).
Question 7
Name one way each example stops its state from growing forever.
Show answer
Fraud: drop entries older than an hour, plus a timer that deletes idle cards. Surge: a timer removes drivers silent for 60 s; demand windows expire. Continue Watching: keep only the latest 50 titles per profile. Feed: decaying scores stay a fixed size (and topics with tiny scores can be dropped). Ads: daily windows expire. Orders: tombstone finished orders after a day.
Related pages
- ← Back to the full theory guide — The log as the unifying abstraction, data integration, stream processing, the partition/replication/acks design problem, commit semantics, rebalancing, and exactly-once — the model these six examples all build on.
- Hands-on lab: count-per-user-per-hour — A real Kafka Streams topology built by hand, with the changelog, RocksDB, and recovery inspected on disk as it happens — the mechanics behind every example on this page.