<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Karan Patel on Medium]]></title>
        <description><![CDATA[Stories by Karan Patel on Medium]]></description>
        <link>https://medium.com/@karanpatel2193?source=rss-c591fa7fe717------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*H0eEeSFpje-ANtUW.jpg</url>
            <title>Stories by Karan Patel on Medium</title>
            <link>https://medium.com/@karanpatel2193?source=rss-c591fa7fe717------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 04 Dec 2026 16:52:36 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@karanpatel2193/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Kafka Layer 5: The Join That Silently Failed]]></title>
            <link>https://medium.com/@karanpatel2193/kafka-layer-5-the-join-that-silently-failed-ee3e4739a708?source=rss-c591fa7fe717------2</link>
            <guid isPermaLink="false">https://medium.com/p/ee3e4739a708</guid>
            <category><![CDATA[partitioned-joins]]></category>
            <category><![CDATA[kafka-topic]]></category>
            <category><![CDATA[kafka-partition]]></category>
            <category><![CDATA[kafka-streams]]></category>
            <dc:creator><![CDATA[Karan Patel]]></dc:creator>
            <pubDate>Thu, 24 Sep 2026 01:18:06 GMT</pubDate>
            <atom:updated>2026-09-24T01:18:06.506Z</atom:updated>
            <content:encoded><![CDATA[<p><em>Layer 5 of </em><a href="https://medium.com/@karanpatel2193/down-the-stack-kafka-in-nine-layers-65541826dd65"><em>Down the Stack: Kafka in Nine Layers</em></a><em>. An ordinary enrichment join that leads to a production mystery.</em></p><p>The growth team wants session summaries enriched with user profiles: plan tier, signup date, region. Profiles live in the accounts team’s service. This layer is all about joins.</p><h3>Getting the profiles</h3><p>The accounts team agrees to publish profile changes to a user-profiles topic, keyed by user_id, one record per update. Their service is Python, so their producer is confluent-kafka (librdkafka under the hood)</p><p>Their producer, roughly:</p><pre>from confluent_kafka import Producer<br>from confluent_kafka.schema_registry.avro import AvroSerializer<br>producer = Producer({<br>    &#39;bootstrap.servers&#39;: &#39;localhost:9092&#39;,<br>    &#39;schema.registry.url&#39;: &#39;http://localhost:8081&#39;,<br>})<br>def publish_profile_change(user_id: str, profile: dict):<br>    producer.produce(<br>        topic=&#39;user-profiles&#39;,<br>        key=user_id,          # string key, keyed by user_id<br>        value=avro_serialize(profile),<br>    )<br>    producer.flush()</pre><p>The key point: Python’s confluent-kafka uses librdkafka&#39;s default partitioner. Java&#39;s kafka-clients uses its own. Both are &quot;hash the key and mod by partition count,&quot; but the hash functions differ. This difference will not show up in any error log. Hold that thought.</p><p>On our side, the profiles become a KTable, materialized into a state store, current value per user:</p><pre>KTable&lt;String, UserProfile&gt; profiles = builder.table(&quot;user-profiles&quot;);</pre><h3>The join, and the requirement underneath it</h3><p>Now enrich. Our enriched-events stream needs each event paired with its user’s profile. Here is what the join topology looks like end to end:</p><p><strong>Producer side (our ingest service):</strong></p><pre>// Events are keyed by session_id (Layer 2 decision)<br>kafka.send(&quot;events&quot;, event.getSessionId(), avroSerialize(event));</pre><p><strong>Consumer/Streams side (enrichment processor):</strong></p><pre>KStream&lt;String, EnrichedEvent&gt; enriched = events<br>    .filter((sessionId, ev) -&gt; ev.getUserId() != null)   // logged-in traffic only<br>    .selectKey((sessionId, ev) -&gt; ev.getUserId())        // rekey to user_id for the join<br>    .join(profiles, (event, profile) -&gt; EnrichedEvent.of(event, profile));<br>enriched.to(&quot;sessions.enriched&quot;);</pre><p><strong>Consumer side (downstream team reading enriched sessions):</strong></p><pre>@KafkaListener(topics = &quot;sessions.enriched&quot;, groupId = &quot;growth-analytics&quot;)<br>public void onEnrichedSession(EnrichedEvent event) {<br>    growthDashboard.record(event.getUserId(), event.getPlan(), event.getRegion());<br>}</pre><p>The selectKey matters. Events are keyed by session_id while profiles are keyed by user_id. A stream-table join in Kafka Streams is a <em>local</em> operation: when an event arrives at an instance, Streams looks up the event&#39;s key in that application instance&#39;s shard of the profile store. For that lookup to ever succeed, the event and the profile must agree on what the key is, and they must be on the same partition number of their respective topics, so that the same application instance owns both. Same key, same partition: that pairing is called <strong>co-partitioning</strong>, and every stream-table join in a partitioned system rests on it.</p><p>It’s worth being precise about why. The profile store is not a database the join queries; it’s twelve local shards, each holding only the profiles whose user_id hashes to that partition. The app instance processing event partitions 0 through 2 holds profile partitions 0 through 2 and nothing else. If user u-1842&#39;s events arrive at one instance and u-1842&#39;s profile row lives in another instance&#39;s shard, the join doesn&#39;t fail. It just finds nothing.</p><p>So what does selectKey actually do? Changing the key changes the partition, and records can&#39;t teleport between partitions inside a running application. Kafka Streams solves this the only way Kafka solves anything: with another topic. It writes the re-keyed events to an internal <strong>repartition topic</strong>, partitioned by the new key, and consumes them back on the other side. Cross-instance routing, implemented as publish and subscribe; no instance ever talks to another instance.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*oR5Pi-i0dLEDUAv15QQ5DQ.png" /></figure><p>It works, and it isn’t free: every filtered event is now written to Kafka twice and read twice, with the extra broker round-trip as latency. That’s the toll the Layer 2 key choice quietly signed us up for: sessions were the right unit for funnels, but every <em>user</em>-oriented use of this data will pay the repartition tax. Keep a running total in your head; we’ll come back to it.</p><h3>The mystery</h3><p>Two weeks later, growth files a bug: “most sessions never get enrichment.” Not all, not none. Roughly nine users in ten, the same users every time, consistently unenriched. No errors in any log, no DLQ traffic, no lag.</p><p>Lets go through the checklist:</p><ul><li>Profile missing? No: pull the missing users from user-profiles with a console consumer, the records are right there.</li><li>Deserialization? No: those same records read fine elsewhere.</li><li>Timing (event before profile)? No: profiles are weeks old, events fresh.</li></ul><p>The breakthrough is asking “<em>which partition</em> is the profile in versus which partition the join expects it in”. For user u-1842: the join’s repartition topic puts their events on partition 7. Their profile sits on partition 4. The instance owning partition 7 dutifully looks up u-1842 in its shard, which has never seen them. Same key. Same partition count. Different partition.</p><p>How? Because “partition = hash(key) mod N” hides an assumption: <em>whose</em> hash. The Java client partitions with murmur2, while librdkafka, which the accounts team’s Python producer uses, defaults to a different function (crc32-based). Same key, two hashes, two partitions. Co-partitioning requires same key, same partition count, <strong>and the same partitioner</strong>, and the third clause appears in approximately none of the introductory material. For a third of our users, the two hash functions happened to disagree; for the rest they happened to agree, which is what made the failure partial, stable, and maximally confusing.</p><p>The fix is one line in the Python producer’s config (partitioner: murmur2_random, matching Java), plus re-producing the profiles topic so existing rows land where they belong. The repo&#39;s reproduction script includes the mismatched producer.</p><p>The durable lesson: <strong>a silent join miss is not an error state in Kafka Streams.</strong> It’s indistinguishable from “no matching row exists.” Whatever observability you have, a join hit-rate metric belongs in it.</p><h3>Could we have dodged this? The GlobalKTable question</h3><p>There is a join that doesn’t require co-partitioning. A <strong>GlobalKTable</strong> replicates the <em>entire</em> table to every instance: each instance consumes all partitions of the topic and holds a full local copy. Any event can join against any row locally, any partitioner, any key. Why not always use it?</p><p>Simple, because it comes with its own storage tradeoffs. A regular KTable shards storage across instances (twelve partitions, each instance stores its slice); a GlobalKTable multiplies it (every instance stores everything). A regular KTable’s failure mode is local: one instance restoring its shard affects its partitions. A GlobalKTable’s is systemic: every instance depends on every partition, so one slow partition staleness-es the table on the whole fleet. The rule of thumb that has served me well: GlobalKTable for small, slow-moving reference data (country codes, plan catalogs, feature flags); regular KTable for anything large or hot (user profiles, account state). Our profiles are both large and hot. The KTable stands, and the co-partitioning discipline stays.</p><h3>The real fix is upstream</h3><p>Step back from the incident and look at the shape of things. The events topic is keyed by session_id. Every user-centric consumer (enrichment now, billing and usage later, most of the roadmap eventually) starts by re-keying to user_id and paying the repartition toll. The is a recurring fee for a key that matches fewer and fewer of the topic&#39;s actual uses.</p><p>Fixing <em>that</em> means changing the topic’s key, and you can’t change a key in place: the key determines placement, so a key change is a data migration :</p><ol><li>Create events.v2, keyed by user_id (sessions of anonymous users key by session_id still; the partitioner doesn&#39;t care that the keyspace is mixed, only that it&#39;s consistent).</li><li>Run a small Streams job mirroring events into events.v2, re-keyed. History replays through it; live traffic follows.</li><li>Move consumers one group at a time. Each consumer cuts over at a chosen offset boundary, <em>not</em> mid-stream: the two topics order events differently (session-order versus user-order), and a consumer straddling both during the overlap can observe a user’s events twice, or in an order neither topic actually contains. Cut clean, per group.</li><li>Producers switch last (write directly to v2), the mirror retires, v1 ages out with its retention.</li></ol><p>Notice what the registry from Layer 3 can’t do for us here. It guards the <em>value’s</em> schema with versioning and compatibility checks. The key has no such machinery: no compatibility mode, no migration tool, no versioned evolution. The key is the contract Schema Registry can’t see, which is precisely why it’s the part you want to get right early, and the part this pipeline now gets to fix at production scale instead of in a design review.</p><h3>Where this leaves us</h3><p>Enrichment works, the partitioner mismatch has a regression test, and events.v2 is migrating. The pipeline survived its first <em>silent</em> failure, the kind with no stack trace to start from, and it taught us the discipline this whole layer boils down to: in a partitioned system, <em>where data lives</em> is part of every operation&#39;s correctness.</p><p>The next incident does come with stack traces. Plenty of them.</p><p>Marketing wants to track checkouts. A new event type, a one-line addition to the EventType enum, reviewed and approved in minutes. The kind of change that doesn&#39;t even get its own deploy, just rides along with Friday&#39;s release. The registry checks the new schema against the compatibility rules we accepted, unread, back in Layer 3, and finds it acceptable. Monday morning, three consumer teams are in the incident channel. Layer 6 is the schema reckoning.</p><p>The full code for this layer with reproducible bug is available here : <a href="https://github.com/Panda0Monium/kafka-layer-by-layer/tree/master/layer5">https://github.com/Panda0Monium/kafka-layer-by-layer/tree/master/layer5</a></p><p><a href="https://medium.com/@karanpatel2193/down-the-stack-kafka-in-nine-layers-65541826dd65"><em>Down the Stack: Kafka in Nine Layers </em></a><em>· Prev: </em><a href="https://medium.com/@karanpatel2193/kafka-layer-4-sessions-and-state-191ea944e350"><em>Layer 4</em></a><em> · Next: Layer 6, The Enum You Can’t Remove</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ee3e4739a708" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Kafka layer 4: Sessions and State]]></title>
            <link>https://medium.com/@karanpatel2193/kafka-layer-4-sessions-and-state-191ea944e350?source=rss-c591fa7fe717------2</link>
            <guid isPermaLink="false">https://medium.com/p/191ea944e350</guid>
            <category><![CDATA[kafka-streams]]></category>
            <category><![CDATA[ktable]]></category>
            <category><![CDATA[kstream]]></category>
            <category><![CDATA[transformation]]></category>
            <dc:creator><![CDATA[Karan Patel]]></dc:creator>
            <pubDate>Sun, 26 Jul 2026 21:12:19 GMT</pubDate>
            <atom:updated>2026-07-28T19:10:23.185Z</atom:updated>
            <content:encoded><![CDATA[<p><em>Layer 4 of </em><a href="https://medium.com/@karanpatel2193/down-the-stack-kafka-in-nine-layers-65541826dd65"><em>Down the Stack: Kafka in Nine Layers</em></a><em>. Product team wants session duration. The pipeline will now require memory.</em></p><p>Every operation so far has looked at one event and forgotten it. “Average session duration” breaks that model: a session’s end arrives minutes or hours after its start, and connecting the two means holding the start somewhere until the end shows up. Multiply by every active session across twelve partitions and a handful of consumer instances, and “somewhere” becomes the real design question of this layer.</p><h3>Two shapes of data: KStream and KTable</h3><p>Kafka Streams gives you two views of a topic, and the distinction does a lot of work in everything that follows.</p><p>A <strong>KStream</strong> is the topic as a sequence of independent facts. Every record matters, every record is processed. “User u-1842 viewed /pricing at 14:02:11” is a fact; a later event doesn’t make it less true. Clicks, page views, transactions: streams.</p><p>A <strong>KTable</strong> is the topic as an evolving snapshot. Each record is an <em>update</em>: the new value for its key replaces the old one, and only the latest version per key matters. A user’s current plan, a product’s current price: tables. A record in a KTable isn’t a fact about what happened; it’s the current answer to “what is the value for this key?”</p><p>The same bytes can be read either way, this is the duality of KStream-KTable.</p><h3>Where state actually lives</h3><p>When a Streams application needs memory (a running aggregate, an open session, a table’s current contents), it keeps it in a <strong>state store</strong>: a RocksDB instance embedded in your application process, one shard per partition of the input.</p><p>That sharding is the part to internalize. If the events topic has twelve partitions, the state behind any aggregation of it is split into twelve shards, and each shard lives inside whichever instance currently owns that partition. An instance holds state <em>only</em> for its partitions. There is no shared database; there is no instance with the full picture. The data was partitioned by key, so the state is partitioned by key, and the processing happens where the state is. (File this sentence away. Layer 5 is entirely about what happens when it&#39;s violated.)</p><p>Local state in a process raises the obvious question: what happens when the process dies? Kafka Streams’ answer is characteristically Kafka-shaped: every write to a state store is also appended to a <strong>changelog topic</strong>, a compacted Kafka topic mirroring the store’s contents. The store is just a materialized view of its changelog. Lose the instance, and the replacement replays the changelog and rebuilds the store. The log is the durability story, again.</p><p>(How long that replay takes when the store is large, and what “the replacement” means on Kubernetes, is a question this series answers the hard way, several layers down.)</p><h3>Sessionizing</h3><p>Sessions in analytics are defined by silence: a session is a burst of activity from one session_id, closed by 30 minutes of inactivity. Kafka Streams has a window type for exactly this shape, the <strong>session window</strong>, notable for having no fixed size: each key&#39;s window grows as long as its events keep coming.</p><pre>KStream&lt;String, TrackingEvent&gt; events = builder.stream(&quot;events&quot;);<br>KTable&lt;Windowed&lt;String&gt;, SessionSummary&gt; sessions = events<br>    .groupByKey()<br>    .windowedBy(SessionWindows.ofInactivityGapAndGrace(<br>        Duration.ofMinutes(30), Duration.ofMinutes(5)))<br>    .aggregate(<br>        SessionSummary::empty,<br>        (sessionId, event, summary) -&gt; summary.add(event),<br>        (sessionId, left, right) -&gt; left.merge(right),<br>        Materialized.with(Serdes.String(), sessionSummarySerde));<br>sessions.toStream((windowedKey, summary) -&gt; windowedKey.key()).to(&quot;sessions&quot;);</pre><p>Each incoming event either extends an open session window or starts a new one; the aggregate accumulates whatever the summary needs (start, end, event count, pages visited, first-five-minutes pages). When a window closes, the summary is the answer to product’s question, and it flows out to a sessions topic for anyone downstream.</p><p>One mechanical detail in that last line: a windowed aggregation’s key isn’t a plain String anymore, it&#39;s Windowed&lt;String&gt; the session ID plus the window&#39;s time bounds. The mapper in toStream unwraps it back to the bare session ID before writing, so downstream consumers get a topic keyed the way they&#39;d expect rather than a serialization surprise.</p><p>The state store underneath holds every open session for the instance’s partitions. Note that this works <em>because</em> of Layer 2’s keying: all of a session’s events are on one partition, so the whole session lives in one shard of state, and no cross-instance coordination is ever needed.</p><h3>Two kinds of time</h3><p>Now the subtle part, and the part of this layer that costs real money when misunderstood.</p><p>The session gap is 30 minutes of inactivity. Inactivity <em>when</em>? A phone rides the subway for 25 minutes, offline, queueing events. When it resurfaces, those events arrive in a burst. If the pipeline measures time by when events <em>arrive</em> (processing time), the subway rider’s single session shatters into two, and every duration metric lies.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xfbIZyez1hSShZDd4n7MIQ.png" /></figure><p>So Kafka Streams windows run on <strong>event time</strong>: the timestamp inside the record, stamped by the phone when the tap actually happened. Our ts field has been carrying this since Layer 1, and a timestamp extractor tells Streams to trust it. The subway rider&#39;s events arrive late but carry their true times, the window math places them where they belong, and the session stays whole.</p><p>Event time creates its own boundary problem: how long do you wait for stragglers? It helps to separate two knobs here that look alike and do different jobs.</p><p>The <strong>inactivity gap : </strong>30 minutes. This is a statement about the data: two events belong to the same session when less than that much silence sits between them. It defines what a session <em>is</em>. Widen it and you change that meaning a user who left and came back 32 minutes later stops being two visits and becomes one.</p><p>The <strong>grace period</strong> : 5 minutes. This answers a delivery question. The subway rider’s straggler carries a ts that already falls <em>inside</em> its session but it arrives after the window has closed. This it&#39;s an in-bounds event that physically <em>arrived</em> late, after the window looked done. Grace is how far behind the newest event time Streams will still accept such a record: while the latest data is under 5 minutes ahead of the straggler&#39;s timestamp, the record is folded into its rightful window, updating the aggregate, even re-merging two windows the gap had briefly split. Once the clock runs further ahead than grace allows, the window is sealed, its result is final, and anything later is dropped, silently, by default.</p><p>So the two aren’t interchangeable, and grace is not just “a bigger window.” Widening the gap to <em>catch</em> late data would glue genuinely separate sessions together; grace catches late data without touching what a session means, at the cost of finalizing each window a little later and holding it in state a little longer. The repo adds the one config everyone should have (a metric on dropped records), because “silently” and “production” are words that should never share a sentence.</p><p>That metric already exists, Kafka Streams counts every dropped record in the built-in dropped-records-total. The only thing to add is a consumer to process this metric:</p><pre>// A past-grace event is dropped silently by default. Streams still counts it<br>// in dropped-records-total; this makes the count loud. A real deployment<br>// scrapes the same metric off JMX into Prometheus/Grafana.<br>@Scheduled(fixedRate = 60_000)<br>public void reportDropped() {<br>    long dropped = (long) streams.metrics().values().stream()<br>        .filter(m -&gt; m.metricName().name().equals(&quot;dropped-records-total&quot;))<br>        .mapToDouble(m -&gt; ((Number) m.metricValue()).doubleValue())<br>        .sum();<br>    if (dropped &gt; lastSeen) {<br>        log.warn(&quot;{} events arrived past grace and were dropped&quot;, dropped);<br>        lastSeen = dropped;<br>    }<br>}</pre><p>Where do the numbers come from? Pick the inactivity gap from your data (ours: histogram the inter-event gaps, 30 minutes covers the valley between “same visit” and “came back later”). Pick grace from your clients’ delivery tail (ours: 5 minutes catches 99.9% of mobile stragglers). Both are product decisions wearing config clothing.</p><h3>The usage counter</h3><p>Two more requirements land this layer, back to back.</p><p>First, support wants a live view of active sessions. A customer writes in“checkout is broken” and the first question is always <em>what did they last touch?</em> That’s not a window or an aggregation; it’s the latest event per session, which is exactly what reading the topic as a table means. One events.toTable()the KTable lens from the top of this layer, applied literally and each session&#39;s row is its most recent event. Wire the store to a small internal endpoint and support has their dashboard.</p><p>Second, the team building our customer-facing usage dashboard needs events per user, kept current. Not windowed, just a running activity count per user_id.</p><p>The obvious build is a second full pass over the raw stream. But we’re already materializing the per-session table, already paying its RocksDB and changelog costs, so the counter derives from it instead: group its rows by user, and maintain the count across updates with the table aggregate’s add/subtract pair:</p><pre>KTable&lt;String, TrackingEvent&gt; latestPerSession = events.toTable();<br><br>KTable&lt;String, Long&gt; eventsPerUser = latestPerSession<br>    .groupBy((sessionId, ev) -&gt; KeyValue.pair(ev.getUserId(), ev))<br>    .aggregate(<br>        () -&gt; 0L,<br>        // adder: session row inserted or updated -&gt; one more event<br>        (userId, ev, count) -&gt; count + 1,<br>        // subtractor: old value retracted on every update (and on deletes, which<br>        // never happen here. No tombstones); we keep the count, not a reversible sum<br>        (userId, ev, count) -&gt; count,<br>        Materialized.as(&quot;events-per-user&quot;));</pre><p>Each event updates its session’s row; each row update bumps the owning user’s count. The numbers match the raw stream in every test, it reuses a table we were already paying for, and the dashboard team ships their feature. Tidy.</p><h3>Reading the state store directly</h3><p>Both features end the same way “wire the store to an endpoint” . A state store is a queryable key-value store already sitting inside the application process. You can read it in place, with no second datastore to populate and keep in sync. Kafka Streams calls this <strong>interactive queries</strong>: ask a running store for the current value of a key.</p><pre>// In the topology: reading events as a table materializes a named store.<br>// This is the same latestPerSession table the usage counter grouped over.<br>KTable&lt;String, TrackingEvent&gt; latestPerSession =<br>    events.toTable(Materialized.as(LATEST_PER_SESSION_STORE));  // &quot;latest-per-session&quot;<br><br>// In the request handler: look that store up by name and read a key.<br>@GetMapping(&quot;/support/sessions/{sessionId}&quot;)<br>public ResponseEntity&lt;DashboardEvent&gt; latestForSession(@PathVariable String sessionId) {<br>    ReadOnlyKeyValueStore&lt;String, TrackingEvent&gt; store = streams.getKafkaStreams()<br>        .store(StoreQueryParameters.fromNameAndType(<br>            LATEST_PER_SESSION_STORE, QueryableStoreTypes.keyValueStore()));<br>    TrackingEvent latest = store.get(sessionId);<br>    return latest == null<br>        ? ResponseEntity.notFound().build()<br>        : ResponseEntity.ok(DashboardEvent.from(latest));<br>}</pre><p>The store isn’t a separate thing you populate; it’s the materialization of the latestPerSession table, named once at Materialized.as(...) and looked up by that same name at query time. Support&#39;s endpoint and the usage dashboard&#39;s /usage/{userId} are the same shape against a different store: name the store, ask for a key, return what&#39;s there. No Postgres behind it, the data is directly sourced from the kafka topic.</p><p>There’s one assumption hiding in store.get(sessionId), and it&#39;s the sharding point from earlier wearing different clothes: an instance holds only the partitions it owns. Right now a single process owns all twelve, so every key is local and the lookup always finds its store. Add a second instance and half the keys move to the other process , get on the wrong one returns null for data that plainly exists. Finding which instance owns a key and hopping to it is real work, and it&#39;s work this series takes up once there&#39;s more than one instance to worry about.</p><h3>What survives a restart</h3><p>One question the whole state-store machinery raises: your service restarts (a deploy, a crash etc) and by the time it’s back, the original events have aged off the source topic under normal retention (7 days default) . Will the counter still reflect accurate values?</p><p>Start with what a restart costs. The RocksDB store is local to the instance; treat it as lost when the process dies (on ephemeral container storage it literally is). What <em>isn’t</em> lost is the <strong>changelog, </strong>a Kafka topic, durable independently of any one instance. So the app rebuilds each store by replaying its changelog from the beginning, then resumes consuming events from its last committed offset for anything new. A brand-new instance joining later does the identical thing for the partitions it&#39;s handed: no local state, so read the changelog from the start and materialize its shard. State is always reconstructed from its log, never handed between processes.</p><p>That’s why source-topic retention is a red herring for the counter. events aging out doesn&#39;t touch it, because the counter restores from the events-per-user changelog and that changelog is <strong>compacted</strong>: latest value per key, kept regardless of age. Replay lands you back on exactly the count you had. Rotate out the source topic events all you like; the compacted changelog is the durable copy.</p><p>The windowed session store answers the same question differently, by design. Its changelog is compact <em>and</em> delete, with a retention tied to the window’s reach. So a restart rebuilds only the windows still inside that horizon. Sessions that closed weeks ago are <strong>not</strong> restored, and that’s intended: their summaries already flowed to the sessions topic when they closed, the windows are finished, and nothing will ever ask about them again. Rebuilding them would be paying to restore state no one reads. A running table keeps its whole history; a time window keeps only its live edge.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*C05cAkfPD_vsnLXX7HMOaw.png" /><figcaption>Case by case comparison of how stateful abstraction deal with crashes differntly.</figcaption></figure><h3>Where this leaves us</h3><p>The pipeline remembers now. Sessions close themselves, summaries flow to a topic, the state behind it all is sharded next to the partitions it serves and journaled to changelogs for recovery. Stateless was a special case; this is what stream processing actually is.</p><p>The sessions topic makes people greedy almost immediately. The first consumer of session summaries is the growth team, and their first question is “great, <em>whose</em> sessions?” They want the summary joined with the user’s profile: plan tier, signup date, region. All of that lives in the accounts service’s Postgres, a different system owned by a different team.</p><p>Getting another system’s data to enrich a stream sounds routine. It’s a join, the most ordinary operation in data engineering. Layer 5 is about why, in a partitioned world, this ordinary operation comes with a requirement nobody warns you about, and what it looks like when that requirement is violated: no errors, no crashes, just enrichments that quietly don’t happen.</p><p>Access the full source code for this layer at : <a href="https://github.com/Panda0Monium/kafka-layer-by-layer/tree/master/layer4">https://github.com/Panda0Monium/kafka-layer-by-layer/tree/master/layer4</a></p><p><a href="https://medium.com/@karanpatel2193/down-the-stack-kafka-in-nine-layers-65541826dd65"><em>Down the Stack: Kafka in Nine Layers</em></a><em> · Prev: </em><a href="https://medium.com/@karanpatel2193/kafka-layer-3-client-sends-garbage-1cb99b3751ca"><em>Layer 3</em></a><em> · Next: Layer 5, The Join That Silently Failed [LINK]</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=191ea944e350" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Kafka Layer 3: Client Sends Garbage]]></title>
            <link>https://medium.com/@karanpatel2193/kafka-layer-3-client-sends-garbage-1cb99b3751ca?source=rss-c591fa7fe717------2</link>
            <guid isPermaLink="false">https://medium.com/p/1cb99b3751ca</guid>
            <category><![CDATA[avro]]></category>
            <category><![CDATA[kafka-streams]]></category>
            <category><![CDATA[schema]]></category>
            <category><![CDATA[apache-kafka]]></category>
            <category><![CDATA[dead-letter-queue]]></category>
            <dc:creator><![CDATA[Karan Patel]]></dc:creator>
            <pubDate>Mon, 06 Jul 2026 04:21:47 GMT</pubDate>
            <atom:updated>2026-07-26T21:13:19.465Z</atom:updated>
            <content:encoded><![CDATA[<p><em>Layer 3 of </em><a href="https://medium.com/@karanpatel2193/down-the-stack-kafka-in-nine-layers-65541826dd65"><em>Down the Stack: Kafka in Nine Layers.</em></a><em> Three teams, one topic, no contracts. This is the layer where the pipeline grows up.</em></p><p>Layer 2 ended with two dashboards quietly disagreeing for a week because a mobile SDK renamed a field. Nobody broke a build. Nobody triggered an alert. The producers changed the data’s shape, the topic accepted it (topics accept everything), and every consumer coped differently: one handled both shapes, one dropped the new events, one counted them with a null URL.</p><p>Before fixing it properly, let’s look at a failure mode that is worth understanding before you go to production: the poison pill.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/350/1*vYlQRYqGblb7s8N_Ejd4YQ.jpeg" /><figcaption>A poison pill message is potentially like throwing a spanner in the works</figcaption></figure><h3>The poison pill</h3><p>To test your error handling, you deliberately send a malformed record: truncated mid-JSON, simulating a flaky client on a dying connection:</p><pre>{&quot;event_type&quot;: &quot;page_view&quot;, &quot;user_id&quot;: &quot;u-99</pre><p>The page-counter’s deserializer throws. The listener dies, the container restarts it, and it resumes from its last committed offset, which is the offset <em>before</em> the malformed record. It reads the same record. It throws again.</p><p>This is a poison pill: a message that cannot be processed, sitting in an ordered lane that must be consumed in order. The consumer is in a crash loop, and here is the part that surprises people: <strong>everything behind that message in the partition waits.</strong> One unparseable record from one broken client has stopped one twelfth of the pipeline’s capacity. Lag on that partition climbs while the other eleven hum along. In production, this produces a signature symptom: some users’ data is current and some is frozen, with no obvious boundary between them.</p><p>This test is worth running deliberately in development because the fix is easy and the production version of this incident is not:</p><p>The fix pattern is standard and worth doing properly once:</p><pre>@KafkaListener(topics = &quot;events&quot;, groupId = &quot;page-counter&quot;)<br>public void onEvent(ConsumerRecord&lt;String, String&gt; record) {<br>    try {<br>        process(json.readValue(record.value(), PageEvent.class));<br>    } catch (Exception e) {<br>        dlq.send(&quot;events.dlq&quot;, record.key(), record.value());  // and a metric, and the error as a header<br>    }<br>}</pre><p>Catch, divert to a dead letter topic, move on. The DLQ gets a monitor on its message rate, and somebody owns looking at it (a DLQ nobody reads is just a slower way to lose data). Spring’s DefaultErrorHandler with a DeadLetterPublishingRecoverer gives you this with retries included; the repo wires it up fully.</p><pre>@Bean<br>DefaultErrorHandler errorHandler(KafkaTemplate&lt;Object, Object&gt; template) {<br>    var recoverer = new DeadLetterPublishingRecoverer(template,<br>        (record, ex) -&gt; new TopicPartition(record.topic() + &quot;.dlq&quot;, record.partition()));<br>    // two retries, one second apart, then publish to the DLQ<br>    return new DefaultErrorHandler(recoverer, new FixedBackOff(1000L, 2));<br>}</pre><p>The recoverer stamps the exception, original topic, partition, and offset into headers on the dead-lettered record, so whoever reads the DLQ can see what failed and where it came from. One catch specific to our poison pill: a record that fails <em>deserialization</em> dies before the listener ever runs, so the error handler alone can’t help. Wrap the deserializer in Spring’s ErrorHandlingDeserializer and the failure is converted into an exception the handler can route:</p><pre>spring.kafka.consumer.value-deserializer=org.springframework.kafka.support.serializer.ErrorHandlingDeserializer<br>spring.kafka.consumer.properties.spring.deserializer.value.delegate.class=org.apache.kafka.common.serialization.StringDeserializer</pre><p>The DLQ stops the bleeding. It does nothing about the disease: producers and consumers have no shared definition of what an event <em>is</em>. Time for contracts.</p><h3>Schemas, and where they live</h3><p>We’re adopting Avro and a Schema Registry. The mechanics first, because they’re simple and widely misunderstood.</p><p>An Avro schema defines the event’s fields and types. The producer serializes against the schema; what goes on the wire is a compact binary payload prefixed with a small schema ID. The schemas themselves live in the registry, a separate service. Consumers see the ID, fetch the schema once from the schema registry, cache it, and deserialize. Nobody ships schema files around; nobody parses JSON hopefully.</p><p>The serializer config is one line each side (KafkaAvroSerializer / KafkaAvroDeserializer plus the registry URL), and from then on, a producer physically cannot publish an event that doesn&#39;t match a registered schema. The SDK-rename incident becomes impossible to ship silently: renaming a field changes the schema, and the registry is now a gate that change must pass through.</p><p>What does the gate check? The registry holds a <em>compatibility mode</em> per subject, and on every new schema version it verifies the change is safe relative to the old one. The default mode is BACKWARD: consumers on the newest schema can still read data written under the previous one. Given how much this pipeline leans on replay, that&#39;s the property we need.</p><h3>The schema</h3><p>Here’s the contract we register, and since this is the artifact three teams will live with, the design discussion is worth recording.</p><pre>{<br>  &quot;type&quot;: &quot;record&quot;,<br>  &quot;name&quot;: &quot;TrackingEvent&quot;,<br>  &quot;fields&quot;: [<br>    {&quot;name&quot;: &quot;event_type&quot;, &quot;type&quot;: {&quot;type&quot;: &quot;enum&quot;, &quot;name&quot;: &quot;EventType&quot;,<br>        &quot;symbols&quot;: [&quot;PAGE_VIEW&quot;, &quot;CLICK&quot;, &quot;HEARTBEAT&quot;, &quot;SIGNUP&quot;]}},<br>    {&quot;name&quot;: &quot;session_id&quot;, &quot;type&quot;: &quot;string&quot;},<br>    {&quot;name&quot;: &quot;user_id&quot;,    &quot;type&quot;: [&quot;null&quot;, &quot;string&quot;], &quot;default&quot;: null},<br>    {&quot;name&quot;: &quot;url&quot;,        &quot;type&quot;: &quot;string&quot;},<br>    {&quot;name&quot;: &quot;app_version&quot;,&quot;type&quot;: &quot;string&quot;},<br>    {&quot;name&quot;: &quot;ts&quot;,         &quot;type&quot;: &quot;long&quot;}<br>  ]<br>}</pre><p>Three choices, three rationales, straight from our design review:</p><p>event_type<strong> is an enum.</strong> It had been a free string, and free strings invite garbage: we&#39;d already seen page_view, pageview, and PageView in the wild, which is one bug per spelling. An enum makes the valid set explicit, gives the Java code a real type instead of string comparisons, and makes typos a compile error at the producer. Type safety all the way down.</p><p>user_id<strong> is nullable, because it genuinely is.</strong> Anonymous visitors don&#39;t have one. The schema says so honestly.</p><p>app_version<strong> is required, no default.</strong> Every current SDK sends it, the debugging from this very incident would have been halved if we&#39;d had it, and marking it optional invites sloppy clients to omit it. If it&#39;s important, the schema should demand it. (A default value felt like an invitation to lie: a fake version string is worse than none.)</p><p>Each of these would pass most code reviews I’ve sat in. Schemas registered, old-format stragglers diverted to the DLQ during a short transition window, and for the first time the topic has a contract with teeth.</p><h3>A first taste of stream processing</h3><p>With the data trustworthy, we can clean up a wart that’s bothered me since Layer 1: every consumer filters out heartbeats, skips malformed events, and routes on event type, each in its own slightly different way. That’s processing logic, copy-pasted across teams.</p><p>Kafka Streams enters here, in its most modest form. A Streams application is just a Java service (ours is the same Spring Boot setup) that consumes topics, transforms records, and produces to other topics. No cluster to run; the “engine” is a library in your app. The stateless operations read like collection code:</p><pre>StreamsBuilder builder = new StreamsBuilder();<br>KStream&lt;String, TrackingEvent&gt; events = builder.stream(&quot;events&quot;);<br>Map&lt;String, KStream&lt;String, TrackingEvent&gt;&gt; branches = events<br>    .filter((sessionId, ev) -&gt; ev.getEventType() != EventType.HEARTBEAT)<br>    .split(Named.as(&quot;by-type-&quot;))<br>    .branch((id, ev) -&gt; ev.getEventType() == EventType.PAGE_VIEW, Branched.as(&quot;page-views&quot;))<br>    .branch((id, ev) -&gt; ev.getEventType() == EventType.SIGNUP,    Branched.as(&quot;signups&quot;))<br>    .defaultBranch(Branched.as(&quot;other&quot;));<br>branches.get(&quot;by-type-page-views&quot;).to(&quot;events.page-views&quot;);<br>branches.get(&quot;by-type-signups&quot;).to(&quot;events.signups&quot;);</pre><p>One small service now owns normalization: heartbeats dropped, events fanned out to clean per-type topics. The dashboard team reads events.page-views and deletes its filtering code. The growth team reads events.signups. The raw topic stays as the source, and the derived topics are conveniences computed from it, an idea that will get much bigger by Layer 7.</p><p>filter, map, branch: nothing here remembers anything between events. Each record is processed alone. That&#39;s what &quot;stateless&quot; means, and it&#39;s exactly the property we&#39;re about to lose.</p><h3>What partition count do the new topics get?</h3><p>This layer quietly created four topics: events.dlq from the error handler, and the three branch outputs from the normalizer. Layer 2 spent a whole section deciding that events gets twelve partitions. Do the new topics inherit that number?</p><p>For the DLQ, yes, and not by choice. Look back at the recoverer’s resolver: it routes with record.partition(), so the dead-lettered record keeps its original partition number. That default exists for a reason (it preserves per-partition ordering in the DLQ and makes &quot;which lane broke&quot; visible at a glance), but it quietly couples the DLQ&#39;s shape to the source topic&#39;s. events.dlq needs at least as many partitions as events. Create it explicitly; if the broker auto-creates it with a smaller default, the recoverer will publish to a partition that doesn&#39;t exist, and now the error handler is the component that&#39;s failing. If you don&#39;t care about ordering in the DLQ, resolve to a negative partition and let the producer choose.</p><p>For the branch topics, the first question is who creates them at all. Not Streams: it auto-creates its own <em>internal</em> topics (we talk about internal topics in Layers 4 and 5), but output topics named in to() are your job. Lean on broker auto-creation and they may materialize with the broker&#39;s default partition count, often one, and whoever consumes them is back in the single-lane world Layer 2 dug us out of.</p><p>So we create them explicitly, with twelve partitions, same as events. Strictly, nothing forces this. The partitioner runs fresh on every produce, hashing the key and modding by <em>that topic&#39;s</em> partition count, so the session key delivers its per-session ordering at any count: a five-partition events.page-views would still put all of session s-123&#39;s views in one lane, in order. What a mismatch changes is the partition <em>number</em>. The same hash modded by twelve and by five puts the same session on partition 7 of one topic and partition 2 of the other. No plain consumer cares. But matching the source lets downstream consumers scale to the same width, and it keeps the derived topics co-partitioned with the raw one: same key, same partition number, everywhere.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mqHgLzbtfJnfEbwl5b8otg.png" /><figcaption>Figure shows the message topology with the new topics. We keep the same number of partitions for the derived topics to ensure the events are not re-routed to different partitions.</figcaption></figure><h3>Where this leaves us</h3><p>Contracts at the door, a DLQ for the garbage, derived topics for the common shapes. The pipeline now fails loudly at the edges instead of quietly in the middle, which is most of what “production grade” means.</p><p>Then product management attends a conference and returns with a question: “What’s our average session duration? Oh, and which pages do users visit in their first five minutes?”</p><p>Look at what answering that requires. Session duration means knowing when a session started, which happened thousands of events ago, possibly twenty minutes ago, possibly on a different calendar day. First-five-minutes behavior means every event has to be considered relative to the session’s beginning. Every operation we’ve written so far looks at one event and forgets it. These questions are about <em>spans</em> of events, and answering them means the pipeline has to start remembering.</p><p>Memory in a system that processes millions of events across a dozen partitions and several instances is not a simple map. Layer 4 is about state: where it lives, who owns which slice of it, what happens to it when things restart, and the two kinds of time every event secretly carries.</p><p>Read full source for this layer at :<a href="https://github.com/Panda0Monium/kafka-layer-by-layer/tree/master/layer3">https://github.com/Panda0Monium/kafka-layer-by-layer/tree/master/layer3</a></p><p><a href="https://medium.com/@karanpatel2193/down-the-stack-kafka-in-nine-layers-65541826dd65"><em>Down the Stack: Kafka in Nine Layers </em></a><em>· Prev: </em><a href="https://medium.com/@karanpatel2193/layer-2-the-app-gets-popular-8c7121feae1e"><em>Layer 2</em></a><em> · Next: </em><a href="https://medium.com/@karanpatel2193/kafka-layer-4-sessions-and-state-191ea944e350"><em>Layer 4, Sessions and State</em></a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1cb99b3751ca" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Layer 2: The App Gets Popular]]></title>
            <link>https://medium.com/@karanpatel2193/layer-2-the-app-gets-popular-8c7121feae1e?source=rss-c591fa7fe717------2</link>
            <guid isPermaLink="false">https://medium.com/p/8c7121feae1e</guid>
            <category><![CDATA[parallelism]]></category>
            <category><![CDATA[apache-kafka]]></category>
            <category><![CDATA[kafka-consumer-group]]></category>
            <category><![CDATA[distributed-computing]]></category>
            <dc:creator><![CDATA[Karan Patel]]></dc:creator>
            <pubDate>Sat, 27 Jun 2026 03:33:13 GMT</pubDate>
            <atom:updated>2026-07-26T19:39:37.597Z</atom:updated>
            <content:encoded><![CDATA[<p><em>Layer 2 of </em><a href="https://medium.com/@karanpatel2193/down-the-stack-kafka-in-nine-layers-65541826dd65"><em>Down the Stack: Kafka in Nine Layers</em></a><em>. One partition, one consumer, and a growth chart that is pointing in the wrong direction.</em></p><p>Layer 1 left us with a working system: one topic, one partition, one consumer, counts landing in Mysql. At current traffic this is fine. But the product is growing, and it is worth thinking through what “traffic grows” actually means for this architecture before it happens, not after.</p><p>Here is the scenario to plan for: the app gets featured, traffic spikes 40x in a couple of hours. The producer side is not a concern, appending to a log is cheap and the broker barely notices. The consumer side is the problem. It processes events one at a time, and with an order-of-magnitude jump in ingest rate, the lag between “event happened” and “event counted” starts growing. The instinctive fix is to run more consumers, and here the one-partition decision comes due: within a consumer group, a partition is read by exactly one consumer at a time. A second page-counter instance connects, gets assigned no work, and sits idle. The unit of consumer parallelism in Kafka is the partition.</p><p>Understanding why unlocks most of Kafka’s scaling model.</p><h3>Partitions: the unit of everything</h3><p>A topic in Kafka isn’t really one log. It’s N logs, called partitions, and each partition is the thing that’s actually ordered, actually stored on disk, and actually assigned to consumers.</p><p>Our topic has one partition, so it behaves like one log. Within a consumer group, a partition is read by exactly one consumer at a time. One partition, one reader; the second instance has nothing to claim.</p><blockquote>The unit of consumer parallelism in Kafka is the partition.</blockquote><p>So we need more partitions. How many?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hlfeC5g7FRUQXEdWr0KhIg.png" /></figure><p>“More than one” is not a plan. Partitions have downstream consequences: every partition is files on disk, replicas across brokers, and (critically for this series) a state store shard per Streams application. Overshooting now means carrying unused overhead forever; undershooting means redoing this work later, which breaks key routing in ways Layer 5 will make concrete.</p><p>Back-of-envelope: Assuming the app is grows toward 10,000 events per second at peak. Benchmarking the consumer under sustained load, with the MySQL write and JSON deserialization in the critical path, shows roughly 1,000 events per second per consumer thread. That gives a raw minimum of 10. The benchmark number is optimistic: real traffic bursts rather than sustains, and production adds garbage collector pauses and connection pool contention that a controlled run never sees. Round up to 12 because it divides evenly by 3, 4, 6 (clean assignments for our likely consumer counts) and in a three-broker cluster places exactly four leader partitions per broker.</p><p>One thing that number commits us to: <strong>partition count should stay constant for as long as this topic is part of a Streams topology.</strong> Partitions are how Kafka distributes work, and state stores are sharded in lockstep with partitions. Change the partition count after the fact and hash(key) % N routes events to different partitions than the state that was built for those keys. This produces silent misses in every join and aggregation downstream. The right time to think about partition count is before the first record is written.</p><p>The commitment doesn’t stop at the ingestion team’s own consumers. Kafka Streams requires co-partitioning for stateful joins: any two topics joined in a topology must have the same partition count and the same partitioner, so that records with the same key land on the same task. Twelve partitions on events means every downstream Streams topology joining against it needs its partner topics to also have twelve partitions. A team that wants to join events with a six-partition experiment-assignments topic has to resolve the mismatch: either align the topics upfront, or rekey one stream inside the topology (which causes Streams to create an internal repartition topic automatically, adding a write step per record). Teams that only consume without joining are unaffected beyond the parallelism ceiling of twelve consumers. Teams using a GlobalKTable (which broadcasts the full table to every task and waives the co-partitioning requirement) are also clear. Everyone else inherits the number chosen today.</p><pre>kafka-topics.sh --bootstrap-server localhost:9092 \<br>  --create --topic events --partitions 12</pre><p>Twelve partitions means up to twelve consumers in a group, each owning a slice. Run four instances of the page-counter and each gets three partitions; the lag drains in minutes.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*oz_BO1Dlyw5UoJneBXt6RQ.png" /><figcaption>4 different jvms/threads of the page-counter service, each reading from a different paritition</figcaption></figure><p>But we’ve just changed something subtle and important. With one partition, every event was in one ordered sequence. With twelve, Kafka guarantees order <em>within</em> a partition and says nothing about order <em>across</em> partitions. An event in partition 3 and an event in partition 9 have no defined relative order, no matter when they were produced.</p><p>Which raises the question Layer 1 ended on: when an event arrives, which partition does it go to?</p><h3>The key decides</h3><p>Every Kafka record has an optional key. When routing a record to a partition, the partitioner uses that key. Three policies are worth knowing:</p><ul><li><strong>No key (sticky/round-robin):</strong> Records are distributed across partitions for even throughput. A batch sticks to one partition briefly (for batching efficiency), then moves to the next. No ordering guarantees between any two records.</li><li><strong>Key-based (murmur2 hash):</strong> partition = murmur2(key) % partition_count. Records with the same key always land on the same partition. This is Kafka&#39;s per-key ordering guarantee: every event for a given key arrives in the order it was produced, on one partition, processed by one consumer. It is also the foundation of the co-partitioning requirement in joins, which Layer 5 will explore in detail.</li><li><strong>Custom partitioner:</strong> Implement the Partitioner interface for business-aware routing (dedicated partitions for high-priority tenants, for example). Custom partitioners are the sharpest edge in the toolbox: you now own the contract of what &quot;same key implies same partition&quot; means, and getting it wrong is silent.</li></ul><p>For our analytics events, key-based partitioning seems right. The ordering guarantee is what we need. Did the user view the pricing page before or after the docs page? Events scattered keylessly across partitions will be processed out of order by different consumers.</p><p>The remaining question is which key to use.</p><p>The obvious candidate is user_id, and we can&#39;t use it: half our traffic is anonymous. Visitors browse logged-out, and user_id doesn&#39;t exist until they sign in. What every event <em>does</em> have, from the first page load, is the session: the tracking snippet mints a session_id cookie on arrival and sends it with every event.</p><pre>kafka.send(&quot;events&quot;, event.sessionId(), json.writeValueAsString(event));</pre><p>One argument added to the send() call. Every session&#39;s events now arrive in order, on one partition, and funnels work for anonymous and logged-in visitors alike. Sessions are the unit of analysis in this product, so the sessionId is the key.</p><p>A brief side note, because someone always asks: if ordering is good, why not order <em>everything</em>? Because a topic with global ordering is a topic with one partition, which is a system with one consumer, which is the lag problem we just escaped. Global ordering and parallelism are the same dial turned in opposite directions. The skill isn’t maximizing ordering; it’s knowing the smallest unit that genuinely needs it.</p><h3>Consumer groups, properly this time</h3><p>Layer 1 hand-waved group.id as a named bookmark. Here&#39;s the fuller picture: a consumer group is a set of consumers sharing one bookmark <em>and</em> one workload. Kafka divides the topic&#39;s partitions among the group&#39;s members, and when membership changes (an instance deploys, crashes, or scales), it redistributes them. That redistribution is called a rebalance. For now, think of it as brief musical chairs; several later layers will give it the respect it deserves.</p><p>The part that makes groups quietly brilliant is what happens <em>between</em> groups: nothing. Each group has its own offsets, its own pace, its own members. The same data, read independently by everyone who needs it.</p><p>That matters because the page-counter no longer has the topic to itself. Success attracted teams:</p><ul><li>The <strong>dashboard team</strong> wants raw events for a live view.</li><li>The <strong>growth team</strong> wants to alert when signups dip.</li><li>The <strong>data team</strong> wants everything, eventually, in the warehouse.</li></ul><p>In a queue world, each of these is a request to the ingestion team: build us a feed, fork the stream, add a binding. In Kafka, each team picks a group.id and starts reading. The prologue called the topic an organizational contract; this is what that looks like in practice.</p><pre>// Each team writes their own listener against the same topic<br>@KafkaListener(topics = &quot;events&quot;, groupId = &quot;page-counter&quot;)<br>public void count(ConsumerRecord&lt;String, String&gt; r) { /* Layer 1&#39;s counter */ }<br>@KafkaListener(topics = &quot;events&quot;, groupId = &quot;live-dashboard&quot;)<br>public void display(ConsumerRecord&lt;String, String&gt; r) { /* real-time feed */ }<br>@KafkaListener(topics = &quot;events&quot;, groupId = &quot;signup-alerts&quot;)<br>public void alert(ConsumerRecord&lt;String, String&gt; r) { /* only cares about SIGNUP events */ }</pre><p>The broker tracks three independent offsets. signup-alerts only reads signup events, so it falls behind the others in offset terms and nobody cares: Kafka doesn&#39;t know which events you&#39;ll process inside the listener, only that you read the record:</p><pre>group &quot;page-counter&quot;   -&gt; offset 84,213,991<br>group &quot;live-dashboard&quot; -&gt; offset 84,214,002<br>group &quot;signup-alerts&quot;  -&gt; offset 84,002,117</pre><h3>Consumer threading: what you are actually running</h3><p>A consumer group is one of the most important concepts to understand regards to kafka and its threading model is where some of the subtler failures later in this series are born.</p><p>Each consumer is a <strong>poll loop</strong>: a thread (or process, or JVM) that calls poll() on a schedule, receives a batch of records, processes them, and calls poll() again. The broker doesn&#39;t push; the consumer pulls.</p><p>Two separate mechanisms tell the broker a consumer is alive, and they catch different failure modes:</p><ul><li><strong>Heartbeat thread:</strong> a background thread sends periodic heartbeats to the broker independently of the poll loop. If the broker stops receiving them for longer than session.timeout.ms (default 45 seconds), it declares the consumer dead and triggers a rebalance. This catches hard failures: process crashes, GC freezes long enough to stall the heartbeat thread, network partitions.</li><li><strong>Poll interval:</strong> the broker also tracks how long it has been since the last poll() call. If that gap exceeds max.poll.interval.ms (default five minutes), the consumer is evicted even if heartbeats are still arriving. This catches a different problem: a consumer that is alive but stuck processing a batch so large or slow that it never comes back for more records.</li></ul><p>The distinction matters because the fix is different. A session timeout means the consumer process is unhealthy. A poll interval breach means the processing inside the listener is too slow for the batch size, and the right lever is max.poll.records or making the processing faster, not the timeout.</p><p>Consumer instances in the same group can be different JVMs on different machines, for e.g. all page-counter replicas share a group.id and Kafka treats them as a pool of active poll loops. They can also be threads within the same JVM: spring-kafka&#39;s @KafkaListener on a single-threaded container is one poll loop, one thread, one consumer. If that consumer owns three partitions, their records are processed sequentially on that thread, partition 3&#39;s batch first, then 7&#39;s, then 11&#39;s, one after another. For concurrency inside one JVM, ConcurrentKafkaListenerContainerFactory.setConcurrency(N) creates N separate consumer instances, each with its own poll loop and assignment.</p><blockquote>The poll interval check is at the consumer level, not the partition level.</blockquote><p>Processing one partition’s batch can’t stall without affecting the others on the same consumer. If a slow database write or an external API call inside the listener takes longer than max.poll.interval.ms, the broker evicts the entire consumer, not just the slow partition, the whole consumer and all its healthy partitions. The rebalance that follows pauses work across the group until it resettles. Slow downstream calls inside a listener are not a latency problem; they are a group-health problem. This pattern has further implications in Layer 7 when we add gRPC calls inside the processing loop.</p><p>The config that governs this, worth setting explicitly rather than leaving at the default:</p><pre>spring:<br>  kafka:<br>    consumer:<br>      max-poll-interval-ms: 30000    # default is 300000 (5 min); size to your actual processing time<br>      max-poll-records: 100          # batch size per poll; smaller batches = more frequent polls</pre><p>Kafka Streams manages threading similarly: num.stream.threads (default one) controls how many internal threads the application runs, each owning a subset of assigned partitions, under the same poll-interval contract.</p><h3>Sidebar: when to not use kafka</h3><p>Around this time in our story, a neighboring team sees the shiny new event pipeline and asks to use it for webhook delivery: customers register URLs, the product POSTs events to them. Retry with backoff if an endpoint is down, rate-limit per customer, give up after 24 hours, let customers replay missed deliveries. “It’s events going out instead of in. Just another topic, right?”</p><p>It’s a reasonable instinct, and it leads somewhere bad, and walking through why is one of the better ways to understand what Kafka is.</p><p>A partition is an ordered lane that must be consumed in order. Webhook delivery is the opposite of that: thousands of independent jobs, each with its own retry clock, no meaningful order among them. Put them in a partition and one customer’s dead endpoint becomes everyone’s problem: the consumer hits the failing delivery, and now it either blocks the whole lane retrying (head-of-line blocking: every webhook behind it waits), or it skips ahead and has to track out-of-band which offsets still need work, at which point you’ve built a job queue <em>on top of</em> Kafka, badly, with the log fighting you the whole way. Per-message retry schedules, per-customer rate limits, priorities, delayed delivery: none of these map onto “read a file forward.”</p><p>A boring job queue (SQS, RabbitMQ, even a database table with a worker pool) handles all of it natively, because per-message lifecycle is exactly what those tools model and exactly what Kafka deliberately gave up to get its throughput.</p><p>The lesson generalizes: <strong>Kafka is a log, not a job queue.</strong> Logs are for facts that many readers consume in order; job queues are for tasks that workers complete independently. Most “Kafka was a mistake here” stories start with confusing the two. The webhook team got a job queue and everyone stayed friends.</p><h3>Where this leaves us</h3><p>The pipeline scales now. Twelve partitions, four counter instances, per-session ordering for the funnel team, and three consumer groups reading independently. The system survived its first scaling problems.</p><p>The next problem doesn’t announce itself with lag graphs. It arrives quietly, in a Slack thread, two weeks after the mobile team ships SDK v2.</p><p>The dashboard team’s numbers and the growth team’s numbers have drifted apart. Same topic, same events, different answers. After a day of confused digging, someone finds it: v2 renamed the url field to page_url. New-SDK events have been flowing in with a shape one consumer handles and another doesn&#39;t, and nothing anywhere considered that an error. Every team parses the JSON its own way, every parser fails its own way, and the topic, faithful append-only log that it is, accepted all of it without comment.</p><p>Three teams, one topic, zero contracts. Layer 3 is about fixing that, and about the day we learned what a single malformed message does to a partition.</p><p>Read the full code for this layer at : <a href="https://github.com/Panda0Monium/kafka-layer-by-layer/tree/master/layer2">https://github.com/Panda0Monium/kafka-layer-by-layer/tree/master/layer2</a></p><p><a href="https://medium.com/@karanpatel2193/down-the-stack-kafka-in-nine-layers-65541826dd65"><em>Down the Stack: Kafka in Nine Layers</em></a><em> · Prev: </em><a href="https://medium.com/@karanpatel2193/layer-1-track-page-views-bbac54dc88e9"><em>Layer 1</em></a><em> · Next:</em><a href="https://medium.com/@karanpatel2193/kafka-layer-3-client-sends-garbage-1cb99b3751ca"><em> Layer 3, Clients Send Garbage</em></a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8c7121feae1e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Layer 1: Track Page Views]]></title>
            <link>https://medium.com/@karanpatel2193/layer-1-track-page-views-bbac54dc88e9?source=rss-c591fa7fe717------2</link>
            <guid isPermaLink="false">https://medium.com/p/bbac54dc88e9</guid>
            <category><![CDATA[kafka-log-retention]]></category>
            <category><![CDATA[pub-sub]]></category>
            <category><![CDATA[apache-kafka]]></category>
            <dc:creator><![CDATA[Karan Patel]]></dc:creator>
            <pubDate>Mon, 22 Jun 2026 09:52:55 GMT</pubDate>
            <atom:updated>2026-07-26T19:20:25.188Z</atom:updated>
            <content:encoded><![CDATA[<p><em>Layer 1 of Down the Stack: Kafka in Nine Layers. The prologue covered why Kafka was built. Now we build with it: one topic, one producer, one consumer.</em></p><p>Here’s the situation. You are building a web app and you want to know what users do in it: which pages get visited, how often, by whom. Nothing fancy yet. A counter per page is the first requirement.</p><p>The architecture for this layer is as small as it gets:</p><ol><li>A snippet in the app POSTs an event to a tiny ingest endpoint.</li><li>The endpoint produces the event to one Kafka topic.</li><li>One consumer reads the topic and keeps counts.</li></ol><p>One topic, one partition, no keys, raw JSON. Deliberately naive. This is the system a sensible engineer builds on day one, and it will carry us surprisingly far before it bites.</p><p>A note on code: the whole series is Java and Spring Boot, using spring-kafka (which wraps the official org.apache.kafka client) and, in later layers, Kafka Streams and the Confluent serializers. Snippets in posts are trimmed for reading. The companion repo has the runnable version of everything.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*scv5HQumFULWiKOs94ajyA.png" /></figure><h3>The event</h3><p>Every analytics pipeline starts with someone deciding what an event looks like. Ours, for now:</p><pre>{<br>  &quot;event_type&quot;: &quot;page_view&quot;,<br>  &quot;user_id&quot;: &quot;u-1842&quot;,<br>  &quot;url&quot;: &quot;/pricing&quot;,<br>  &quot;ts&quot;: 1718304000000<br>}</pre><h3>Standing up Kafka</h3><p>One broker in KRaft mode via Docker Compose. Create the topic:</p><pre>kafka-topics.sh --bootstrap-server localhost:9092 \<br>  --create --topic events --partitions 1</pre><p>That’s a decision hiding in a flag: --partitions 1 means the topic is a single log. Everything lands in one ordered sequence. Remember the shape, layer 2 is entirely about what happens to it.</p><h3>The producer</h3><pre>public record PageEvent(String eventType, String userId, String url, long ts) {}<br><br>@Service<br>public class TrackingService {<br><br>    private final KafkaTemplate&lt;String, String&gt; kafka;<br>    private final ObjectMapper json = new ObjectMapper();<br><br>    public TrackingService(KafkaTemplate&lt;String, String&gt; kafka) {<br>        this.kafka = kafka;<br>    }<br><br>    public void track(String eventType, String userId, String url) throws JsonProcessingException {<br>        var event = new PageEvent(eventType, userId, url, System.currentTimeMillis());<br>        kafka.send(&quot;events&quot;, json.writeValueAsString(event));<br>    }<br>}</pre><p>send() appends the event to the end of the log. There&#39;s no routing logic and no key, just &quot;add this to the file.&quot; In the real service this sits behind a small @RestController ingest endpoint; the repo version does exactly that.</p><h3>The consumer</h3><pre>@Component<br>public class PageCounter {<br><br>    private final ObjectMapper json = new ObjectMapper();<br>    private final Map&lt;String, Long&gt; counts = new ConcurrentHashMap&lt;&gt;();<br><br>    @KafkaListener(topics = &quot;events&quot;, groupId = &quot;page-counter&quot;)<br>    public void onEvent(String value) throws JsonProcessingException {<br>        var event = json.readValue(value, PageEvent.class);<br>        counts.merge(event.url(), 1L, Long::sum);<br>    }<br>}</pre><p>With one line of configuration in application.yml:</p><pre>spring:<br>  kafka:<br>    bootstrap-servers: localhost:9092<br>    consumer:<br>      auto-offset-reset: earliest</pre><p>(The repo version writes counts to mysql instead of a map; the listener is the same.)</p><p>Two configuration lines deserve attention, because they’re the prologue’s philosophy showing up in code.</p><p>group.id<strong> is a named bookmark.</strong> Kafka tracks how far &quot;page-counter&quot; has read in the log: a single number, the offset. That&#39;s all the broker remembers about this consumer. Not which messages were delivered, not which were acknowledged. One number per partition. Consumer groups do much more than this, and Layer 2 covers them properly; for now, one consumer, one bookmark.</p><p>auto.offset.reset: earliest<strong> answers &quot;where do I start if I have no bookmark.&quot;</strong> Our answer: the beginning of the log. The first time this consumer runs, it reads everything the topic retains, then keeps following the head.</p><p>And that’s the system. Events flow, counts accumulate. A dashboard reads the counts table. Ship it.</p><h3>Log replay in practice</h3><p>Early in development, before you have any real traffic, you add a heartbeat ping to the client SDK: it fires every 30 seconds to measure session liveness and help debug connectivity. You wire it up, run the consumer, and check the counts.</p><p>The numbers are wrong. Every page count is inflated. The consumer is counting heartbeat pings as page views, because it is counting every event, and when you wrote it, page views were the only events. Now there is a second event type, and the consumer logic was not updated.</p><p>The code fix is one line: count only event_type == &quot;page_view&quot;. But now consider: how do you fix the <em>data</em>?</p><p>With a fire-and-forget message queue, this question does not have a good answer. The messages were consumed, acknowledged, and deleted. If the system had been in production for weeks, you would be left estimating the inflation rate and applying a correction factor to every historical number, forever explaining the asterisk.</p><p>With a log, the messages are still there. The fix is to move the bookmark:</p><pre>kafka-consumer-groups.sh --bootstrap-server localhost:9092 \<br>  --group page-counter --topic events \<br>  --reset-offsets --to-earliest --execute</pre><p>Truncate the counts table, deploy the fixed consumer, and let it re-read the entire topic from offset zero. Twenty minutes later the table holds correct numbers for all the data you have, computed by the corrected code.</p><p>No restore-from-backup procedure, no data engineering ticket. Reprocessing is just reading. This is the replay property from the prologue, now concrete: the code was wrong, the data was not, and the log kept it safe until the code was fixed. When you do reach production scale and this happens with real historical data, the same mechanism applies with the only difference is how long the replay takes.</p><h3>What retention actually means</h3><p>The log isn’t infinite by default. Kafka retains data by policy; out of the box, that policy is seven days (retention.ms), after which old segments are deleted regardless of who has or hasn&#39;t read them.</p><p>Two things follow, and both are worth internalizing now:</p><ul><li>Retention is the replay window. Our three-week recount only worked because the repo config raised retention. With the 7-day default, the oldest two weeks would have been gone, silently.</li><li>Deletion has nothing to do with consumption. A queue deletes what’s been read; Kafka deletes what’s old. A message can be deleted having never been read by anyone, or read a hundred times and still retained.</li></ul><p>Retention is the first config in this series where the default is reasonable and also quietly load-bearing. It will not be the last.</p><h3>Where this leaves us</h3><p>Take stock of what we have: durable ingestion, a rebuildable derived view, and a replay capability that already paid for itself once. Total Kafka-specific code: roughly twenty lines. For a small app, this is honestly a fine production system.</p><p>Then your app gets big. Traffic goes up 40x in an hour. The producer side is fine; appending to a log is cheap and the broker barely notices. The consumer is not fine. It processes events one at a time, and the lag between “event happened” and “event counted” starts growing. The dashboard falls minutes behind, then hours. The log doesn’t lose anything (that’s the point of it), but nobody is reading fast enough.</p><p>The instinctive fix is to run more consumers. And here the one-partition decision comes due: a partition is an ordered sequence that can only be read in order, by one consumer in a group, at a time. A second “page-counter” instance connects, gets assigned nothing, and sits idle. The unit of consumer parallelism in Kafka is the partition, and we have one.</p><p>So we’ll add partitions. Which immediately raises a question that sounds trivial and is actually one of the most consequential in the whole system: when an event arrives and there are twelve partitions to choose from, <em>which partition does it go to?</em></p><p>That’s Layer 2. The answer involves a field called the key, what it does to ordering, and a choice that every event pipeline makes in its first week and lives with for years.</p><p>Download and run the full source code for layer 1 at : <a href="https://github.com/Panda0Monium/kafka-layer-by-layer/tree/master/layer1">https://github.com/Panda0Monium/kafka-layer-by-layer/tree/master/layer1</a></p><p><a href="https://medium.com/@karanpatel2193/down-the-stack-kafka-in-nine-layers-65541826dd65"><em>Down the Stack: Kafka in Nine Layers</em></a><em> · Prev: </em><a href="https://medium.com/@karanpatel2193/9ad6bf525995"><em>Prologue </em></a><em>· Next: </em><a href="https://medium.com/@karanpatel2193/layer-2-the-app-gets-popular-8c7121feae1e"><em>Layer 2, The App Gets Popular</em></a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bbac54dc88e9" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Prologue: The Log, or Why Kafka Exists]]></title>
            <link>https://medium.com/@karanpatel2193/prologue-the-log-or-why-kafka-exists-9ad6bf525995?source=rss-c591fa7fe717------2</link>
            <guid isPermaLink="false">https://medium.com/p/9ad6bf525995</guid>
            <category><![CDATA[kafka-log]]></category>
            <category><![CDATA[distributed-systems]]></category>
            <category><![CDATA[apache-kafka]]></category>
            <category><![CDATA[message-queue]]></category>
            <dc:creator><![CDATA[Karan Patel]]></dc:creator>
            <pubDate>Sat, 20 Jun 2026 19:38:01 GMT</pubDate>
            <atom:updated>2026-06-23T21:38:35.899Z</atom:updated>
            <content:encoded><![CDATA[<p><em>Layer 0 of </em><a href="https://medium.com/@karanpatel2193/down-the-stack-kafka-in-nine-layers-65541826dd65"><em>Down the Stack: Kafka in Nine Layers</em></a><em>. No code yet. Before we build anything, it’s worth understanding what problem Kafka was actually built to solve, because almost everything strange about Kafka stops being strange once you know.</em></p><p>In 2010, LinkedIn had a problem that had nothing to do with messaging.</p><p>They had data: page views, profile edits, search queries, connection events, application logs, database changes. And they had systems that needed that data: a data warehouse, a search indexer, a recommendation engine, monitoring, an experimentation platform. Every one of those systems needed much of the same data, and every one of them got it through its own custom pipeline, built by whichever team needed it, each with its own format, its own failure modes, and its own schedule.</p><p>With N sources of data and M systems consuming it, you have something that <strong>grows toward N times M</strong>. Every new data source means updating every consumer that wants it. Every new consumer means tapping every source it needs. Each pipeline looks reasonable on its own. Collectively, they’re a maintenance debt that compounds.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*g0vywAbubCpAveGUs9Uuog.png" /></figure><p>On top of the tangle, there was a timing problem. The pipelines that existed were mostly batch: collect the day’s data, ship it overnight, process it tomorrow. The business increasingly wanted answers now. Fraud signals, abuse detection, operational metrics, search freshness. A nightly batch is 24 hours of latency on a good day.</p><blockquote>So the actual problem was: get every kind of data, from every producer, to every consumer, continuously, at company scale. Messaging is just the shape the solution took.</blockquote><p>LinkedIn was not the first company to run into this. Facebook had independently diagnosed the same disease around 2008 and open-sourced their fix: Apache Scribe, a log-aggregation system for collecting and forwarding data from thousands of machines to central storage. Other companies were running similar custom infrastructure. The data-distribution problem was recognized, and solutions existed.</p><p>LinkedIn’s engineers evaluated these options and built something different anyway. The reason is not obvious from the outside, but it is the key to understanding what Kafka actually is. Scribe and similar systems treated data as something to be <strong>forwarded once</strong>, to a fixed set of destinations, and then it was done. That assumption was exactly the problem: LinkedIn’s teams kept finding that data was never done with. The warehouse wanted it again for a new query. The search indexer wanted to replay it after a bug fix. A team that didn’t exist last year wanted yesterday’s stream without going back to every original producer. The design flaw wasn’t in the delivery mechanism; it was in the underlying model : fire-and-forget, consume-and-delete, one pass and move on.</p><h3>Why the existing tools couldn’t do it</h3><p>The obvious candidates already existed. Message brokers like ActiveMQ and RabbitMQ were mature, standardized, and widely deployed. LinkedIn used them. They broke down here for reasons that are structural, not incidental.</p><p><strong>Queues forget.</strong> A traditional broker treats a message as a unit of work in transit: deliver it, get an acknowledgment, delete it. Consumption is destructive. That’s exactly right for work distribution and exactly wrong for data distribution. If the search indexer and the warehouse both need the same event, a queue gives you awkward choices: duplicate the stream per consumer, or fan out with the broker doing per-consumer bookkeeping. And once a message is consumed, it’s gone. There is no “the indexer had a bug last Tuesday, reprocess the week.” The data passed through and ceased to exist.</p><p><strong>The broker carries the state.</strong> Those brokers track delivery status per message, per consumer: delivered, acknowledged, pending, requeued. That bookkeeping is the broker’s core feature and its scaling ceiling. At thousands of messages per second it’s fine. At millions, with dozens of consumers each at their own position in the stream, the broker spends its capacity remembering who has seen what.</p><p><strong>Databases hold the present, not the past.</strong> A database row is current state. The sequence of changes that produced it is discarded (or buried in a write-ahead log that isn’t yours to read). Consumers that want to react to changes are stuck polling tables and diffing.</p><p>None of these tools were bad. They were each built for a different problem, and data distribution at company scale fell in the gap between them.</p><h3>The log as a concept</h3><p>Before describing what Kafka does, it is worth understanding what a log is, because the idea is older than Kafka and shows up in systems design in a way that makes the whole thing click.</p><blockquote>A log, in the computer science sense, is an append-only, ordered sequence of records. You write to the end; you read from any position forward; you never go back and modify the middle. That’s the whole structure.</blockquote><p>What makes it useful is what falls out of that simplicity. An append-only file preserves history: every state the data has ever been in is still in the sequence. You can replay from any point. You can have multiple readers at different positions without them interfering with each other. The writer just appends; it doesn’t track readers; it doesn’t coordinate delivery.</p><p>This idea keeps appearing across software because it keeps solving the same problem. A PostgreSQL database writes every change to a write-ahead log (WAL) before applying it to the data files. If the database crashes mid-write, it replays the WAL on restart and arrives at the correct state. The log is the ground truth; the database tables are derived views built on top of it. MySQL has its binlog. Oracle has its redo log. Every major database uses some form of write-ahead log for the same reason: an ordered, durable sequence of changes is the simplest way to survive failures and rebuild state.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/619/1*fsjNrvgiqvxmjhuYK6-wLA.png" /><figcaption>Source : <a href="https://www.confluent.io/blog/okay-store-data-apache-kafka/">https://www.confluent.io/blog/okay-store-data-apache-kafka/</a></figcaption></figure><p>Distributed consensus algorithms, such as Raft, use a replicated log as their central data structure. The leader appends entries; followers replay the same entries in the same order. Agreement on the log means agreement on the state of the system. Git stores the history of a codebase as a directed acyclic graph of commits, effectively a log. Which is why you can branch, replay, cherry-pick, and reset to any past state. Event sourcing in application design stores domain events in a log rather than only the current state, for the same reasons.</p><blockquote>The pattern is: when you need durability, recoverability, and multiple independent readers, you reach for a log.</blockquote><p>What LinkedIn did in 2010 was take that idea and make it the primary interface of a distributed messaging system, rather than an implementation detail inside a database. The result was Kafka.</p><h3>The design</h3><p>The Kafka team’s design move was to stop modeling messages in transit and start modeling a log: an append-only file of records, in order, numbered by position. Producers append to the end. The records just sit there, retained by policy (time, size, or forever), whether anyone has read them or not.</p><p>Consumers do the one thing you can do with a log: read forward from a position. And here’s the part that changes everything downstream: <strong>the position belongs to the consumer, not the broker.</strong> Each reader tracks a single number, its offset, marking how far it has gotten. The broker doesn’t know or care who has read what.</p><p>That one decision pays out almost everything Kafka is known for:</p><ul><li><strong>Fan-out becomes free.</strong> Ten consumers are ten offsets into the same shared data. Adding an eleventh costs the broker nothing. The warehouse, the indexer, and a service some team spins up next quarter all read the same log without coordinating.</li><li><strong>Replay becomes a feature instead of an impossibility.</strong> Rewinding is just setting your offset back. The bad-deploy-last-Tuesday scenario goes from data loss to a reprocessing job.</li><li><strong>Consumers decouple in time.</strong> A reader can be real-time, an hour behind, or down for the weekend, and nothing upstream notices. Slow consumers don’t clog the broker with unacknowledged messages; they’re just further back in the file.</li><li><strong>The broker gets simple enough to be fast.</strong> Appending to the end of a file and serving sequential reads is the access pattern disks and operating systems are best at. Kafka leans on sequential I/O and the OS page cache instead of elaborate in-broker data structures. The dumb broker is the fast broker.</li></ul><p>If you want the full version of this worldview, the canonical text is Jay Kreps’ 2013 essay <a href="https://engineering.linkedin.com/distributed-systems/log-what-every-software-engineer-should-know-about-real-time-datas-unifying">“The Log: What every software engineer should know about real-time data’s unifying abstraction”</a>. Kreps was one of Kafka’s creators, and the essay is the closest thing the system has to a design philosophy. This series will keep one of its claims in view the whole way down.</p><p><a href="https://medium.com/@karanpatel2193/down-the-stack-kafka-in-nine-layers-65541826dd65"><em>Down the Stack: Kafka in Nine Layers</em></a><em> · Next: </em><a href="https://medium.com/@karanpatel2193/layer-1-track-page-views-bbac54dc88e9"><em>Layer 1, Track Page Views</em></a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9ad6bf525995" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Down the Stack: Kafka in Nine Layers]]></title>
            <link>https://medium.com/@karanpatel2193/down-the-stack-kafka-in-nine-layers-65541826dd65?source=rss-c591fa7fe717------2</link>
            <guid isPermaLink="false">https://medium.com/p/65541826dd65</guid>
            <category><![CDATA[kafka-streams]]></category>
            <category><![CDATA[apache-kafka]]></category>
            <category><![CDATA[distributed-systems]]></category>
            <category><![CDATA[message-queue]]></category>
            <dc:creator><![CDATA[Karan Patel]]></dc:creator>
            <pubDate>Sat, 20 Jun 2026 19:32:41 GMT</pubDate>
            <atom:updated>2026-06-23T21:52:36.810Z</atom:updated>
            <content:encoded><![CDATA[<p><em>One pipeline, built from scratch and taken to production scale, one layer at a time.</em></p><p>In practice, you build something simple that works. Then traffic grows, teams multiply, and requirements shift. Decisions that were perfectly reasonable in month one start producing symptoms in month twelve. The interesting parts of Kafka live in that gap: what happens to a real system, under real load, when the assumptions behind it expire.</p><p>I spent six years building and operating event-driven systems on Kafka and Kubernetes at a Oracle, the last several as the primary escalation point for production incidents. This series is a write-up about one system. Starting from a simple pub-sub model we go all they way to production incidents and fixes on a distributed scale.</p><h3>What we’re building</h3><p>A product analytics pipeline: the thing behind every “track what users do in your app” dashboard. Events arrive from thousands of clients; we ingest them, sessionize them, enrich them, serve queries on them, and bill customers based on them.</p><p>I picked this domain because everyone already understands it, and because ingestion pipelines escalate naturally: high volume, malformed input from old client versions, late and duplicated events from offline phones, hot keys from viral pages, and state that grows faster than you expect.</p><blockquote>Every Kafka concept in this series shows up because the system needs it.</blockquote><h3>How the series works</h3><p>Each post is one layer. A layer adds a capability, and most layers end with the first symptom of the next layer’s problem.</p><p>A warning before we descend. Some of the choices made in the early layers are reasonable decisions that aged badly: configurations and designs including a few stock Kafka defaults that worked fine…. until they spectacularly backfired. I won’t point them out when they happen. When one fails, we’ll go back and trace why it looked correct, what the failure actually looked like, and what the fix cost.</p><p>Everything presented as firsthand in this series is mine. Where I reference other people’s incidents, they are credited and linked.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JM2ncmGuzOZgcWiu1Tno_g.png" /></figure><h3>The descent</h3><p>(Links will updated when each post goes live)</p><p><a href="https://medium.com/@karanpatel2193/prologue-the-log-or-why-kafka-exists-9ad6bf525995?postPublishedType=repub"><strong>Prologue: The Log, or Why Kafka Exists</strong></a> : The problem Kafka was built for, why message brokers and ETL couldn’t solve it, and why enterprises adopted a system this operationally demanding.</p><p><a href="https://medium.com/@karanpatel2193/layer-1-track-page-views-bbac54dc88e9"><strong>Layer 1: Track Page Views</strong></a> : One topic, one producer, one consumer. The log-versus-queue distinction, made concrete in about twenty lines of code.</p><p><strong>Layer 2: The App Gets Popular</strong> : Partitions, keys, and consumer groups. Scaling reads without breaking per-user ordering, and a sidebar on a workload Kafka is the wrong tool for.</p><p><strong>Layer 3: Clients Send Garbage</strong> : Schemas, Schema Registry, and dead letter queues. The pipeline gets contracts.</p><p><strong>Layer 4: Sessions and State</strong> : Stateful stream processing: state stores, changelogs, session windows, and event time versus processing time.</p><p><strong>Layer 5: The Join That Silently Failed</strong> : Enrichment joins, the co-partitioning requirement, and what it takes to change a topic’s key after the fact.</p><p><strong>Layer 6: The Enum You Can’t Remove</strong> : Avro compatibility modes in practice: who deploys first, why enums resist evolution, and the playbook for migrating a live schema.</p><p><strong>Layer 7: Kafka as the Source of Truth</strong> : The architectural core of the series: using the log as the system of record. Log compaction, interactive queries, serving reads across pods with gRPC, and where this approach honestly stops.</p><p><strong>Layer 8: When You Needed a Stream but Built a Table</strong> : KTable versus KStream: what each abstraction actually promises, why KTable’s record cache makes it eventually consistent, and the production undercount that traced back to using the wrong one.</p><p><strong>Layer 9: Onto Kubernetes, Naively</strong> : Deployments, probes, and the two sections most teams set up after their first incident instead of before: observability and access control.</p><p>That’s the nine layers. But a dev blog feels incomplete without real-world production incidents and high level decisions that don’t really account for technical details. Hence for extra reading I’ll add 2 more layers.</p><p><strong>Production War Stories</strong> : Two incidents in full: the Kafka Streams pods that took five minutes to restart, and the configuration that Kafka silently ignored. Plus a credited tour of other teams’ compound failures.</p><p><strong>“Simply Change the Endpoint”</strong> : Management signs a cloud deal sold on Kafka compatibility. What ports cleanly, what doesn’t and how to build the missing functionalities outside of kafka.</p><h3>The companion repo</h3><p>I’ll provide the full working code for each layer in a github repository. Every layer will further be fully dockerized with all the required applications and utility scripts to re-produce any bugs that I talk about in this series.</p><p>Repo: <a href="https://github.com/Panda0Monium/kafka-layer-by-layer">https://github.com/Panda0Monium/kafka-layer-by-layer</a></p><h3>Who this is for</h3><p>Engineers who know what Kafka is and want to know what it’s like. You don’t need production Kafka experience; Layers 1 through 4 build everything up from first principles. If you’ve already run Kafka in production, the later layers are where this series earns its keep.</p><p><em>Next : </em><a href="https://medium.com/@karanpatel2193/prologue-the-log-or-why-kafka-exists-9ad6bf525995?postPublishedType=repub"><em>Prologue: The Log, or Why Kafka Exists</em></a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=65541826dd65" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>