<?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 abdallah selim on Medium]]></title>
        <description><![CDATA[Stories by abdallah selim on Medium]]></description>
        <link>https://medium.com/@abdallahmselim?source=rss-15717d0b0b9c------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*MWmuFnHAAQ21MRzX</url>
            <title>Stories by abdallah selim on Medium</title>
            <link>https://medium.com/@abdallahmselim?source=rss-15717d0b0b9c------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Wed, 02 Dec 2026 06:22:17 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@abdallahmselim/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[Understanding Kafka: How It Works Behind the Scenes]]></title>
            <link>https://medium.com/@abdallahmselim/understanding-kafka-how-it-works-behind-the-scenes-b7a7f7467272?source=rss-15717d0b0b9c------2</link>
            <guid isPermaLink="false">https://medium.com/p/b7a7f7467272</guid>
            <dc:creator><![CDATA[abdallah selim]]></dc:creator>
            <pubDate>Mon, 13 Oct 2025 19:54:28 GMT</pubDate>
            <atom:updated>2025-10-13T20:05:54.830Z</atom:updated>
            <content:encoded><![CDATA[<h3>Introduction</h3><p>Many of us are familiar with Kafka and its basic functions, but have you ever thought about how it works behind the scenes? For example, how you interact with it, the types of requests you make, and how Kafka manages different kinds of communication.</p><h3>The Binary Protocol</h3><p>Kafka servers communicate with clients using a high-performance binary protocol over TCP.</p><p>In Kafka, every action like sending or getting messages, uses a request and response pattern. The client asks for something, and the broker answers. Each message has a set size, so both sides know where each message begins and ends.</p><h3>Connection Management</h3><p>When a client connects to a broker, it opens a TCP socket and starts sending requests right away. There is no handshake process like in some other protocols. You simply connect, send your requests, and read the responses. Setting up the connection is fast, but it’s more efficient to keep it open for multiple requests. This way, you avoid the extra work of repeating the TCP handshake and keep things running smoothly.</p><p>Kafka makes sure that requests sent over the same connection are handled in the order they arrive, and responses come back in that same order. To do this, the broker only lets one request be active on a connection at any time.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/619/0*B6SOvZ_vhBafjQH3" /></figure><h3>API Versioning and Compatibility</h3><p>Kafka compatibility allows users to upgrade either clients or servers without downtime. So, how is this achieved internally?</p><p>Since the Kafka protocol has changed over time, clients and servers need to agree on the schema of the message that they are sending over the Connection. This is done through API versioning.</p><p>Before each request is sent, the client sends the API key and the API version. These two 16-bit numbers, when taken together, uniquely identify the schema of the message to follow.</p><h3>Tagged Fields</h3><p>Kafka also introduces tagged fields, which are optional fields in a message. If a tagged field is not used, it does not consume any space. This design keeps messages compact and efficient, especially when carrying rarely used data. How does this mechanism work?</p><h3>How Tagged Fields Work</h3><p>Let’s see an example. Kafka request will look like this:</p><pre>[Fixed Fields ...][Tagged Fields Section]</pre><p>And for tagged fields:</p><pre>tag_count][tag_id_1][tag_size_1][tag_data_1]</pre><h3>Example Without Tagged Fields</h3><p>So if I want to represent this request that doesn’t have a tagged field:</p><pre>Request: {<br>  topic: &quot;selimo&quot;      (string)<br>  partition: 1         (int32)<br>}</pre><p>It will look like this as hex:</p><pre>00 06 6F 72 64 65 72 73   00 00 00 01   00<br>----- -----------------   -----------   --<br>1             2              3         4</pre><p>Let’s decode that piece by piece:</p><ul><li>00 06: The first two bytes say the topic name is 6 characters long.</li><li>6F 72 64 65 72 73: This is the word “selimo” in hex.</li><li>00 00 00 01: This is the partition number, 1.</li><li>00: And this last part says there are zero tagged fields. Simple and clean!</li></ul><h3>Example With Tagged Fields</h3><p>Now, what if we add one tagged field? The message would look something like this:</p><pre>00 06 6F 72 64 65 72 73   00 00 00 01   01 01 02 45 55</pre><p>The first parts are the same, but look at the end:</p><ul><li>01: This now says there is one tagged field.</li><li>01 02 45 55: This is the actual tagged field, with its ID, size, and data.</li></ul><p>This design is awesome because it means Kafka can add new optional features without making older clients or servers confused. They just see “zero tagged fields” and ignore the rest.</p><blockquote><strong>I caught you nerd, the one who went to decode “selimo” to see if its hex equivalent “6F 72 64 65 72 73” was correct. That hex actually translates to “orders”, not “selimo”, you nerdy detective 😆</strong></blockquote><p>But how does the client retrieve the supported versions so they can agree on the right schema of messaging?</p><ol><li>Client connects to a broker.</li><li>Client sends an ApiVersionsRequest.</li></ol><ul><li>asks the broker which Kafka APIs and versions it supports.</li></ul><p>3. Broker receives the request and replies with a list of supported API keys and their version ranges.</p><p>4. If the client uses a newer request version than the broker supports:</p><ul><li>Brokers will respond with an UNSUPPORTED_VERSION error.</li><li>The response includes which versions are supported.</li></ul><p>5. Client retries the request using the highest version supported by both sides.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/887/0*QmSqQtYc-NhpSXfo" /></figure><h3>Topic and Partition Discovery</h3><p>After establishing which API versions are supported, clients need to discover topic and partition information. The DescribeTopicPartitions API (API Key 75) serves this crucial role in Kafka’s metadata discovery system.</p><h3>How It Works</h3><ol><li>Clients send a list of topic names they’re interested in</li><li>Broker responds with detailed metadata, including:</li></ol><ul><li>Topic UUIDs (unique identifiers)</li><li>Partition distribution</li><li>Leader brokers for each partition</li><li>Replica and ISR (In-Sync Replica) information</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/881/0*tAi9TQZU-qDTD3Wg" /></figure><h3>Kafka Fetch:</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/452/1*y0Qubc4HqEexIyW36bkvGw.png" /></figure><h3>What is a Fetch Request?</h3><p>A Fetch request is how a consumer (or a replica) asks a Kafka broker for messages from one or more partitions. It’s not just “give me everything” — it’s designed to be smart and efficient.</p><p>Think of it like ordering from a restaurant: you don’t want the kitchen to send you food the moment it’s ready (which might be tiny portions), and you don’t want to wait forever. You want to wait a bit for enough food to be ready, then get it all at once. That’s what Fetch does.</p><h3>The Main Pieces of a Fetch Request</h3><p><strong>MaxWaitMs</strong> — How long the broker will wait (in milliseconds) before sending you data. If new messages arrive faster than this timer, the broker sends them immediately.</p><p><strong>MinBytes</strong> — The minimum amount of data the broker should collect before sending a response. If only 100 bytes are ready but you ask for 1000 bytes minimum, the broker waits for more data to arrive.</p><p><strong>MaxBytes</strong> — The maximum amount of data you’re willing to receive in one response. This prevents the broker from overwhelming you with huge responses.</p><p><strong>IsolationLevel</strong> — Controls which messages you can see. Think of it as asking: “Should I see messages that are still being written as part of a transaction, or only committed ones?”</p><p><strong>SessionID / SessionEpoch</strong> — For advanced Kafka setups, these help with session-based optimizations. When fetching repeatedly, you can reuse a session so you don’t have to send the same request data every time.</p><p><strong>Topics</strong> — The list of topics and partitions you want to read from. For each partition, you specify the offset (the message number) where you want to start reading.</p><p><strong>ForgottenTopicsData</strong> — A way to tell the broker, “I don’t need these topics anymore in my session” so the broker can clean up.</p><p><strong>RackID</strong> — Optional. Tells the broker where you’re located physically, so it can pick which replica to give you data from (replica with lowest latency).</p><h3>What Each Partition Needs</h3><p>For each partition in your request, you send:</p><p><strong>Partition</strong> — The partition number (0, 1, 2, etc.).</p><p><strong>FetchOffset</strong> — The exact message offset you want to start reading from. If you fetched up to message #100, your next FetchOffset is 101.</p><p><strong>CurrentLeaderEpoch</strong> — A number that changes when the partition’s leader changes. It helps detect if leadership switched between requests.</p><p><strong>LastFetchedEpoch</strong> — What you think the epoch was last time you fetched. Used to spot inconsistencies.</p><p><strong>LogStartOffset</strong> — The earliest offset you think exists. If the broker’s earliest offset is higher, it means old messages were deleted and you fell behind.</p><p><strong>PartitionMaxBytes</strong> — A hint to the broker: “Please don’t send more than this many bytes from this specific partition.”</p><h3>How the Server Handles a Fetch Request (Step by Step)</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*8IyK801oXdQSz_ZC" /></figure><ol><li><strong>ReadRequest</strong> — The broker reads the size prefix and header.</li><li><strong>ParseFetchRequest</strong> — Parses all fields and topic arrays.</li><li><strong>BuildFetchResponse</strong> — Constructs the response with offsets, data, and tag buffers.</li><li><strong>WriteResponse</strong> — prepare message size and correlation ID before sending.</li></ol><h3>Step 1: Network Reception (ReadRequest)</h3><p>The broker reads the 4-byte size prefix, then reads exactly that many bytes. It pulls out the header (API key, version, correlation ID) and the client ID, then passes the remaining bytes as the body to the parser.</p><h3>Step 2: Parse the Request (ParseFetchRequest)</h3><p>The parser reads:</p><ul><li>Fixed fields (MaxWaitMs, MinBytes, etc.) using big-endian integers</li><li>The Topics array (compact array format: varint length minus 1 for each element count)</li><li>Each topic’s 16-byte UUID and its partitions</li><li>For each partition: all the INT32/INT64 fields</li><li>Tag buffers at each level (these are for future protocol extensions)</li><li>ForgottenTopicsData</li><li>RackID (as a compact string)</li><li>Final tag buffer</li></ul><h3>Why Error Codes Matter</h3><p>If you request a topic that doesn’t exist or a partition that’s not assigned, the broker sends back error code 100 (UNKNOWN_TOPIC_OR_PARTITION). The client should then:</p><ul><li>Try to discover the topic again</li><li>Or treat it as unavailable for now</li></ul><h3>Smart Consumer Behavior</h3><p><strong>Don’t fetch too often</strong> — Set MinBytes to something reasonable (like 1024 bytes) and MaxWaitMs to a few hundred milliseconds. This lets messages batch up instead of sending tiny responses constantly.</p><p><strong>Detect truncation</strong> — If LogStartOffset &gt; your FetchOffset, it means messages were deleted. You need to seek to the new start.</p><p><strong>Track leadership changes</strong> — If CurrentLeaderEpoch changes between requests, the partition leader switched. You might need to re-fetch or handle inconsistencies.</p><p><strong>Respect limits</strong> — Always obey MaxBytes and PartitionMaxBytes. If you get close to limits, stop adding more messages and come back for more on the next fetch.</p><h3>Kafka Produce:</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/458/0*4p9ay47Z95F8Mxte" /></figure><h3>What is Kafka Produce?</h3><p>Kafka Produce is simple. You have data. You want to send it to Kafka. This is how you do it.</p><p>Think of it like sending a letter. You write your message, put it in an envelope, write the address on it, and send it. Kafka works the same way.</p><h3>The Three Main Things You Need</h3><p>When you send a message to Kafka, you must tell it three things:</p><p><strong>Acks</strong> — This is the most critical configuration for data durability. It tells the broker how many acknowledgments you need before you consider the message successfully sent.</p><ul><li><strong>acks=0</strong>: Very fast, but not safe. You send and go. You don’t wait for any answer. Maybe the message gets lost. Maybe it doesn’t. You don’t know.</li><li><strong>acks=1</strong>: Medium fast and medium safe. You wait for one answer from the main Kafka server. This is the normal choice. It is good balance.</li><li><strong>acks=all</strong>: Very safe, but slow. You wait for all Kafka servers to say “yes, we have it.” Your message never gets lost. But it takes more time.</li></ul><p><strong>2. TimeoutMs — How Long Do You Wait?</strong></p><p>This is simple. You say: “Kafka, you have 5000 milliseconds to answer me. If you don’t answer in 5000 milliseconds, I stop waiting.”</p><p>If Kafka is slow and doesn’t answer in time, your computer tries again.</p><p><strong>3. TopicData — The Message Container</strong></p><p>This is where your message goes. You put your message inside TopicData. You say where it should go.</p><h3>Where Your Message Goes: Topic and Partition</h3><p>You must tell Kafka two things about where your message goes:</p><p><strong>Topic</strong> — The name of the place. Like “orders” or “users” or “payments”. This is like saying “put this in the red box.”</p><p><strong>Partition</strong> — Which part of the topic. Like 0, 1, or 2. This is like saying “put this in the red box, in the top drawer.” ( note : you don’t have to specify the partation you want to save records on , kafka can manage this for you )</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*usLU6Z76fSCaz-jG" /></figure><p>Kafka has many topics. Each topic has many partitions. You choose both. Your message goes to the right place.</p><p>Every message you send to Kafka has two parts. Think of it like a name and a story.</p><ul><li><strong>Value</strong>: This is your data. It is the real message. The story. It can be anything: “Ahmed bought a new phone,” or the number “125.50,” or a long customer file. This is the important stuff you want to save.</li><li><strong>Key</strong>: This is like the name for your message. It is a small piece of text or a number, like “Ahmed” or “Order-456”. The key is very, very important for keeping things in order.</li></ul><p>Why is the key so important, you ask? Because of the partition! Remember the partitions? 0, 1, 2…</p><p>Kafka looks at the key and uses it to choose the partition. All messages with the <strong>same key</strong> will always go to the <strong>same partition</strong>. Always.</p><p><strong>Example, :</strong> Imagine you have messages about orders for different cities: “Cairo”, “Banha”, “Tanta”.</p><ul><li>If you use the city name as the <strong>key</strong>:</li><li>All “Cairo” messages go to Partition 0.</li><li>All “Banha” messages go to Partition 1.</li><li>All “Tanta” messages go to Partition 2.</li></ul><p>Now, all the orders for Cairo are together in one line, in the correct order. It makes reading them later much easier. If you don’t give a key, Kafka just puts the message in any partition it likes. It’s like throwing your letter in a big box without sorting.</p><h3>How the Producer Really Sends the Messages (TopicData)</h3><p>When a Kafka producer sends data, it doesn’t send a message at a time.<br>It sends one <strong>Produce Request</strong>, which can carry many messages for many different topics at once.</p><p>In Kafka’s protocol, this is represented by the <strong>topic_data</strong> array in the request.<br>Each topic_data item contains:</p><ul><li>name → the <strong>topic name</strong>, like “orders” or “users”.</li><li>[partition_data] → the list of partitions in that topic where messages should go.</li></ul><p>Think of it like a big truck (ProduceRequest) leaving your warehouse.<br>Each <strong>box</strong> inside the truck is one topic_data — for example:</p><pre>topic_data:<br>  - name: &quot;cars&quot;<br>    partition_data: [...]<br>  - name: &quot;users&quot;<br>    partition_data: [...]<br>  - name: &quot;payments&quot;<br>    partition_data: [...]:</pre><h3>Inside the Boxes: Batches and Compression</h3><p>Each partition_data section represents a <strong>specific partition</strong> of a topic.<br>It has two important fields:</p><ul><li>index → the <strong>partition number</strong>, like 0, 1, 2.</li><li>records → the actual <strong>batch of messages</strong>, compressed and ready to send.</li></ul><p>So, for “cars”, partition 0 might contain a batch of 100 messages.<br>Kafka doesn’t send them one by one — it groups them together in records.</p><p>This is batching in action:</p><pre>partition_data:<br>  - index: 0<br>    records: &lt;compressed batch of 100 messages&gt;</pre><p>the producer compresses records using gzip or whatever compression you configured.</p><h3>The Truck Leaves: Sending the Request</h3><p>Once all topic boxes are packed, the producer sends <strong>one big Produce Request</strong>.<br>The request also includes a few top-level fields:</p><ul><li>acks → how many acknowledgments it expects (like 1 for leader-only or -1 for full ISR).</li><li>timeout_ms → how long to wait before giving up.</li><li>_tagged_fields → optional metadata for newer protocol versions (Kafka’s “extra info” tag system).</li></ul><p>This is your truck fully loaded and dispatched across the network to the Kafka broker.</p><h3>The Broker’s Side: Unloading and Storing</h3><p>When the Kafka broker receives the truck (the request), it unpacks every topic_data box.<br>Then, for each partition_data, it appends the records to its local .log files for that topic-partition.</p><p>If any partition or topic doesn’t exist, the broker immediately knows and sets an error code for that entry in the response.</p><h3>The Report Card: Produce Response</h3><p>Now the broker prepares your <strong>Produce Response </strong>a detailed report card back to the producer.<br>This is structured similarly to your request:</p><pre>ProduceResponse =&gt;<br>  throttle_time_ms<br>  [responses]<br>  _tagged_fields</pre><p>Each response in [responses] matches one topic you sent in the request.<br>For example:</p><pre>responses:<br>  - name: &quot;cars&quot;<br>    partition_responses:<br>      - index: 0<br>        error_code: 0<br>        base_offset: 542<br>        log_append_time: 1697045234</pre><p>Here’s what these fields mean:</p><ul><li>index → which partition this report line refers to.</li><li>error_code → whether it succeeded (0) or failed (100 = UnknownTopicOrPartition, etc.).</li><li>base_offset → the <strong>offset</strong> assigned to the first message in your batch (the “receipt number”).</li><li>log_append_time → when it was written to the log file.</li><li>_tagged_fields → again, extra data for flexible versions.</li></ul><p>This is the broker’s <strong>report card</strong> — telling you exactly what happened for every box you sent.<br>If one partition failed, you can resend <em>just that partition’s batch</em>, not the whole truck.</p><h3>Conclusion</h3><p>Kafka may seem complex from the outside, but its design is built on simple ideas that work together very efficiently. Every request follows a clear structure that helps the broker and clients communicate quickly and reliably.</p><p>By understanding how these requests are built and processed, we can see why Kafka performs so well, even with huge amounts of data. Its binary format, versioning, and smart way of handling topics and partitions all make it fast and flexible.</p><p>In the end, Kafka’s internal system shows how good design can make a big difference. Knowing how it works under the hood helps developers use it better and appreciate the engineering that keeps it running smoothly every day.</p><h3>References</h3><ul><li><a href="https://kafka.apache.org/documentation/">Apache Kafka</a></li><li><a href="https://www.oreilly.com/library/view/kafka-the-definitive/9781491936153/">Kafka: The Definitive Guide</a></li><li><a href="https://app.codecrafters.io/courses/kafka/overview">The Software Pro&#39;s Best Kept Secret.</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b7a7f7467272" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>