<?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 Mayukh Datta on Medium]]></title>
        <description><![CDATA[Stories by Mayukh Datta on Medium]]></description>
        <link>https://medium.com/@mayukhdatta?source=rss-169ea66e807e------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*H_wbr3JE9YkuutdaWpjECA.png</url>
            <title>Stories by Mayukh Datta on Medium</title>
            <link>https://medium.com/@mayukhdatta?source=rss-169ea66e807e------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 24 Nov 2026 17:05:24 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@mayukhdatta/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 Deep Dive For System Design Interviews]]></title>
            <link>https://medium.com/@mayukhdatta/kafka-deep-dive-for-system-design-interviews-ef421a90b5b8?source=rss-169ea66e807e------2</link>
            <guid isPermaLink="false">https://medium.com/p/ef421a90b5b8</guid>
            <category><![CDATA[kafka]]></category>
            <category><![CDATA[system-design-interview]]></category>
            <category><![CDATA[distributed-systems]]></category>
            <category><![CDATA[system-design-concepts]]></category>
            <dc:creator><![CDATA[Mayukh Datta]]></dc:creator>
            <pubDate>Wed, 15 Oct 2025 15:26:33 GMT</pubDate>
            <atom:updated>2025-10-15T15:29:02.212Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6jmTGwn8LjSjSLAoRdsLGA.jpeg" /></figure><blockquote>Originally published at <a href="https://thecoducer.com/2025/10/kafka-deep-dive-for-system-design-interviews/">https://thecoducer.com/2025/10/kafka-deep-dive-for-system-design-interviews/</a></blockquote><p>In this deep dive, we’re going to peel back the layers of Kafka and understand it from every angle — what it is, why teams reach for it, when it’s the right tool for the job, and how it actually works under the hood. We’ll take a question-and-answer approach so the concepts click faster and stay with you longer. Think of it as both a guided tour of Kafka and a quick reference you can revisit before your next interview.</p><p>Imagine Kafka as a nationwide postal service, but instead of letters and parcels, it moves streams of data. Producers are the senders, dropping their messages into topic “mailboxes,” which are further divided into neatly ordered trays called partitions. The Kafka cluster acts like a network of post offices, storing, routing, and making sure every message arrives where it should. On the other side, consumers are the recipients, collecting their messages at their own pace. And just like teams of mail sorters working together, consumer groups divide up the workload without ever duplicating deliveries. In essence, Kafka is a highly efficient, fault-tolerant postal system for data in motion.</p><h3>What makes Kafka special?</h3><ul><li><strong>High throughput, low latency</strong> → can handle millions of records/messages per second.</li><li><strong>Durable storage, Replayability</strong> → records persist on disk; consumers can re-read. You can rewind to past events, it retains data for a configurable period.</li><li><strong>Decoupling of systems</strong> → producers and consumers don’t need to know about each other.</li><li><strong>Horizontal scalability</strong> → just add more brokers/partitions.</li></ul><h3>Basic Terminology and Architecture</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NEwwl2qiEFSZ5TZ0xs4fCA.png" /></figure><p>A Kafka cluster is made up of multiple <strong>brokers</strong>. These are just individual servers (they can be physical or virtual). Each broker is responsible for storing data and serving clients. The more brokers you have, the more data you can store and the more clients you can serve.</p><p>Each broker has a number of <strong>partitions</strong>, physical grouping of records. Each partition is an ordered, immutable sequence of records that is continually appended to — think of like a log file. Partitions are the way Kafka scales as they allow for records to be consumed in parallel. Partitions are further divided into smaller blocks called <strong>segments</strong> which store the topic data on the physical disk.</p><p>A <strong>segment</strong> is a physical file on disk that stores a portion of a partition’s data. Each segment consists of a .log file (actual records), .index file (maps offsets to file positions) and .timeindex file (maps timestamps to offsets). Read more about Kafka storage internals <a href="https://rohithsankepally.github.io/Kafka-Storage-Internals/">here</a>.</p><p>A <strong>topic</strong> is just a logical grouping of partitions. Topics are the way you publish and subscribe to data in Kafka. When you publish a record, you publish it to a topic, and when you consume a record, you consume it from a topic. Topics are always multi-producer; that is, a topic can have zero, one, or many producers that write data to it.</p><p>Last up we have our <strong>producers</strong> and <strong>consumers</strong>. Producers are the ones who write data to topics, and consumers are the ones who pull data from topics. While Kafka exposes a simple API for both producers and consumers, the creation and processing of records is on you, the developer. Kafka doesn’t care what the data is, it just stores and serves it.</p><p>From a high-level point of view, there are two layers in the Kafka architecture: <strong>the compute layer</strong> and <strong>the storage layer</strong>. The compute layer, or the processing layer, allows various applications to communicate with Kafka brokers via API. The storage layer is composed of Kafka brokers.</p><p>Since Kafka brokers are deployed in a cluster mode, there are two necessary components to manage the nodes: the control plane and the data plane. <strong>The control plane</strong> manages the metadata of the Kafka cluster. It used to be Zookeeper (maintaining another system overhead gone) that managed the controllers: one broker was picked as the controller. Now Kafka uses a new module called KRaft to implement the control plane. A few brokers are selected to be the controllers. <strong>The data plane</strong> handles the data replication. Followers issue FetchRequest with offsets to the leader broker to get new records.</p><h3>What do you mean by a Kafka Record?</h3><p>A record (formerly messages) is the smallest unit of data in Kafka. It’s what a producer sends, a broker stores, and a consumer reads. At a high level, each record is part of a Record Batch, and that batch is part of a partition log segment.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-YG8MwDwRdo25cMWFCXy9w.png" /><figcaption>Logical structure of a record</figcaption></figure><h3>What is the underlying network protocol used by Kafka?</h3><p>Kafka uses a custom binary protocol over long-lived persistent TCP connections to brokers. That means it sends records in binary format over TCP. Binary encoding makes the record size smaller, less time is spent on processing (serialization/deserialization overhead) and lower bandwidth usage. Connection setup overhead happens once per broker, the connection stays open enabling batched writes and async I/O, resulting in high throughput and low latency.</p><h3>How do we achieve parallelism in Kafka?</h3><p>Kafka’s parallelism comes from partitions, as each topic is divided into partitions that producers write to and consumers read from concurrently. The number of partitions defines your maximum parallelism — too few limits throughput, too many adds metadata overhead. Within a consumer group, each consumer is assigned one or more partitions, and no two consumers share the same partition, preventing duplicate processing. Ideally, the number of consumers should match the number of partitions: fewer consumers reduce parallelism, while extra consumers remain idle. In short, balance your partition count and consumer group size to maximize parallelism without unnecessary overhead.</p><h3>Kafka’s log-centric design</h3><p>Kafka’s storage engine is a <strong>write-ahead</strong> log. Every topic partition is an append-only log file, where records are written sequentially with an offset. This design makes Kafka extremely fast because sequential disk writes are efficient, and it provides durability since records are persisted before acknowledgment. Once written, records cannot be altered. This immutability avoids consistency issues and increases reliability. The WAL also allows <strong>replay — consumers can re-read from any offset</strong>. Logs are segmented, and retention policies decide whether old data is deleted or compacted. This log-centric design is what differentiates Kafka from traditional queues and databases.</p><h3>How is log compaction different from time-based retention?</h3><p>In Kafka, time-based retention deletes records once they’re older than a configured duration or once the log exceeds a certain size. That’s good for event streams where you only care about recent history. Log compaction, on the other hand, guarantees that Kafka keeps at least the latest record for each key, regardless of age. This is ideal when you want Kafka to act as a source of truth for state — for example, keeping the latest user profile or account balance. In short: retention keeps data by time/size, compaction keeps the latest value per key.</p><h3>What do you mean by replication factor?</h3><p>It is the number of copies of each partition that Kafka maintains across different brokers in a cluster.</p><p>Example: If a topic has <strong>3 partitions</strong> and a <strong>replication factor of 3</strong>, then:</p><ul><li>Each partition has 3 <strong>replicas</strong> (leader + followers).</li><li>Kafka stores them on <strong>different brokers</strong> (to survive broker failures).</li><li>Total = 3 partitions × 3 replicas = 9 partition replicas in the cluster.</li></ul><p>If replication factor is 1, then we have only one replica which is our leader by default.</p><h3>When should we use one vs many producers?</h3><p>Number of producers is <em>not limited</em> by the number of topics or partitions.</p><p><strong>One producer → multiple topics</strong></p><ul><li>Simpler, fewer network connections, efficient batching.</li><li>Common pattern when the same app generates different categories of events.</li></ul><p><strong>Multiple producers</strong></p><ul><li>Useful if you want different configs (e.g., different serializers, acks, retries).</li><li>Sometimes chosen for isolation between pipelines.</li></ul><h3>Let’s talk about producer retries and idempotence</h3><p>When a producer sends record to a broker, the send may fail. The producer may retry sending it again.</p><p>This behavior is controlled by the retries (or in newer Kafka versions, delivery.timeout.ms + request.timeout.ms) config.</p><p>Retries can cause duplicates because the producer may not receive an acknowledgment even if the broker already stored the record. We can enable idempotence for the producer via config.</p><p><strong>With idempotence</strong> (enable.idempotence=true):</p><ul><li>Each producer session is assigned a <strong>Producer ID (PID)</strong>.</li><li>Each record carries a <strong>sequence number</strong>.</li><li>Broker deduplicates by rejecting records with the same PID + sequence number → ensuring no duplicates, even if retries occur.</li></ul><h3>You might have heard about “acks”. What are they?</h3><ul><li>It tells the <strong>producer</strong> how many acknowledgments it must receive from the Kafka cluster before considering a message “successfully sent.”</li><li>This controls the balance between <strong>latency, throughput, durability, and consistency.</strong></li><li>This takes care of the <strong>producer-side delivery semantics/guarantees</strong>.</li></ul><p>acks=0 → <em>Fire and Forget</em></p><ul><li>Producer doesn’t wait for any broker acknowledgment.</li><li>Record is sent over the network and considered “delivered.”</li><li>If the broker crashes before persisting, the record is lost.</li><li>At most once.</li><li>✅ Lowest latency, highest throughput.</li><li>❌ No guarantee of durability or delivery.</li><li><strong>Use case</strong>: Logging, metrics, or telemetry where losing data is acceptable.</li></ul><p>acks=1 → <em>Leader Acknowledgment</em></p><ul><li>Producer gets ACK once the leader broker writes the record to its local log (not necessarily replicated yet).</li><li>If the leader crashes <em>after ack but before replicas sync</em>, the record is lost.</li><li>At least once, possible duplicates if retry.</li><li>✅ Reasonable durability with good latency.</li><li>❌ Possible data loss if leader crashes before replication.</li><li><strong>Use case</strong>: Common default for applications where some data loss is tolerable.</li></ul><p>acks=all (or acks=-1) → <em>All In-Sync Replicas Acknowledge</em></p><ul><li>Producer gets ACK only after the leader and all in-sync replicas (ISRs) confirm the write.</li><li>Guarantees that the record won’t be lost as long as ≥1 replica remains alive.</li><li>Stronger at least once guarantee.</li><li>✅ Strongest durability guarantee.</li><li>❌ Higher latency (must wait for multiple brokers).</li><li><strong>Use case</strong>: Financial transactions, orders, payments — where no record loss is acceptable.</li></ul><h3>Why do we need consumer groups?</h3><p>A <strong>consumer group</strong> is a set of consumers that <strong>coordinate together</strong> to read from a topic, such that:</p><ul><li>Each partition of the topic is consumed by <strong>only one consumer</strong> in the group.</li><li>But multiple consumers in the group can work in parallel across partitions.</li></ul><p>If consumers subscribe independently:</p><ul><li><strong>Each consumer gets the full topic</strong> → duplicate processing.</li><li>No parallelism benefit → every consumer does all the work.</li><li>Failover is manual.</li></ul><p>Consumer groups solve this with <strong>partition assignment and rebalancing</strong> while ensuring <strong>no duplicate reads within the group</strong>.</p><h3>What are consumer offsets?</h3><ul><li>Each <strong>partition</strong> in Kafka is an append-only log of records.</li><li>Every record inside a partition has a unique <strong>offset</strong> (0, 1, 2, …).</li><li>A <strong>consumer offset</strong> = the position of the <strong>last record a consumer has processed</strong> in that partition.</li></ul><p>Offsets let consumers:</p><ol><li>Resume after failure (don’t reread from the beginning).</li><li>Track progress per partition (because consumers can read multiple partitions).</li><li>Enable parallelism (each consumer in a group keeps its own bookmarks).</li></ol><h3>How are consumer offsets maintained?</h3><p><strong>Automatically by Kafka (default)</strong></p><ul><li>Consumers commit offsets to an internal Kafka topic: __consumer_offsets.</li><li>Stored as a compacted log keyed by (consumer_group, topic, partition).</li><li>On restart, the consumer group coordinator fetches the last committed offsets from there.</li></ul><p><strong>Manual commit by application</strong></p><ul><li>You can control when offsets are committed (after successful processing).</li><li>APIs:</li><li>commitSync() (synchronous, safe but slower).</li><li>commitAsync() (faster but riskier if crash happens).</li></ul><h3>Let’s also discuss the consumer-side delivery semantics</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*V0ibZQ6N1iB6NHbRzjpEQw.png" /></figure><h3>When do we need idempotent consumers?</h3><p>The default delivery semantic in Kafka is at-least-once where offsets are committed after processing. Now there can be cases when the consumer crashes just after processing but before committing the offset. In such a situation, another consumer can again consume and process the same record. Idempotent consumers can help in such a situation.</p><h3>What are the strategies for building idempotent consumers?</h3><p><strong>Idempotent Writes via Primary Keys</strong></p><ul><li>Store results in a DB where each record has a natural unique key (txn_id, order_id, payment_id).</li><li>Use upserts (insert-or-update) instead of blind inserts.</li></ul><pre>INSERT INTO payments (txn_id, amount, status)<br>VALUES (&#39;abc123&#39;, 100, &#39;FAILED&#39;)<br>ON CONFLICT (txn_id) DO UPDATE<br>    SET status = EXCLUDED.status;</pre><ul><li>If the same record is processed again → no duplicate row.</li></ul><p><strong>Deduplication Log / Cache</strong></p><ul><li>Keep a table (or Redis set) of already-processed record IDs.</li><li>Before processing, check if ID exists.</li><li>If yes → skip. If no → process and record ID.</li><li>Trade-off: needs storage + lookup overhead.</li></ul><h3>How do we achieve Exactly-Once Semantics?</h3><ul><li>Writing messages with transaction IDs (transactional producer at work)</li><li>Atomically processing messages + committing offsets (transactional consumers)</li><li>Ensuring retries don’t cause duplicates (idempotency)</li></ul><p>This provides exactly-once between producer → broker → consumer.</p><h3>How can we handle hot partitions?</h3><p>A hot partition is the one that receives significantly more traffic than the others.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*37MuJXRU1QfC697pi9XAuw.png" /><figcaption>Strategies to avoid them</figcaption></figure><h3>What are the different partitioning strategies?</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NgWoI_1wDr__1UrGRoVmtA.png" /></figure><h3>When message ordering is important?</h3><p>Kafka only guarantees ordering within a single partition, not across partitions. That’s a core rule.</p><p>Let’s say you produce these two events:</p><pre>User123 -&gt; &quot;Account Created&quot;<br>User123 -&gt; &quot;Account Deleted&quot;</pre><p>With round-robin partitioning:</p><pre>“Account Created” → Partition 0<br>“Account Deleted” → Partition 1</pre><p>Consumers reading partitions independently might see: “Deleted” before “Created”. That breaks the logical timeline of events.</p><p>One way of solving this is by using key-based partitioning. We can use the userId as our key so that Kafka’s partitioner send records for the same user id to the same partition every time.</p><pre>partition = hash(&quot;user123&quot;) % num_partitions</pre><h3>What is rebalancing?</h3><p>Rebalancing is the process where Kafka <strong>redistributes partitions among the consumers in a consumer group</strong>.</p><ul><li>A consumer group = multiple consumers working together on the same topic.</li><li>Each partition can only be owned by <strong>one consumer in the group</strong> at a time.</li><li>When the group membership changes (a consumer joins, leaves, or crashes), Kafka <strong>reassigns partitions</strong> → that’s a rebalance.</li></ul><p>It’s like reshuffling tasks among workers when someone joins or leaves the team.</p><h3>When does rebalancing happen?</h3><p>Consumer joins</p><ul><li>A new consumer subscribes to the group → Kafka assigns it some partitions.</li></ul><p>Consumer leaves/crashes</p><ul><li>A consumer shuts down, crashes, or is kicked out due to heartbeat timeout → its partitions are reassigned to remaining consumers.</li></ul><p>Topic partitions change</p><ul><li>Admin increases partitions in a topic → Kafka must redistribute them across consumers.</li></ul><p>Subscription changes</p><ul><li>A consumer subscribes to a new topic or changes its subscription → group must reshuffle assignments.</li></ul><h3>Who manages rebalancing?</h3><ul><li>The <strong>Group Coordinator</strong> (a special broker) orchestrates rebalancing.</li><li>Consumers use the <strong>Group Protocol</strong> (via heartbeats) to agree on who gets which partition.</li></ul><h3>What happens during a rebalance?</h3><ol><li>All consumers in the group stop fetching records.</li><li>The group coordinator pauses consumption and figures out a new partition assignment.</li><li>Each consumer gets its new assignment.</li><li>Consumers resume fetching from their new partitions (using stored offsets).</li></ol><h3>Why is rebalancing both good and bad?</h3><p>✅ <strong>Good</strong>:</p><ul><li>Ensures fault tolerance (if a consumer dies, others pick up its work).</li><li>Allows horizontal scaling (add more consumers → load spreads out).</li></ul><p>❌ <strong>Bad</strong>:</p><ul><li>During a rebalance, no consumer in the group processes records → <em>pause in consumption</em>.</li><li>Frequent rebalances can hurt performance (thrashing).</li></ul><h3>How Kafka mitigates frequent rebalancing</h3><ul><li><strong>Heartbeat &amp; session timeouts</strong>: Avoid kicking consumers out too aggressively.</li><li><strong>Incremental rebalancing (KIP-429)</strong>: Instead of stopping all consumers, only adjust the ones impacted.</li><li><strong>Sticky partition assignment</strong>: Try to keep the same consumer-partition mapping as much as possible, to reduce churn.</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ef421a90b5b8" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[My take on the new revolutionary National Education Policy and my concerns about it]]></title>
            <link>https://medium.com/@mayukhdatta/my-take-on-the-new-revolutionary-national-education-policy-and-my-concerns-about-it-4367ef5686e9?source=rss-169ea66e807e------2</link>
            <guid isPermaLink="false">https://medium.com/p/4367ef5686e9</guid>
            <category><![CDATA[education-reform]]></category>
            <category><![CDATA[policy]]></category>
            <category><![CDATA[national-education-policy]]></category>
            <category><![CDATA[india]]></category>
            <category><![CDATA[education]]></category>
            <dc:creator><![CDATA[Mayukh Datta]]></dc:creator>
            <pubDate>Sat, 08 Aug 2020 07:50:09 GMT</pubDate>
            <atom:updated>2020-08-09T18:20:54.716Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-FC_ChZ5Dw0VRyCjEXxU5Q.jpeg" /></figure><p>India’s education policy got a long awaited update after three decades. The National Education Policy 2020, NEP, has some of the much needed changes, which makes it the third major education policy update since independence. I have wanted such reforms in education for a long time and am happy to welcome this new policy.</p><blockquote>A policy is a plan for action, and its value lies in whether the plans are actionable, and acted upon.</blockquote><h3>The revolutionary changes</h3><p>NEP marks a departure from archaic practices and pedagogy. The 10+2 old system has been replaced by a new 5+3+3+4 academic structure. It covers the age group of 3–6 and it promises to bring 2 crores out of school children back into the mainstream through an open schooling system. The class 10 and 12 board exams are also to be made easier.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/1*cDtVqD-c1zQDfrgfG6qS6w.jpeg" /></figure><p>The policy has made crucial reforms to discourage and curtail rote learning by introducing holistic education. I had a discussion sometime back with one of my college teachers about how teachers and students should take a holistic approach to education. I’m glad that the policy took care of it. Students now will be assessed upon higher-order skills, such as analysis, problem-solving skills, critical thinking, and conceptual clarity. A 360-degree holistic progress card is to be introduced and a new National Assessment Centre, PARAKH (Performance Assessment, Review, and Analysis of Knowledge for Holistic Development), will be set up as a standard-setting body. Quite impressive!</p><p>I know a few of my batchmates who lack these real-life skills. They manage to memorize the textbooks and score well enough in the examinations. But they struggle to explain a certain topic on being asked to, and also finds it hard to learn any new concept. This is how the habit of rote learning affects students. But, is it entirely the fault of the students? I don’t think so. I’ve studied in an engineering college affiliated to MAKAUT, a state university in West Bengal. Our university exam papers have almost 70% of repeated questions. They are designed in such a pattern that a student can score good marks by just memorizing answers to the previous year’s questions. This habit of rote learning makes a disparity between the marks they score and the amount of knowledge they have.</p><h3>It offers a lot of flexibility</h3><p>I had opted for science in school. I chose it because I was genuinely interested in science, space, and physics, and not because my parents asked me to take science so that I can establish a lucrative career ahead. It was in class 11 that interest to study political science built up within me. But since I was not in the arts &amp; humanities stream, I couldn’t study any subject that lies beyond the boundary of my chosen stream. This new education policy has smashed such an odd limitation. Now, the students will have the liberty to study subjects belonging to different domains. I wish we had such flexibility during our school times.</p><p>Read the whole article here: <a href="https://www.thecoducer.com/2020/08/my-take-on-national-education-policy-2020/">https://www.thecoducer.com/2020/08/my-take-on-national-education-policy-2020/</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4367ef5686e9" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>