<?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 Arjun Singh on Medium]]></title>
        <description><![CDATA[Stories by Arjun Singh on Medium]]></description>
        <link>https://medium.com/@arjun.devb25?source=rss-f027b3325552------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*mWK_gWW5IZzKq-yCY3aKYg.jpeg</url>
            <title>Stories by Arjun Singh on Medium</title>
            <link>https://medium.com/@arjun.devb25?source=rss-f027b3325552------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 24 Nov 2026 23:23:13 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@arjun.devb25/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[Apache Kafka Internals: A Deep Dive into Brokers, Partitions, Log Segments, and Indexes]]></title>
            <link>https://medium.com/@arjun.devb25/apache-kafka-internals-a-deep-dive-into-brokers-partitions-log-segments-and-indexes-7be0459d21af?source=rss-f027b3325552------2</link>
            <guid isPermaLink="false">https://medium.com/p/7be0459d21af</guid>
            <category><![CDATA[event-driven-architecture]]></category>
            <category><![CDATA[backend-development]]></category>
            <category><![CDATA[apache-kafka]]></category>
            <category><![CDATA[distributed-systems]]></category>
            <category><![CDATA[microservices]]></category>
            <dc:creator><![CDATA[Arjun Singh]]></dc:creator>
            <pubDate>Mon, 23 Nov 2026 19:11:31 GMT</pubDate>
            <atom:updated>2026-11-23T19:11:31.182Z</atom:updated>
            <content:encoded><![CDATA[<p><strong>Understanding How Kafka Stores Millions of Events on Disk and Retrieves Them Efficiently</strong></p><p><em>Topics covered: Kafka Broker Architecture, Partition Storage, Append-Only Logs, Log Segments, Offset Indexes, Timestamp Indexes, Segment Rolling, Retention, and Internal Message Retrieval.</em></p><h3>Introduction: What Actually Happens When Kafka Receives a Message?</h3><p>Apache Kafka is one of the most widely adopted distributed event streaming platforms in modern software architecture.</p><p>Organizations use Kafka to build event-driven microservices, real-time analytics platforms, payment processing systems, order management applications, and large-scale data pipelines.</p><p>We often describe Kafka using a simple flow:</p><p><strong>Producer → Kafka Topic → Consumer</strong></p><p>A producer publishes an event to a Kafka topic, and a consumer subscribes to that topic to process the event.</p><p>But this explanation only describes Kafka from an application’s perspective.</p><p>Have you ever wondered what happens internally when a producer publishes a message?</p><ul><li>Where does Kafka physically store that message?</li><li>Does Kafka maintain one large file for every topic?</li><li>How does Kafka manage millions of messages inside a partition?</li><li>How can Kafka retrieve a message at a particular offset without reading every previous message?</li><li>What exactly are .log, .index, and .timeindex files?</li><li>Why does Kafka divide partition data into multiple segments?</li><li>How does Kafka remove expired data without continuously rewriting enormous files?</li></ul><p>These questions lead us to one of Kafka’s most important architectural concepts: <strong>its internal storage engine</strong>.</p><p>To understand Kafka at a deeper level, we need to explore the following hierarchy:</p><pre>Kafka Cluster<br>    |<br>    |-- Broker 1<br>    |     |<br>    |     |-- Topic A - Partition 0<br>    |     |      |<br>    |     |      |-- Segment 00000000000000000000<br>    |     |      |      |-- .log<br>    |     |      |      |-- .index<br>    |     |      |      |-- .timeindex<br>    |     |      |<br>    |     |      |-- Segment 00000000000000001000<br>    |     |             |-- .log<br>    |     |             |-- .index<br>    |     |             |-- .timeindex<br>    |     |<br>    |     |-- Topic B - Partition 1<br>    |<br>    |-- Broker 2<br>    |<br>    |-- Broker 3</pre><p>Technically, a broker stores <strong>partition replicas</strong>, and the diagram represents a simplified view of their storage.</p><p>Let’s explore each layer and understand how they work together.</p><h3>1. Kafka Broker: The Foundation of Physical Storage</h3><p>A Kafka broker is a server process responsible for storing Kafka records and handling requests from producers, consumers, and other brokers.</p><p>A Kafka cluster usually consists of multiple brokers.</p><p>Consider a cluster containing three brokers:</p><pre>Kafka Cluster<br>                        |<br>         +--------------+--------------+<br>         |              |              |<br>      Broker 1       Broker 2       Broker 3<br>         |              |              |<br>     Partition 0    Partition 1    Partition 2<br>      (Leader)       (Leader)       (Leader)<br>         |              |              |<br>     Partition 2    Partition 0    Partition 1<br>     (Follower)     (Follower)     (Follower)</pre><p>Assume the topic has three partitions and a replication factor of two.</p><p>Each partition has one leader replica and one follower replica.</p><p>The leader is responsible for handling normal producer writes, while the follower replicates records from the leader.</p><h3>What does a broker actually store?</h3><p>A broker does not store an entire topic as one large file.</p><p>Instead, it stores the replicas of partitions assigned to it.</p><p>For example, if we create a topic named order-events with three partitions, Kafka might distribute them across three brokers.</p><p>On a broker hosting Partition 0, the storage directory might contain:</p><pre>/kafka-logs/<br>    |<br>    |-- order-events-0/<br>           |<br>           |-- 00000000000000000000.log<br>           |-- 00000000000000000000.index<br>           |-- 00000000000000000000.timeindex</pre><p>The directory name order-events-0 represents the partition replica for Partition 0 of the order-events topic.</p><p>The files inside that directory are used to store and locate records.</p><p>A broker can manage many such directories, depending on how many partition replicas it hosts.</p><h3>Important broker responsibilities</h3><p>A Kafka broker performs several storage-related operations:</p><ol><li>Accepts records from producers for partitions where it is the leader.</li><li>Appends incoming record batches to the corresponding partition logs.</li><li>Maintains log segments and associated index files.</li><li>Serves fetch requests from consumers.</li><li>Replicates partition records between brokers.</li><li>Applies configured retention and cleanup policies.</li><li>Manages storage recovery after broker restarts.</li></ol><p><strong>Key takeaway:</strong> A Kafka broker is the server responsible for managing partition storage. The actual message data resides in partition log files maintained by that broker.</p><h3>2. Kafka Partitions: The Fundamental Unit of Storage and Ordering</h3><p>A Kafka topic is a logical category used to organize related events.</p><p>For example, an e-commerce application might use these topics:</p><pre>order-events<br>payment-events<br>inventory-events<br>notification-events</pre><p>Each topic can contain one or more partitions.</p><p>Suppose we create a topic:</p><pre>bin/kafka-topics.sh \<br>  --create \<br>  --topic order-events \<br>  --partitions 3 \<br>  --replication-factor 2 \<br>  --bootstrap-server localhost:9092</pre><p>This creates three partitions, with two replicas per partition, assuming sufficient brokers are available.</p><p>Conceptually:</p><pre>Topic: order-events</pre><pre>Partition 0<br>    Offset 0<br>    Offset 1<br>    Offset 2<br>    Offset 3</pre><pre>Partition 1<br>    Offset 0<br>    Offset 1<br>    Offset 2</pre><pre>Partition 2<br>    Offset 0<br>    Offset 1<br>    Offset 2<br>    Offset 3<br>    Offset 4</pre><p>Notice that each partition has its own offset sequence.</p><p>An offset is a logical position assigned to a record within a partition.</p><p>For example:</p><pre>Topic: order-events<br>Partition: 0<br>Offset: 1500</pre><p>This combination identifies a particular record position.</p><p>An offset is not a physical disk address, and it is not a byte position.</p><p>This distinction becomes extremely important when we discuss Kafka’s indexes.</p><h3>2.1 Why Kafka uses partitions</h3><p>Partitions provide three important capabilities.</p><p><strong>Ordering</strong></p><p>Kafka preserves record order within a partition.</p><p>For example, if all events for an order are written to the same partition, consumers can process those events in their partition order.</p><p><strong>Parallelism</strong></p><p>Different partitions can be processed independently, allowing multiple consumers in a consumer group to share the workload.</p><p><strong>Distributed storage</strong></p><p>Partition replicas can be distributed across multiple brokers, allowing Kafka to scale storage and processing capacity.</p><p>However, there is another important question.</p><p>What happens when a partition contains millions or billions of records?</p><p>Does Kafka maintain one continuously growing file?</p><p>No.</p><p>Kafka divides a partition’s log into smaller units called <strong>log segments</strong>.</p><h3>3. Kafka Log Segments: Why a Partition Is Not One Giant File</h3><p>Imagine a payment processing application receiving 100,000 payment events every second.</p><p>Over time, the Kafka partition logs can grow to contain enormous amounts of data.</p><p>If Kafka maintained a single file for an entire partition, operations such as retention cleanup and file management would become difficult.</p><p>Kafka addresses this by dividing each partition log into multiple segments.</p><p>A log segment is a portion of a partition’s append-only log.</p><p>For example:</p><pre>Partition: order-events-0</pre><pre>+----------------------------------+<br>| Segment 1                        |<br>| Base Offset: 0                   |<br>| Records: Offset 0 - 999          |<br>+----------------------------------+</pre><pre>+----------------------------------+<br>| Segment 2                        |<br>| Base Offset: 1000                |<br>| Records: Offset 1000 - 1999      |<br>+----------------------------------+</pre><pre>+----------------------------------+<br>| Segment 3                        |<br>| Base Offset: 2000                |<br>| Records: Offset 2000 - 2999      |<br>+----------------------------------+</pre><p>These boundaries are illustrative.</p><p>In real Kafka, segments are not created after a fixed number of records.</p><p>They are rolled based on configured conditions such as segment size or time.</p><h3>3.1 How Kafka names segments</h3><p>Kafka names segment files using the segment’s base offset.</p><p>The base offset is the starting offset associated with that segment.</p><p>Kafka uses 20-digit, zero-padded filenames.</p><p>For example:</p><pre>00000000000000000000.log<br>00000000000000001000.log<br>00000000000000002000.log</pre><p>Each filename represents the base offset of its segment.</p><p>This naming convention helps Kafka organize segments in offset order.</p><p>Suppose a consumer requests offset 1500.</p><p>Kafka can identify that the relevant segment begins at offset 1000, assuming the next segment begins at 2000.</p><p>This is the first step toward locating the requested record efficiently.</p><h3>3.2 What files exist inside a log segment?</h3><p>A typical segment consists of three primary files.</p><pre>order-events-0/<br>    |<br>    |-- 00000000000000001000.log<br>    |<br>    |-- 00000000000000001000.index<br>    |<br>    |-- 00000000000000001000.timeindex</pre><p>Each file has a different responsibility.</p><p>FileResponsibility.logStores actual Kafka record batches.indexMaps relative offsets to physical positions in the log.timeindexHelps locate offsets associated with timestamps</p><p>Depending on the partition, Kafka may also maintain other files, such as transaction index files and partition metadata.</p><p>The three files above are the main focus of this article.</p><h3>4. The .log File: Where Kafka Stores Actual Messages</h3><p>The .log file contains the actual Kafka records, organized into record batches.</p><p>Suppose an order service publishes the following event:</p><pre>{<br>  &quot;orderId&quot;: &quot;ORD-1001&quot;,<br>  &quot;customerId&quot;: &quot;CUST-501&quot;,<br>  &quot;amount&quot;: 2500,<br>  &quot;status&quot;: &quot;CREATED&quot;<br>}</pre><p>Kafka does not simply save this JSON as a line of text.</p><p>The producer serializes the record, and Kafka stores the resulting bytes using its binary record-batch format.</p><p>A Kafka record can contain:</p><ul><li>Key</li><li>Value</li><li>Timestamp</li><li>Headers</li><li>Offset information</li></ul><p>Multiple records are grouped into record batches.</p><p>Conceptually:</p><pre>00000000000000001000.log</pre><pre>+-----------------------------------+<br>| Record Batch 1                    |<br>|                                   |<br>| Offset 1000                       |<br>| Offset 1001                       |<br>| Offset 1002                       |<br>+-----------------------------------+</pre><pre>+-----------------------------------+<br>| Record Batch 2                    |<br>|                                   |<br>| Offset 1003                       |<br>| Offset 1004                       |<br>| Offset 1005                       |<br>+-----------------------------------+</pre><pre>+-----------------------------------+<br>| Record Batch 3                    |<br>|                                   |<br>| Offset 1006                       |<br>| Offset 1007                       |<br>+-----------------------------------+</pre><p>The actual binary structure also includes batch metadata such as offsets, timestamps, attributes, checksums, and record counts.</p><h3>4.1 Why Kafka uses an append-only log</h3><p>Kafka follows an append-oriented storage model.</p><p>When new records arrive, they are appended to the active segment rather than inserted into arbitrary positions within the existing log.</p><p>For example:</p><pre>Before:</pre><pre>Offset 1000<br>Offset 1001<br>Offset 1002</pre><pre>After new records arrive:</pre><pre>Offset 1000<br>Offset 1001<br>Offset 1002<br>Offset 1003<br>Offset 1004</pre><p>This design provides several advantages.</p><p><strong>Efficient sequential writes</strong></p><p>Appending data sequentially is generally more efficient than performing many random writes.</p><p><strong>Batching</strong></p><p>Kafka can write and transfer multiple records together, reducing per-record overhead.</p><p><strong>Compression</strong></p><p>Records within batches can be compressed, reducing storage requirements and network traffic.</p><p><strong>Operating-system page cache</strong></p><p>Kafka relies heavily on the operating system’s page cache, allowing frequently accessed log data to be served without requiring a physical disk read every time.</p><p>These techniques contribute significantly to Kafka’s high throughput.</p><p>But an append-only log creates another interesting challenge.</p><p>If a consumer requests offset 1500, how does Kafka find it?</p><p>This brings us to the offset index.</p><h3>5. Kafka Offset Index: How Kafka Finds Records Without Scanning the Entire Partition</h3><p>The offset index is one of the most important components of Kafka’s storage architecture.</p><p>Every log segment has an associated .index file.</p><p>The offset index helps Kafka translate a logical record offset into an approximate physical position within the segment’s .log file.</p><p>To understand why this is necessary, consider an example.</p><p>Suppose a partition contains 10 million records.</p><p>A consumer requests:</p><pre>Topic: order-events<br>Partition: 0<br>Offset: 5,000,000</pre><p>Without any indexing mechanism, Kafka might need to scan a very large portion of the log to locate the requested offset.</p><p>That would be inefficient.</p><p>Instead, Kafka first identifies the relevant segment and then uses its offset index.</p><h3>5.1 Logical offset versus physical position</h3><p>These are two different concepts.</p><p><strong>Logical offset</strong></p><p>Identifies a record’s position in a Kafka partition.</p><p>Example:</p><pre>Offset = 1500</pre><p><strong>Physical position</strong></p><p>Represents the byte location inside a .log file where Kafka can begin reading.</p><p>Example:</p><pre>Position = 20480 bytes</pre><p>The offset index connects these concepts.</p><h3>5.2 Understanding the structure of an offset index</h3><p>Suppose we have a segment with base offset 1000.</p><p>Its offset index might conceptually look like this:</p><p>Relative offsetPosition in .log00 bytes1004096 bytes2008192 bytes30012288 bytes40016384 bytes50020480 bytes</p><p>These are hypothetical values used to explain the mechanism.</p><p>Kafka’s real index entries depend on record-batch boundaries and how much data has been appended.</p><p>The index does not contain the actual message payload.</p><p>Instead, it contains information that helps Kafka locate a position in the log.</p><h3>5.3 Why Kafka uses relative offsets</h3><p>Suppose a segment begins at offset 1000.</p><p>A consumer requests offset 1500.</p><p>Kafka calculates:</p><pre>Relative Offset = Requested Offset - Base Offset</pre><pre>Relative Offset = 1500 - 1000</pre><pre>Relative Offset = 500</pre><p>Kafka’s offset index stores relative offsets rather than full absolute offsets.</p><p>This makes the index more compact.</p><p>In Kafka’s traditional offset index format, an entry contains:</p><pre>Relative Offset: 4 bytes<br>Physical Position: 4 bytes</pre><pre>Total: 8 bytes per entry</pre><p>Using compact entries reduces the memory and storage overhead of maintaining indexes.</p><h3>5.4 Why Kafka uses a sparse index</h3><p>An important question is:</p><p>Does Kafka maintain an index entry for every message?</p><p><strong>No. Kafka uses sparse indexing.</strong></p><p>A sparse index stores entries only at selected positions rather than indexing every individual record.</p><p>For example:</p><pre>Actual offsets:</pre><pre>1000<br>1001<br>1002<br>1003<br>...<br>1099<br>1100<br>1101<br>...<br>1199<br>1200</pre><p>The index might contain entries corresponding to:</p><pre>1000<br>1100<br>1200</pre><p>This is only an illustration. Kafka does not index every 100 offsets.</p><p>The spacing of index entries is primarily controlled by the amount of data written.</p><p>For example:</p><pre>log.index.interval.bytes=4096</pre><p>This setting controls the approximate byte interval between index entries.</p><p>Kafka adds index entries at record-batch boundaries when the relevant indexing threshold is reached.</p><h3>Why not index every record?</h3><p>Imagine storing one index entry for every message in a partition containing hundreds of millions of records.</p><p>The index itself could become very large.</p><p>A larger index would require more disk space and could increase memory pressure.</p><p>Sparse indexing provides a practical tradeoff:</p><ul><li>Smaller indexes</li><li>Efficient lookup</li><li>Less indexing overhead</li><li>A limited sequential scan after locating a nearby position</li></ul><p>This design works especially well because Kafka stores records sequentially.</p><h3>6. Step-by-Step: How Kafka Retrieves a Record Using the Offset Index</h3><p>Let’s walk through a complete example.</p><p>Assume Partition 0 contains the following segments:</p><pre>Partition 0</pre><pre>Segment A:<br>Base Offset = 0</pre><pre>Segment B:<br>Base Offset = 1000</pre><pre>Segment C:<br>Base Offset = 2000</pre><p>A consumer requests:</p><pre>Offset = 1575</pre><h3>Step 1: Kafka identifies the correct segment</h3><p>Kafka examines the segment base offsets.</p><p>The requested offset 1575 belongs to the segment beginning at offset 1000.</p><pre>Selected Segment:</pre><pre>00000000000000001000.log<br>00000000000000001000.index</pre><h3>Step 2: Kafka calculates the relative offset</h3><pre>Requested Offset = 1575<br>Segment Base Offset = 1000</pre><pre>Relative Offset = 1575 - 1000</pre><pre>Relative Offset = 575</pre><h3>Step 3: Kafka searches the offset index</h3><p>Suppose the index contains these illustrative entries:</p><pre>Relative Offset    File Position</pre><pre>0                  0<br>100                4096<br>200                8192<br>300                12288<br>400                16384<br>500                20480<br>600                24576</pre><p>Kafka looks for the greatest indexed offset that does not exceed the requested relative offset.</p><p>For relative offset 575, the nearest preceding indexed offset is 500.</p><p>The corresponding physical position is:</p><pre>20480 bytes</pre><h3>Step 4: Kafka reads the .log file</h3><p>Kafka begins reading from the indexed position.</p><p>It then scans forward through the record batches until it reaches the requested offset or the next available relevant records.</p><p>Conceptually:</p><pre>.log File</pre><pre>Position 20480<br>    |<br>    |-- Offset 1500<br>    |-- Offset 1501<br>    |-- Offset 1502<br>    |<br>    |-- ...<br>    |<br>    |-- Offset 1574<br>    |<br>    |-- Offset 1575  &lt;-- Requested</pre><p>The actual scan operates on record batches, not necessarily individual records one at a time.</p><h3>Step 5: Kafka prepares the fetch response</h3><p>After locating the appropriate batch position, the broker can return the relevant record batches to the consumer, subject to fetch limits and visibility rules.</p><p>One subtle but important point is that Kafka’s fetch protocol is batch-oriented. The returned data may begin at a batch boundary, and the consumer handles the records according to the requested offset and its isolation settings.</p><h3>What did Kafka achieve?</h3><p>Kafka avoided scanning the entire partition.</p><p>It narrowed the search in stages:</p><pre>Requested Offset<br>       |<br>       v<br>Find Partition<br>       |<br>       v<br>Find Segment<br>       |<br>       v<br>Search Offset Index<br>       |<br>       v<br>Find Nearby Byte Position<br>       |<br>       v<br>Scan Relevant Record Batches<br>       |<br>       v<br>Return Records</pre><p>This combination of segment lookup, sparse indexing, and sequential scanning is fundamental to Kafka’s efficient read performance.</p><h3>7. Kafka Timestamp Index: How Kafka Locates Records by Time</h3><p>So far, we have explored offset-based retrieval.</p><p>But what if an application wants to begin consuming records from a particular timestamp?</p><p>For example, imagine a payment reconciliation service needs to reprocess events starting from:</p><pre>23 November 2026<br>10:30 AM</pre><p>The application knows the timestamp but does not know the corresponding Kafka offset.</p><p>Kafka supports timestamp-based offset lookup.</p><p>One API that exposes this capability is:</p><pre>consumer.offsetsForTimes(...)</pre><p>Internally, Kafka can use the timestamp index to help find the relevant offset.</p><h3>7.1 What is a timestamp index?</h3><p>Every standard log segment has an associated .timeindex file.</p><p>The timestamp index stores mappings between timestamps and relative offsets.</p><p>Conceptually:</p><p>TimestampRelative offset10:00:00010:10:0010010:20:0020010:30:0030010:40:00400</p><p>These entries are illustrative.</p><p>Kafka’s actual timestamp index is sparse and stores timestamps as millisecond values.</p><p>Unlike the offset index, the timestamp index does not directly map a timestamp to a byte position in the .log file.</p><p>Instead, it maps timestamps to offsets.</p><p>The offset index then helps locate the corresponding physical position.</p><h3>7.2 How timestamp-based lookup works</h3><p>Suppose the application requests:</p><pre>Timestamp = 10:35 AM</pre><p>Kafka conceptually performs these operations:</p><p><strong>Step 1:</strong> Identify a segment that may contain records matching the requested timestamp.</p><p><strong>Step 2:</strong> Search the timestamp index to find a suitable preceding indexed timestamp and associated offset.</p><p><strong>Step 3:</strong> Use the offset index to locate a nearby physical position in the .log file.</p><p><strong>Step 4:</strong> Scan the relevant record batches to find an appropriate offset for the requested timestamp.</p><p>The flow looks like this:</p><pre>Requested Timestamp<br>        |<br>        v<br>Find Relevant Segment<br>        |<br>        v<br>Search .timeindex<br>        |<br>        v<br>Find Candidate Offset<br>        |<br>        v<br>Search .index<br>        |<br>        v<br>Find Physical Log Position<br>        |<br>        v<br>Scan .log<br>        |<br>        v<br>Return Matching Offset</pre><p>Kafka generally returns an offset corresponding to a record with a timestamp greater than or equal to the requested timestamp, when such a record is available.</p><p>The exact behavior depends on Kafka’s timestamp semantics and available records.</p><h3>7.3 CreateTime versus LogAppendTime</h3><p>Kafka supports two important timestamp concepts.</p><p><strong>CreateTime</strong></p><p>The timestamp is associated with record creation, typically supplied by the producer.</p><p><strong>LogAppendTime</strong></p><p>The broker assigns the timestamp when the record is appended.</p><p>The configured timestamp type affects how timestamps are interpreted.</p><p>This is important when building systems that replay events based on time.</p><p>For example, producer-created timestamps may not always arrive in chronological order, even though Kafka preserves append order within the partition.</p><p>Therefore, timestamps and offsets should not be treated as interchangeable.</p><h3>8. Offset Index versus Timestamp Index</h3><p>Both indexes improve Kafka’s ability to locate records, but they solve different problems.</p><p>PropertyOffset IndexTimestamp IndexFile extension.index.timeindexLookup inputOffsetTimestampStored mappingRelative offset to byte positionTimestamp to relative offsetPrimary purposeOffset-based retrievalTime-based offset lookupIndex typeSparseSparseStores message payloadNoNo</p><p>An easy way to remember their responsibilities:</p><p><strong>Offset Index:</strong> Where should Kafka start reading inside the log file?</p><p><strong>Timestamp Index:</strong> Which offset should Kafka examine for a requested time?</p><p>Together, they allow Kafka to efficiently navigate large partition logs.</p><h3>9. Active Segments and Segment Rolling</h3><p>A Kafka partition can contain multiple log segments, but normally only one segment is active for appending new records.</p><p>The active segment is the segment currently receiving new writes.</p><p>Older segments are closed for appending.</p><p>Consider:</p><pre>Partition: order-events-0</pre><pre>Segment 1<br>    Base Offset: 0<br>    Status: Closed</pre><pre>Segment 2<br>    Base Offset: 1000<br>    Status: Closed</pre><pre>Segment 3<br>    Base Offset: 2000<br>    Status: Active</pre><p>New records are appended to Segment 3.</p><p>Eventually, the active segment must be rolled.</p><p>This means Kafka closes it for further appends and creates a new active segment.</p><h3>9.1 What triggers segment rolling?</h3><p>Kafka supports segment rolling based on configurable conditions.</p><p>Two important settings are:</p><pre>log.segment.bytes=1073741824<br>log.roll.hours=168</pre><p>The first setting represents approximately 1 GiB.</p><p>The second represents 168 hours.</p><p>These are example broker-level configurations; topic-level overrides may apply.</p><p>Kafka can roll a segment when an applicable size or time condition is reached.</p><p>It does not require both conditions to become true simultaneously.</p><p>Other internal conditions may also trigger a roll.</p><h3>9.2 Example of segment rolling</h3><p>Suppose the current active segment starts at offset 2000.</p><pre>Before Rolling:</pre><pre>00000000000000002000.log<br>00000000000000002000.index<br>00000000000000002000.timeindex</pre><p>Assume the next offset to append is 3000 and Kafka rolls the segment.</p><p>It creates a new segment:</p><pre>After Rolling:</pre><pre>00000000000000002000.log<br>00000000000000002000.index<br>00000000000000002000.timeindex</pre><pre>00000000000000003000.log<br>00000000000000003000.index<br>00000000000000003000.timeindex</pre><p>The segment beginning at 2000 becomes closed for appends.</p><p>The segment beginning at 3000 becomes active.</p><p>New records are appended to the new segment.</p><h3>9.3 Why segment rolling matters</h3><p>Segment rolling is not merely a file-size management mechanism.</p><p>It is also closely connected to Kafka’s retention behavior.</p><p>Kafka can delete old eligible segments instead of rewriting an entire partition log.</p><p>That is a major operational advantage.</p><h3>10. Kafka Retention: How Segments Help Manage Storage</h3><p>Kafka is designed to retain records according to configured retention policies.</p><p>Unlike traditional message queues where messages may be removed immediately after acknowledgment, Kafka can retain records even after consumers have processed them.</p><p>This makes it possible for applications to replay historical events while the data remains available.</p><p>However, Kafka cannot retain unlimited data without sufficient storage.</p><p>Retention policies control when old data becomes eligible for cleanup.</p><p>Two common policies are time-based retention and size-based retention.</p><h3>10.1 Time-based retention</h3><p>For example:</p><pre>log.retention.hours=168</pre><p>This configures seven days of retention at the broker level, unless overridden.</p><p>For topics using delete-based cleanup, Kafka evaluates old segments for removal according to the configured retention rules.</p><p>Retention is not an exact per-record expiration timer.</p><p>A record may remain beyond the configured retention period because Kafka performs cleanup asynchronously and normally deletes entire eligible segments.</p><h3>10.2 Size-based retention</h3><p>For example:</p><pre>log.retention.bytes=10737418240</pre><p>This configures approximately 10 GiB of retention per partition log.</p><p>When the applicable size threshold is exceeded, Kafka can remove eligible older segments.</p><p>The configured retention size is not a strict instantaneous cap on the partition’s disk usage.</p><h3>10.3 Why Kafka deletes segments instead of individual records</h3><p>Imagine a partition containing:</p><pre>Segment 1 - Old Records<br>Segment 2 - Old Records<br>Segment 3 - Recent Records<br>Segment 4 - Active Records</pre><p>If Segments 1 and 2 become eligible for deletion, Kafka can remove their files.</p><pre>Before Cleanup:</pre><pre>Segment 1<br>Segment 2<br>Segment 3<br>Segment 4</pre><pre>After Cleanup:</pre><pre>Segment 3<br>Segment 4</pre><p>Kafka does not need to rewrite the entire partition to remove those expired segments.</p><p>This makes log management more efficient.</p><p>One important qualification: Kafka also supports log compaction, which uses a different cleanup strategy to retain records based on keys. Segment deletion and compaction should not be confused.</p><h3>11. What Happens When a Consumer Requests an Offset That No Longer Exists?</h3><p>This is an interesting consequence of Kafka’s retention model.</p><p>Suppose a consumer previously processed records up to offset 500.</p><p>The consumer stops for several days.</p><p>During that time, Kafka’s retention cleanup removes old segments.</p><p>The earliest available offset is now 2000.</p><p>When the consumer resumes, it attempts to read from offset 501.</p><p>But that offset is no longer available.</p><p>The consumer’s configured offset-reset behavior becomes important.</p><p>For example:</p><pre>auto.offset.reset=earliest</pre><p>Depending on the consumer’s state and the out-of-range condition, this can cause the consumer to reset to the earliest available offset.</p><p>Alternatively:</p><pre>auto.offset.reset=latest</pre><p>The consumer can reset to the latest position.</p><p>Another option is:</p><pre>auto.offset.reset=none</pre><p>This causes an error when no valid position can be established through the configured reset behavior.</p><p>This illustrates an important relationship:</p><p><strong>Kafka retention policies directly affect how far back consumers can replay events.</strong></p><p>For production systems, retention should be designed with consumer downtime, recovery time, and replay requirements in mind.</p><h3>12. Practical Lab: Explore Kafka Storage Files Yourself</h3><p>Understanding the theory is useful, but examining Kafka’s actual files makes the concepts much clearer.</p><p>Let’s create a topic and inspect its storage layout.</p><p>This experiment assumes you already have a Kafka cluster running locally.</p><h3>Step 1: Create a topic with small segments</h3><pre>bin/kafka-topics.sh \<br>  --create \<br>  --topic kafka-storage-demo \<br>  --partitions 1 \<br>  --replication-factor 1 \<br>  --config segment.bytes=16384 \<br>  --config index.interval.bytes=1024 \<br>  --bootstrap-server localhost:9092</pre><p>We intentionally use a small segment size for demonstration.</p><p>This makes it easier to trigger segment rolling without generating gigabytes of data.</p><h3>Step 2: Publish events</h3><p>Start the Kafka console producer:</p><pre>bin/kafka-console-producer.sh \<br>  --topic kafka-storage-demo \<br>  --bootstrap-server localhost:9092</pre><p>Publish records:</p><pre>Order Created - 1001<br>Order Created - 1002<br>Payment Completed - 1001<br>Inventory Updated - 1001<br>Order Shipped - 1001</pre><p>These few messages will probably not fill a 16 KiB segment.</p><p>To observe rolling, publish enough additional records to exceed the configured segment size.</p><h3>Step 3: Locate the partition directory</h3><p>Find the broker’s configured log.dirs location.</p><p>For example, a local KRaft broker might use:</p><pre>log.dirs=/tmp/kraft-broker-logs</pre><p>Navigate to the partition directory:</p><pre>cd /tmp/kraft-broker-logs/kafka-storage-demo-0</pre><p>List its files:</p><pre>ls -lh</pre><p>You may see files similar to:</p><pre>00000000000000000000.log<br>00000000000000000000.index<br>00000000000000000000.timeindex</pre><pre>leader-epoch-checkpoint<br>partition.metadata</pre><p>The exact file list depends on the Kafka version and partition state.</p><h3>Step 4: Inspect the actual log file</h3><p>Kafka provides a utility called kafka-dump-log.sh.</p><p>Run:</p><pre>bin/kafka-dump-log.sh \<br>  --files /tmp/kraft-broker-logs/kafka-storage-demo-0/00000000000000000000.log</pre><p>This displays information about stored record batches.</p><p>You can also print record data:</p><pre>bin/kafka-dump-log.sh \<br>  --files /tmp/kraft-broker-logs/kafka-storage-demo-0/00000000000000000000.log \<br>  --print-data-log</pre><p>This helps you inspect the offsets, record batches, and associated metadata stored in the segment.</p><h3>Step 5: Inspect the offset index</h3><p>Run:</p><pre>bin/kafka-dump-log.sh \<br>  --files /tmp/kraft-broker-logs/kafka-storage-demo-0/00000000000000000000.index</pre><p>This allows you to inspect index entries.</p><p>Compare the relative offsets and positions with the corresponding log file.</p><h3>Step 6: Inspect the timestamp index</h3><p>Run:</p><pre>bin/kafka-dump-log.sh \<br>  --files /tmp/kraft-broker-logs/kafka-storage-demo-0/00000000000000000000.timeindex</pre><p>This helps you examine timestamp-to-offset index entries.</p><h3>Step 7: Observe segment rolling</h3><p>Continue producing records until Kafka creates another segment.</p><p>Then run:</p><pre>ls -lh /tmp/kraft-broker-logs/kafka-storage-demo-0/</pre><p>You should eventually observe additional groups of segment files.</p><p>For example:</p><pre>00000000000000000000.log<br>00000000000000000000.index<br>00000000000000000000.timeindex</pre><pre>00000000000000000125.log<br>00000000000000000125.index<br>00000000000000000125.timeindex</pre><p>The offset 125 is only an example. Your actual segment base offsets will depend on the records produced and when Kafka rolls the active segment.</p><p>This experiment demonstrates that a single partition is physically represented by multiple segments and their associated indexes.</p><h3>13. Why Kafka’s Storage Architecture Is So Efficient</h3><p>At this point, we can connect the entire architecture.</p><p>Kafka’s performance comes from several complementary design decisions.</p><h3>1. Append-oriented storage</h3><p>Kafka appends new records to the active segment.</p><p>This supports efficient sequential writes.</p><h3>2. Record batching</h3><p>Kafka groups records into batches, reducing overhead and improving compression and I/O efficiency.</p><h3>3. Sparse offset indexing</h3><p>Kafka does not maintain a separate index entry for every record.</p><p>Instead, it uses a compact index to locate a nearby log position and scans forward.</p><h3>4. Segment-based storage</h3><p>Large partition logs are divided into manageable files.</p><p>This simplifies rolling, retention, and recovery operations.</p><h3>5. Timestamp indexing</h3><p>Kafka can efficiently narrow timestamp-based offset searches without scanning the entire partition from the beginning.</p><h3>6. Operating-system page cache</h3><p>Kafka benefits from the operating system’s caching mechanisms, which can reduce physical disk reads for frequently accessed data.</p><h3>7. Distributed partitioning</h3><p>Partition replicas can be distributed across brokers, allowing Kafka to scale storage and processing workloads horizontally.</p><p>Together, these mechanisms allow Kafka to handle large event streams while maintaining efficient storage and retrieval.</p><h3>14. Common Misconceptions About Kafka Storage</h3><p>Before concluding, let’s clarify some frequently misunderstood concepts.</p><h3>Misconception 1: A Kafka topic is stored in one file</h3><p>Incorrect.</p><p>A topic consists of partitions, and partition replicas are stored as sequences of log segments.</p><h3>Misconception 2: Every Kafka message has its own index entry</h3><p>Incorrect.</p><p>Kafka uses sparse indexes, and index entries are associated with positions of record batches.</p><h3>Misconception 3: Kafka’s offset is the physical byte position of a message</h3><p>Incorrect.</p><p>An offset is a logical position within a partition.</p><p>The offset index helps translate that logical position into a nearby physical position in a log file.</p><h3>Misconception 4: Kafka loads all partition records into memory</h3><p>Incorrect.</p><p>Kafka stores records on disk and relies heavily on the operating system’s page cache and efficient I/O mechanisms.</p><h3>Misconception 5: The timestamp index directly points to the message bytes</h3><p>Incorrect.</p><p>The timestamp index maps timestamps to relative offsets.</p><p>The offset index helps locate corresponding positions in the log.</p><h3>Misconception 6: Kafka deletes a record immediately when its retention period expires</h3><p>Incorrect.</p><p>Under delete-based retention, Kafka generally removes eligible segments asynchronously rather than deleting individual records immediately.</p><h3>15. System Design Perspective: Why Backend Engineers Should Understand Kafka Internals</h3><p>Let’s consider a real-world scenario.</p><p>You are designing an order processing platform where millions of order events are published daily.</p><p>Your Kafka topic receives events such as:</p><pre>OrderCreated<br>PaymentInitiated<br>PaymentCompleted<br>InventoryReserved<br>OrderShipped<br>OrderDelivered</pre><p>Over time, the topic accumulates a large volume of data.</p><p>Now imagine a consumer service crashes and remains unavailable for several hours.</p><p>When it restarts, it needs to continue processing from its previously committed offset.</p><p>Kafka does not need to read every event from the beginning of the partition.</p><p>The broker can identify the relevant segment, use its sparse offset index to locate a nearby physical position, and retrieve the appropriate record batches.</p><p>Similarly, if a reconciliation service needs to replay records starting from a particular timestamp, Kafka’s timestamp index can help locate the relevant offset.</p><p>And when records become eligible for deletion, Kafka can remove old segments according to the configured retention policy.</p><p>This is why understanding storage internals matters when designing production systems.</p><p>It helps engineers reason about:</p><ul><li>Consumer recovery and event replay</li><li>Retention configuration</li><li>Disk utilization</li><li>Fetch performance</li><li>Partition sizing</li><li>Storage troubleshooting</li><li>Operational behavior during high-throughput workloads</li></ul><p>It also helps explain why increasing partition counts, changing retention settings, or configuring very small segments can affect broker performance.</p><p>These decisions should be based on workload requirements rather than arbitrary defaults.</p><h3>16. Interview Questions to Test Your Understanding</h3><p>If you are preparing for SDE-2, Senior Backend Developer, or System Design interviews, these are useful questions to practice.</p><p><strong>Q1. What is the relationship between a Kafka broker, partition, and segment?</strong></p><p>A broker stores partition replicas. Each partition replica is maintained as an ordered log divided into segments. Each segment has a log file and associated index files.</p><p><strong>Q2. Why does Kafka use log segments instead of one large file?</strong></p><p>Segments make it easier to manage large partition logs, roll active files, apply retention policies, and recover storage state.</p><p><strong>Q3. What is the purpose of the </strong><strong>.index file?</strong></p><p>It maps relative offsets to physical positions in the segment’s .log file, allowing Kafka to efficiently locate a nearby position for an offset-based read.</p><p><strong>Q4. Why does Kafka use sparse indexing?</strong></p><p>Sparse indexing reduces storage and memory overhead while still enabling efficient lookups through a combination of indexed positions and sequential scanning.</p><p><strong>Q5. What is the difference between </strong><strong>.index and </strong><strong>.timeindex?</strong></p><p>The offset index maps relative offsets to byte positions, while the timestamp index maps timestamps to relative offsets.</p><p><strong>Q6. What happens when an active segment becomes full?</strong></p><p>Kafka rolls the segment, closes the previous segment for appending, and creates a new active segment.</p><p><strong>Q7. How does Kafka delete expired records?</strong></p><p>For topics using delete-based retention, Kafka generally removes eligible old segments rather than deleting individual records one by one.</p><p><strong>Q8. Can a consumer request an offset that has already been deleted?</strong></p><p>Yes. If the requested offset is no longer available, the consumer may need to reset its position according to its configuration or handle an error.</p><h3>Conclusion: Understanding the Storage Engine Behind Kafka</h3><p>Kafka is much more than a system that receives events from producers and delivers them to consumers.</p><p>Behind that simple interface is a carefully designed storage architecture.</p><p>Let’s summarize the complete hierarchy:</p><pre>Kafka Cluster<br>      |<br>      v<br>Kafka Broker<br>      |<br>      v<br>Topic Partition Replica<br>      |<br>      v<br>Log Segments<br>      |<br>      +-----------------------------+<br>      |              |              |<br>      v              v              v<br>   .log File     .index File    .timeindex File<br>      |              |              |<br>      v              v              v<br>   Actual         Offset to      Timestamp to<br>   Record         Physical       Relative<br>   Batches        Position       Offset</pre><p>Each component solves a specific problem.</p><p><strong>Brokers</strong> manage partition storage and requests.</p><p><strong>Partitions</strong> provide ordered logs, distribution, and parallel processing.</p><p><strong>Log segments</strong> divide partition data into manageable storage units.</p><p><strong>Log files</strong> contain the actual record batches.</p><p><strong>Offset indexes</strong> help Kafka locate records efficiently by offset.</p><p><strong>Timestamp indexes</strong> help Kafka find offsets associated with a requested time.</p><p>The key insight is that Kafka does not rely on indexing every message or loading the entire log into memory.</p><p>Instead, Kafka combines append-only storage, record batching, sparse indexing, segment-based file management, and operating-system caching to achieve efficient reads and writes at scale.</p><p><strong>The next time you publish an event to Kafka, remember that the event does not simply disappear into a topic. It becomes part of an ordered partition log, stored within a segment, and made efficiently accessible through Kafka’s indexing mechanisms.</strong></p><p>Understanding this internal architecture is an important step toward moving beyond Kafka API usage and developing a deeper understanding of distributed event streaming systems.</p><h3>References and Further Reading</h3><ol><li><a href="https://kafka.apache.org/documentation/">Apache Kafka Official Documentation</a></li><li><a href="https://github.com/apache/kafka">Apache Kafka Source Code — GitHub</a></li><li><a href="https://kafka.apache.org/42/implementation.html">Apache Kafka Implementation Details</a></li><li><a href="https://kafka.apache.org/42/javadoc/org/apache/kafka/clients/consumer/KafkaConsumer.html">Kafka Consumer API Documentation</a></li></ol><p><em>If you found this article useful, consider sharing it with developers who want to understand what happens behind the scenes when Kafka stores and retrieves events.</em></p><p><strong>#ApacheKafka #KafkaInternals #EventDrivenArchitecture #DistributedSystems #BackendDevelopment #SystemDesign #Microservices #SoftwareEngineering #Java #Golang</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7be0459d21af" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Apache Kafka Internals: Understanding Producers, Topics, Partitions, Offsets, Log Segments, and…]]></title>
            <link>https://medium.com/@arjun.devb25/apache-kafka-internals-understanding-producers-topics-partitions-offsets-log-segments-and-4a795c59f7ef?source=rss-f027b3325552------2</link>
            <guid isPermaLink="false">https://medium.com/p/4a795c59f7ef</guid>
            <category><![CDATA[event-driven-architecture]]></category>
            <category><![CDATA[apache-kafka]]></category>
            <category><![CDATA[system-design-interview]]></category>
            <category><![CDATA[distributed-systems]]></category>
            <category><![CDATA[microservices]]></category>
            <dc:creator><![CDATA[Arjun Singh]]></dc:creator>
            <pubDate>Sun, 22 Nov 2026 13:57:13 GMT</pubDate>
            <atom:updated>2026-11-22T13:57:13.071Z</atom:updated>
            <content:encoded><![CDATA[<h3>Apache Kafka Internals: Understanding Producers, Topics, Partitions, Offsets, Log Segments, and Partitioning Strategies</h3><p><em>From distributed event streaming fundamentals to how Kafka organizes and retrieves millions of events efficiently.</em></p><h3>Introduction</h3><p>In the previous articles of our Event-Driven Architecture (EDA) series, we explored the fundamentals of asynchronous communication, including:</p><ul><li>Publish/Subscribe (Pub/Sub) Model</li><li>Event Streaming Model</li><li>Advantages of Event-Driven Architecture</li></ul><p>We learned how event-driven systems allow applications to communicate asynchronously without requiring every service to know about its downstream consumers.</p><p>But understanding EDA is only the beginning.</p><p>The next important question is:</p><p><strong>How do we implement event-driven communication reliably when our applications generate thousands or even millions of events?</strong></p><p>This is where Apache Kafka comes into the picture.</p><p>Kafka is one of the most widely adopted distributed event streaming platforms. It provides a scalable and fault-tolerant infrastructure for publishing, storing, and processing continuous streams of events.</p><p>In this article, we’ll go beyond Kafka’s basic definition and explore how its internal components work together.</p><p>By the end, you’ll understand:</p><ol><li>What Apache Kafka is and why it exists.</li><li>How producers publish events.</li><li>How topics organize events.</li><li>How partitions store and order records.</li><li>How Kafka manages offsets.</li><li>How partition logs are divided into segments.</li><li>How Kafka uses index files for efficient record lookup.</li><li>How producers determine which partition receives an event.</li><li>Which partitioning strategy to choose for different business requirements.</li></ol><p>Let’s begin with the fundamentals.</p><h3>1. What Is Apache Kafka?</h3><p><strong>Apache Kafka is a distributed event streaming platform designed to publish, store, and process streams of events reliably and at scale.</strong></p><p>Unlike traditional messaging systems that primarily focus on delivering messages between applications, Kafka also provides persistent event storage and the ability to replay retained events.</p><p>Kafka supports three fundamental capabilities:</p><p><strong>1. Publish events</strong></p><p>Applications can produce events representing business activities, system changes, or operational information.</p><p>Examples include:</p><ul><li>OrderCreated</li><li>PaymentCompleted</li><li>InventoryUpdated</li><li>UserRegistered</li></ul><p><strong>2. Store events</strong></p><p>Kafka stores events in distributed, replicated, append-only partition logs.</p><p>Events can remain available even after consumers have processed them, depending on the topic’s retention configuration.</p><p><strong>3. Subscribe to and process events</strong></p><p>Applications can consume events independently and process them according to their business requirements.</p><p>Consumers can also reread retained events when necessary.</p><h3>Real-world example: E-commerce order processing</h3><p>Imagine building an e-commerce platform with the following microservices:</p><ul><li>Order Service</li><li>Payment Service</li><li>Inventory Service</li><li>Notification Service</li><li>Analytics Service</li></ul><p>When a customer places an order, the Order Service generates an OrderCreated event.</p><p>Instead of directly invoking every downstream service through REST APIs, it publishes the event to Kafka.</p><p>The interested services can consume that event independently.</p><pre>                   Order Service<br>                        |<br>                        | OrderCreated<br>                        v<br>                Apache Kafka<br>                  order-events<br>                        |<br>             +----------+----------+<br>             |          |          |<br>             v          v          v<br>         Inventory  Analytics  Notification<br>          Service    Service      Service</pre><p>This architecture reduces direct coupling between services and allows each consumer to process events independently.</p><p><strong>The key idea is that the producer publishes a business fact without needing to know which applications will consume it.</strong></p><h3>2. Kafka Producer: Where Events Originate</h3><p>A <strong>Kafka Producer is an application component responsible for publishing records to Kafka topics</strong>.</p><p>It can be implemented using Java, Go, Python, Node.js, or any other language supported by a compatible Kafka client.</p><p>Consider an Order Service that publishes an event after an order has been successfully created.</p><p>A conceptual producer record looks like this:</p><pre>{<br>  &quot;topic&quot;: &quot;order-events&quot;,<br>  &quot;key&quot;: &quot;order-123&quot;,<br>  &quot;value&quot;: {<br>    &quot;eventId&quot;: &quot;evt-1001&quot;,<br>    &quot;eventType&quot;: &quot;OrderCreated&quot;,<br>    &quot;orderId&quot;: &quot;order-123&quot;,<br>    &quot;customerId&quot;: &quot;customer-501&quot;,<br>    &quot;amount&quot;: 2500,<br>    &quot;currency&quot;: &quot;INR&quot;<br>  }<br>}</pre><p>Let’s understand its three important components.</p><h3>Topic</h3><p>The topic identifies the logical destination where the record should be published.</p><p>In our example:</p><p>order-events</p><h3>Key</h3><p>The key can be used to determine which partition receives the record.</p><p>Here:</p><p>order-123</p><p>Using the same key for all events associated with an order helps preserve their order within the selected partition.</p><h3>Value</h3><p>The value contains the actual business information.</p><p>For example:</p><pre>{<br>  &quot;eventType&quot;: &quot;OrderCreated&quot;,<br>  &quot;orderId&quot;: &quot;order-123&quot;,<br>  &quot;amount&quot;: 2500<br>}</pre><p>This is the information downstream services use to perform their operations.</p><p>The producer serializes the key and value into bytes before sending the record to Kafka.</p><h3>Does the producer know who consumes the event?</h3><p>No.</p><p>The producer doesn’t need to know whether the event will be consumed by one service, ten services, or no services at all.</p><p>Its responsibility is to publish the event successfully to the appropriate Kafka topic.</p><p>This separation is one of the primary benefits of event-driven architecture.</p><h3>3. Kafka Topics: Logical Organization of Events</h3><p>A <strong>Kafka topic is a logical category or named stream into which producers publish records</strong>.</p><p>You can think of a topic as a category or folder, but this is only a conceptual analogy.</p><p>A Kafka topic is not a single physical folder containing one large event file.</p><p>Instead, a topic is divided into partitions, which are distributed across Kafka brokers.</p><h3>Example</h3><p>Suppose our application has three topics:</p><pre>Kafka Cluster<br>|<br>|-- order-events<br>|<br>|-- payment-events<br>|<br>|-- inventory-events</pre><p>Each topic represents a particular category of events.</p><p>The Order Service publishes order-related events to order-events.</p><p>The Payment Service publishes payment-related events to payment-events.</p><h3>Can multiple producers publish to the same topic?</h3><p>Absolutely.</p><p>For example, suppose an e-commerce company operates across multiple regions.</p><pre>Order Service - India ----+<br>                          |<br>Order Service - US -------+----&gt; order-events<br>                          |<br>Order Service - Europe ---+</pre><p>All three producers can publish to the same topic.</p><p>Kafka organizes these records into the topic’s partitions.</p><p><strong>Important:</strong> A topic is a logical abstraction. The actual records are stored within its partitions.</p><h3>4. Kafka Partitions: The Foundation of Scalability</h3><p>A <strong>partition is an ordered, append-only log that forms part of a Kafka topic</strong>.</p><p>This is one of the most important concepts in Kafka architecture.</p><p>Why?</p><p>Because partitions enable Kafka to distribute storage and processing across multiple brokers and consumers.</p><p>Let’s assume we create a topic called order-events with three partitions.</p><pre>Topic: order-events</pre><pre>+-------------------------+<br>| Partition 0             |<br>+-------------------------+</pre><pre>+-------------------------+<br>| Partition 1             |<br>+-------------------------+</pre><pre>+-------------------------+<br>| Partition 2             |<br>+-------------------------+</pre><p>Each partition maintains its own sequence of records.</p><p>A producer can publish records to any eligible partition according to its partitioning strategy.</p><h3>Three fundamental properties of partitions</h3><p>Kafka partitions are:</p><ol><li>Physically stored</li><li>Ordered</li><li>Append-only</li></ol><p>Let’s understand each property in depth.</p><h3>5. Physical Storage: Where Does Kafka Store Events?</h3><p>When we say a partition is physically stored, we mean that Kafka persists its records in log files on broker storage.</p><p>Consider:</p><pre>Topic: order-events</pre><pre>Partition 0: order-events-0<br>Partition 1: order-events-1<br>Partition 2: order-events-2</pre><p>These names represent the logical partition directories used in Kafka’s local storage layout.</p><p>A simplified representation might look like:</p><pre>Kafka Broker Storage<br>|<br>|-- order-events-0/<br>|     |-- 00000000000000000000.log<br>|     |-- 00000000000000000000.index<br>|<br>|-- order-events-1/<br>|     |-- 00000000000000000000.log<br>|     |-- 00000000000000000000.index<br>|<br>|-- order-events-2/<br>      |-- 00000000000000000000.log<br>      |-- 00000000000000000000.index</pre><p>In an actual distributed cluster, these partition replicas may be located on different brokers.</p><p>A broker stores the replicas assigned to it, not necessarily every partition in the cluster.</p><p>Kafka’s log files contain serialized record batches in a binary format, rather than plain JSON lines.</p><h3>Why does physical storage matter?</h3><p>Because Kafka is not simply forwarding messages from one application to another.</p><p>It persists records so that consumers can read them later.</p><p>For example, if an Analytics Service is temporarily unavailable, retained events can remain in Kafka.</p><p>When the service recovers, it can resume consuming from its recorded position, provided those events are still retained.</p><p>This makes Kafka particularly useful for asynchronous processing and recovery.</p><h3>6. Ordered Logs: How Kafka Maintains Event Order</h3><p>Every Kafka partition maintains an ordered sequence of records.</p><p>Each record is assigned an <strong>offset</strong>, which identifies its position within that partition.</p><p>Consider the following example:</p><pre>Topic: order-events</pre><pre>Partition 0<br>+----------+----------+<br>| Offset 0 | Offset 1 |<br>| Event E0 | Event E3 |<br>+----------+----------+</pre><pre>Partition 1<br>+----------+----------+<br>| Offset 0 | Offset 1 |<br>| Event E1 | Event E4 |<br>+----------+----------+</pre><pre>Partition 2<br>+----------+<br>| Offset 0 |<br>| Event E2 |<br>+----------+</pre><p>Notice that each partition has its own offsets.</p><p>Partition 0 contains:</p><p>E0 → E3</p><p>Partition 1 contains:</p><p>E1 → E4</p><p>Partition 2 contains:</p><p>E2</p><h3>What happens when a new event arrives?</h3><p>Suppose a producer publishes another event, E5, to Partition 2.</p><p>Kafka appends it after the existing record.</p><pre>Partition 2</pre><pre>+----------+----------+<br>| Offset 0 | Offset 1 |<br>| Event E2 | Event E5 |<br>+----------+----------+</pre><p>The existing record is not overwritten.</p><p>Instead, the new record is appended to the partition log.</p><p>This is the foundation of Kafka’s append-only storage model.</p><h3>Does Kafka guarantee event ordering?</h3><p>Yes, but there is an important limitation.</p><p><strong>Kafka maintains record ordering within an individual partition, not globally across every partition of a topic.</strong></p><p>For example:</p><p>Within Partition 0, E0 appears before E3.</p><p>Within Partition 1, E1 appears before E4.</p><p>However, the offsets alone cannot establish whether E4 occurred before or after E0, because they belong to different partitions.</p><p>There is no single global offset sequence spanning the entire topic.</p><p>This distinction becomes extremely important when designing financial, inventory, or order-processing systems.</p><h3>Production example</h3><p>Suppose an order generates three events:</p><pre>OrderCreated<br>OrderPaid<br>OrderShipped</pre><p>If all three records use the same orderId as their key and the key-to-partition mapping remains stable, they can be routed to the same partition.</p><p>This allows consumers to process them in partition-log order.</p><p>However, application-level concurrency, retries, and multiple producers can still affect the intended business sequence. Kafka’s ordering guarantee concerns the order of records appended to a partition.</p><h3>7. Append-Only Logs: Why Kafka Doesn’t Insert Events in the Middle</h3><p>Traditional databases allow applications to update or delete existing rows.</p><p>Kafka’s partition logs work differently.</p><p>New records are appended to the end of the active log.</p><p>Consider:</p><pre>Partition 0</pre><pre>Offset 0 -&gt; OrderCreated<br>Offset 1 -&gt; OrderPaid<br>Offset 2 -&gt; OrderShipped</pre><p>Now suppose the order is cancelled.</p><p>Kafka doesn’t modify the original OrderCreated record.</p><p>Instead, the application publishes a new event:</p><pre>Partition 0</pre><pre>Offset 0 -&gt; OrderCreated<br>Offset 1 -&gt; OrderPaid<br>Offset 2 -&gt; OrderShipped<br>Offset 3 -&gt; OrderCancelled</pre><p>This provides a historical sequence of recorded events.</p><p>However, Kafka does not guarantee that every historical record remains available forever.</p><p>Records may be removed according to retention policies or affected by log compaction.</p><p><strong>Append-only describes how records are written; it does not mean records are permanently retained.</strong></p><h3>8. Going One Level Deeper: Kafka Log Segments</h3><p>Now let’s explore something that happens internally.</p><p>Imagine a partition receives millions of events every day.</p><p>If Kafka stored all records in one continuously growing file, that file could become extremely large.</p><p>Managing retention, recovery, and storage would become more difficult.</p><p>Kafka addresses this by dividing each partition log into smaller units called <strong>log segments</strong>.</p><h3>What is a log segment?</h3><p>A log segment is a portion of a partition’s log stored in a separate set of files.</p><p>For example:</p><pre>Topic: order-events<br>Partition: 0</pre><pre>order-events-0/<br>|<br>|-- 00000000000000000000.log<br>|-- 00000000000000000000.index<br>|<br>|-- 00000000000000000500.log<br>|-- 00000000000000000500.index<br>|<br>|-- 00000000000000001000.log<br>|-- 00000000000000001000.index</pre><p>The filenames represent the base offsets of their corresponding segments.</p><p>For illustration, suppose:</p><ul><li>Segment 1 contains offsets 0–499.</li><li>Segment 2 contains offsets 500–999.</li><li>Segment 3 begins at offset 1000.</li></ul><p>These ranges are examples, not fixed Kafka rules.</p><p>Kafka rolls segments based on configured size, time, and other internal conditions. A segment’s actual offset range depends on the records written to it.</p><h3>Why divide a partition log into segments?</h3><p>There are several benefits.</p><p><strong>1. Efficient storage management</strong></p><p>Kafka can manage smaller segment files instead of one indefinitely growing file.</p><p><strong>2. Retention management</strong></p><p>Old eligible segments can be deleted according to retention policies.</p><p><strong>3. Faster recovery and maintenance</strong></p><p>Segment boundaries and indexes help Kafka manage and locate stored records.</p><p><strong>4. Efficient record lookup</strong></p><p>Kafka can identify the segment containing a requested offset without scanning the entire partition history.</p><p>Let’s understand this last point.</p><h3>9. How Kafka Finds a Record Using Its Offset</h3><p>Suppose a consumer requests records from:</p><pre>Topic: order-events<br>Partition: 0<br>Starting offset: 550</pre><p>Kafka must locate the record corresponding to offset 550.</p><p>Assume the partition contains these segments:</p><pre>Segment A<br>Base Offset: 0</pre><pre>Segment B<br>Base Offset: 500</pre><pre>Segment C<br>Base Offset: 1000</pre><p>Kafka can identify that offset 550 belongs to Segment B, based on segment metadata and the available offset ranges.</p><p>It doesn’t need to begin reading from offset 0.</p><p>But there’s another challenge.</p><p>Even if Kafka identifies the correct segment, that segment may contain hundreds of megabytes of records.</p><p>How does it locate the requested offset efficiently inside the segment?</p><p>This is where <strong>offset index files</strong> become important.</p><h3>10. Kafka Offset Index Files: Efficient Lookup Inside a Segment</h3><p>Each log segment maintains an offset index that maps selected offsets to physical positions in its log file.</p><p>A simplified example:</p><pre>00000000000000000500.log</pre><pre>Offset 500 -&gt; Record batch<br>Offset 501 -&gt; Record batch<br>Offset 502 -&gt; Record batch<br>...<br>Offset 800 -&gt; Record batch</pre><p>Associated index:</p><pre>00000000000000000500.index</pre><pre>Relative Offset | File Position<br>----------------|--------------<br>0               | 0<br>150             | 4200<br>300             | 8900<br>450             | 13200</pre><p>The actual index uses relative offsets from the segment’s base offset and physical positions measured in bytes.</p><p>Kafka doesn’t create a separate index entry for every record.</p><p>Instead, it uses a sparse index.</p><h3>What is a sparse index?</h3><p>A sparse index stores selected offset-to-position mappings rather than indexing every record.</p><p>This reduces index storage and memory overhead.</p><p>Kafka can use the nearest suitable index entry to locate a position in the log, then scan forward to find the requested record.</p><h3>Example: Understanding index intervals</h3><p>Assume a simplified sequence of records with the following sizes:</p><p>OffsetRecord sizeStarting byte position0300 bytes01500 bytes30021,000 bytes80032,000 bytes1,8004500 bytes3,800</p><p>Total record data:</p><p>300 + 500 + 1,000 + 2,000 + 500 = <strong>4,300 bytes</strong></p><p>Suppose the index interval is configured to 4,096 bytes.</p><p>Kafka uses this setting to control the approximate spacing between index entries.</p><p>For a simplified conceptual model, once enough data has accumulated, an index entry may be added near the relevant position.</p><p>For example:</p><pre>Offset Index</pre><pre>Relative Offset | Physical Position<br>----------------|------------------<br>4               | 3800</pre><p>This illustrates the purpose of a sparse index, but the exact index entry produced by Kafka depends on record-batch boundaries and its internal indexing implementation.</p><p>Kafka indexes record batches rather than treating every JSON event as an independent file entry.</p><h3>Why is this efficient?</h3><p>Imagine a consumer wants to read from offset 550.</p><p>Kafka can:</p><ol><li>Identify the segment whose offset range contains 550.</li><li>Search the segment’s sparse offset index.</li><li>Locate the nearest indexed position.</li><li>Read forward from that position.</li><li>Return the appropriate records to the consumer.</li></ol><p>This avoids scanning every record from the beginning of the partition.</p><h3>Important configuration properties</h3><p>Kafka provides several configuration options for managing segment storage.</p><pre>log.segment.bytes=1073741824<br>log.index.interval.bytes=4096</pre><p>The first property controls the default maximum log segment size.</p><p>The second controls the approximate byte interval between offset index entries.</p><p>Topic-level settings such as segment.bytes and index.interval.bytes can override relevant broker defaults.</p><p>These values are useful to understand, but production tuning should be based on actual workload characteristics rather than changing defaults without measurement.</p><h3>11. Kafka Partitioning Strategies: How Does a Producer Choose a Partition?</h3><p>So far, we’ve learned that a topic can contain multiple partitions.</p><p>But an important question remains:</p><p><strong>When a producer publishes an event, how does Kafka decide which partition should store it?</strong></p><p>The partitioning strategy determines how records are distributed across partitions.</p><p>Let’s explore three common approaches.</p><h3>Strategy 1: Key-Based Partitioning</h3><p>Key-based partitioning uses a record’s key to select a partition.</p><p>Consider:</p><pre>{<br>  &quot;topic&quot;: &quot;order-events&quot;,<br>  &quot;key&quot;: &quot;order-123&quot;,<br>  &quot;value&quot;: {<br>    &quot;eventType&quot;: &quot;OrderCreated&quot;,<br>    &quot;orderId&quot;: &quot;order-123&quot;<br>  }<br>}</pre><p>The producer uses the serialized key and its partitioning algorithm to select a partition.</p><p>Conceptually:</p><pre>partition = hash(key) % numberOfPartitions</pre><p>This formula illustrates the idea.</p><p>The exact implementation depends on the Kafka client, serializer, and partitioner. For example, the standard Java producer uses a specific hash-based strategy for keyed records.</p><h3>Example</h3><p>Assume our topic contains three partitions.</p><pre>order-events</pre><pre>Partition 0<br>Partition 1<br>Partition 2</pre><p>We publish:</p><pre>Event E0 -&gt; Key: order-123<br>Event E1 -&gt; Key: order-456<br>Event E2 -&gt; Key: order-789</pre><p>For illustration, assume the partitioner selects:</p><pre>E0 -&gt; Partition 1<br>E1 -&gt; Partition 2<br>E2 -&gt; Partition 0</pre><p>Now another event arrives for order-123.</p><pre>Event E3 -&gt; Key: order-123</pre><p>With the same partitioning configuration and partition count, it maps to Partition 1.</p><pre>Partition 0:<br>E2</pre><pre>Partition 1:<br>E0 -&gt; E3</pre><pre>Partition 2:<br>E1</pre><h3>Why is key-based partitioning important?</h3><p>Because related events can remain together in the same ordered partition log.</p><p>Consider a banking application.</p><pre>AccountCreated<br>MoneyDeposited<br>MoneyWithdrawn<br>AccountClosed</pre><p>Using accountId as the key can keep events for the same account in the same partition.</p><p>This is particularly useful when processing order matters.</p><h3>Production consideration</h3><p>If the number of partitions changes, the same key may map to a different partition.</p><p>Therefore, increasing the partition count can affect key-to-partition mapping and ordering assumptions.</p><p>This is one reason partition-count planning matters in production systems.</p><p><strong>Use key-based partitioning when events associated with the same business entity require ordered processing.</strong></p><h3>Strategy 2: Round-Robin Partitioning (Without a Key)</h3><p>Another approach is to distribute events across partitions in a round-robin sequence.</p><p>For example:</p><pre>Event E0 -&gt; Partition 0<br>Event E1 -&gt; Partition 1<br>Event E2 -&gt; Partition 2<br>Event E3 -&gt; Partition 0<br>Event E4 -&gt; Partition 1</pre><p>This distributes records across the available partitions.</p><p>Consider a record without a key:</p><pre>{<br>  &quot;topic&quot;: &quot;order-events&quot;,<br>  &quot;key&quot;: null,<br>  &quot;value&quot;: {<br>    &quot;eventType&quot;: &quot;OrderCreated&quot;,<br>    &quot;orderId&quot;: &quot;order-123&quot;<br>  }<br>}</pre><p>Because the key is absent, the producer can use a strategy that doesn’t depend on entity identity.</p><h3>Important Kafka implementation detail</h3><p>Round-robin is a partitioning strategy, but it is not necessarily the default behavior of modern Kafka producers.</p><p>Modern Apache Kafka Java producers generally use sticky partitioning behavior for records without keys, grouping records into batches for improved efficiency rather than strictly rotating partitions for every event.</p><p>The exact behavior can depend on the client library and configuration.</p><h3>When is round-robin useful?</h3><p>Round-robin distribution can be useful when:</p><ul><li>Records don’t require key-based ordering.</li><li>Events are independent.</li><li>The application wants to spread records across partitions.</li></ul><p>However, strict round-robin distribution can reduce batching efficiency compared with sticky partitioning.</p><p>For high-throughput Kafka producers, batching behavior is an important performance consideration.</p><h3>Strategy 3: Custom Partitioning</h3><p>Kafka clients can also support custom partition selection logic.</p><p>Suppose we’re building an application that processes orders from different countries.</p><p>Our business requirement is:</p><pre>India -&gt; Partition 0<br>US    -&gt; Partition 1<br>UK    -&gt; Partition 2</pre><p>We could implement custom logic to select a partition based on the country.</p><p>Conceptually:</p><pre>if (country.equals(&quot;India&quot;)) {<br>    return 0;<br>}</pre><pre>if (country.equals(&quot;US&quot;)) {<br>    return 1;<br>}</pre><pre>return 2;</pre><p>This is only an illustration, not a complete Kafka partitioner implementation.</p><h3>When should custom partitioning be used?</h3><p>Custom partitioning can be useful when there are specific business or technical requirements that cannot be satisfied by standard key-based distribution.</p><p>However, it introduces additional complexity.</p><p>For example:</p><ul><li>Some partitions may receive significantly more traffic than others.</li><li>Changing partition counts can break hardcoded mappings.</li><li>A single hot partition can become a throughput bottleneck.</li><li>Ordering requirements must still be considered.</li></ul><p>Suppose 90% of the orders originate from India.</p><p>If all Indian orders are routed to Partition 0, that partition could receive substantially more traffic than the others.</p><p>This is known as a <strong>hot partition problem</strong>.</p><p>For this reason, custom partitioning should be selected carefully and supported by workload measurements.</p><h3>12. Comparing Kafka Partitioning Strategies</h3><p>StrategyHow it worksOrderingTypical useKey-basedHashes a record keySame-key records stay in partition order under stable mappingOrders, accounts, paymentsRound-robinRotates records across partitionsNo ordering guarantee across partitionsIndependent recordsStickyBatches records on selected partitionsPartition-local ordering onlyHigh-throughput keyless publishingCustomApplication-defined selectionDepends on implementationSpecialized routing requirements</p><h3>Which strategy should we choose?</h3><p>For most event-driven business applications, <strong>key-based partitioning is a practical starting point when entity-level ordering matters</strong>.</p><p>For independent events without ordering requirements, the producer’s default keyless batching strategy is often sufficient.</p><p>Custom partitioning should be introduced only when there is a clear requirement that justifies its operational complexity.</p><h3>13. Putting Everything Together: End-to-End Kafka Producer Flow</h3><p>Now that we understand producers, topics, partitions, offsets, segments, and partitioning, let’s connect these concepts.</p><p>Imagine the Order Service publishes an OrderCreated event.</p><pre>                  Order Service<br>                       |<br>                       | Publish OrderCreated<br>                       | Key: order-123<br>                       v<br>                 Kafka Producer<br>                       |<br>                       | 1. Obtain topic metadata<br>                       | 2. Select partition using key<br>                       v<br>                Topic: order-events<br>                       |<br>          +------------+------------+<br>          |            |            |<br>          v            v            v<br>     Partition 0  Partition 1  Partition 2<br>                       |<br>                       | Selected partition<br>                       v<br>                Partition Leader<br>                       |<br>                       | Append record batch<br>                       v<br>                  Active Segment<br>                       |<br>              +--------+--------+<br>              |                 |<br>              v                 v<br>          .log file        .index file<br>              |<br>              | Record assigned offset<br>              v<br>           Replication<br>              |<br>              | Acknowledgment conditions met<br>              v<br>        Producer receives result</pre><p>Let’s walk through the flow.</p><p><strong>Step 1: Producer creates the event</strong></p><p>The Order Service constructs an OrderCreated record containing the topic, key, and value.</p><p><strong>Step 2: Producer obtains metadata</strong></p><p>The producer uses cluster metadata to discover the topic’s partitions and their leaders.</p><p>This metadata is normally obtained from Kafka brokers and cached by the producer.</p><p><strong>Step 3: Partition selection</strong></p><p>The producer selects a partition using the configured partitioning strategy.</p><p>For our example, assume order-123 maps to Partition 1.</p><p><strong>Step 4: Leader identification</strong></p><p>The producer identifies the broker currently leading Partition 1.</p><p><strong>Step 5: Event publication</strong></p><p>The producer sends a record batch to that broker.</p><p><strong>Step 6: Log append</strong></p><p>The partition leader appends the batch to its local log and assigns offsets.</p><p><strong>Step 7: Replication</strong></p><p>Follower replicas fetch data from the partition leader and maintain their own copies.</p><p><strong>Step 8: Acknowledgment</strong></p><p>Depending on the producer’s acks configuration and the partition&#39;s replication state, the leader responds when the required conditions are satisfied.</p><p><strong>Step 9: Consumer processing</strong></p><p>Consumers can fetch the retained records from the partition and process them according to their application requirements.</p><p>This is the basic lifecycle of a Kafka record, from the producer application to persistent partition storage and eventual consumption.</p><h3>14. Production Engineering: Five Important Lessons</h3><p>Understanding Kafka’s internal storage and partitioning behavior helps us make better architectural decisions.</p><h3>Lesson 1: Partition count affects scalability</h3><p>Partitions provide units of parallelism for consumer groups.</p><p>For traditional Kafka consumer groups, one partition is assigned to at most one consumer within the same group at a time.</p><p>Therefore, a topic with three partitions can have at most three actively assigned consumers in that group for that topic, even if more consumer instances are running.</p><h3>Lesson 2: Ordering is partition-specific</h3><p>Kafka does not provide global ordering across multiple partitions.</p><p>If business operations require ordered processing, choose partition keys carefully.</p><h3>Lesson 3: Offsets identify positions, not business events</h3><p>Offsets are unique only within a particular partition.</p><p>A business event should have its own event identifier when tracking or deduplication is required.</p><h3>Lesson 4: Log segments improve manageability</h3><p>Kafka’s segmented logs support efficient storage organization, offset lookup, retention, and recovery.</p><p>The sparse offset index helps locate records without indexing every individual event.</p><h3>Lesson 5: Partitioning directly affects performance</h3><p>A poorly chosen key can concentrate traffic on a small number of partitions.</p><p>A good partitioning strategy balances business ordering requirements with throughput and workload distribution.</p><h3>15. Common Kafka Interview Questions</h3><p>Before concluding, let’s review a few questions that frequently appear in backend and distributed systems interviews.</p><p><strong>Q1. What is the difference between a Kafka topic and a partition?</strong></p><p>A topic is a logical stream of records. A partition is an ordered, append-only log that stores a subset of the topic’s records.</p><p><strong>Q2. Does Kafka guarantee global ordering?</strong></p><p>No. Kafka guarantees ordering within individual partitions, not across all partitions of a topic.</p><p><strong>Q3. Why does Kafka use offsets?</strong></p><p>Offsets identify record positions within partitions and allow consumers to track their progress.</p><p><strong>Q4. Why does Kafka divide partition logs into segments?</strong></p><p>Segments make storage management, retention, recovery, and offset lookup more manageable.</p><p><strong>Q5. Does Kafka index every event?</strong></p><p>No. Kafka maintains sparse indexes that map selected offsets to physical positions within log segments.</p><p><strong>Q6. What happens if multiple records have the same key?</strong></p><p>Under a stable key-based partitioning strategy, those records map to the same partition, allowing partition-local ordering.</p><p><strong>Q7. Is round-robin the default partitioning strategy when no key is provided?</strong></p><p>Not necessarily. Modern Kafka Java producers generally use sticky partitioning behavior for keyless records to improve batching efficiency.</p><p><strong>Q8. What is a hot partition?</strong></p><p>A hot partition receives disproportionately high traffic or processing demand compared with other partitions, potentially limiting throughput.</p><h3>Conclusion</h3><p>Apache Kafka becomes much easier to understand when we stop thinking of it as simply a messaging system and start looking at how it organizes and stores events internally.</p><p>The fundamental concepts are closely connected:</p><ul><li><strong>Producers</strong> publish records without knowing their consumers.</li><li><strong>Topics</strong> logically organize event streams.</li><li><strong>Partitions</strong> distribute records and provide ordered logs.</li><li><strong>Offsets</strong> identify positions within individual partitions.</li><li><strong>Log segments</strong> divide partition storage into manageable files.</li><li><strong>Sparse indexes</strong> support efficient record lookup.</li><li><strong>Partitioning strategies</strong> determine how events are distributed and influence ordering, throughput, and scalability.</li></ul><p>The most important takeaway is:</p><p><strong>Kafka’s scalability comes from partitioning, its replay capability comes from retained logs and offsets, and its storage efficiency comes partly from segmented logs and sparse indexing.</strong></p><p>Understanding these internals is essential for designing reliable event-driven applications rather than simply integrating Kafka as another messaging dependency.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4a795c59f7ef" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Unit of Work (UoW) Pattern: Keeping Database Operations Consistent]]></title>
            <link>https://medium.com/@arjun.devb25/unit-of-work-uow-pattern-keeping-database-operations-consistent-76bf7f478028?source=rss-f027b3325552------2</link>
            <guid isPermaLink="false">https://medium.com/p/76bf7f478028</guid>
            <category><![CDATA[design]]></category>
            <category><![CDATA[system-design-interview]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[database-design]]></category>
            <category><![CDATA[golang]]></category>
            <dc:creator><![CDATA[Arjun Singh]]></dc:creator>
            <pubDate>Thu, 13 Aug 2026 18:00:27 GMT</pubDate>
            <atom:updated>2026-08-13T18:00:27.342Z</atom:updated>
            <content:encoded><![CDATA[<p>Imagine you are building an <strong>Order Service</strong>.</p><p>When a customer places an order, your application may need to:</p><ul><li>Create the order</li><li>Reduce inventory</li><li>Create a payment record</li><li>Update customer information</li><li>Store an audit record</li></ul><p>At first glance, this looks simple.</p><p>But now imagine this:</p><pre>Create Order       → SUCCESS<br>Update Inventory   → SUCCESS<br>Create Payment     → FAILED</pre><p>Now your database is in an inconsistent state.</p><p>The order exists.</p><p>The inventory has already been reduced.</p><p>But there is no payment record.</p><p>So the question becomes:</p><blockquote><strong><em>How can we make multiple database operations behave like one logical operation?</em></strong></blockquote><p>This is where the <strong>Unit of Work (UoW) Pattern</strong> becomes useful.</p><h3>What is the Unit of Work Pattern?</h3><p>The <strong>Unit of Work pattern</strong> is a design pattern used to group multiple related database operations into a <strong>single logical unit of work</strong>.</p><p>The basic idea is simple:</p><blockquote><strong><em>Either all required database changes succeed, or none of them should be committed.</em></strong></blockquote><p>Conceptually:</p><pre>Business Operation<br>                     │<br>                     ▼<br>                Unit of Work<br>                     │<br>          ┌──────────┼──────────┐<br>          ▼          ▼          ▼<br>       Order      Inventory   Payment<br>      Repository  Repository  Repository<br>          │          │          │<br>          └──────────┼──────────┘<br>                     ▼<br>                Transaction<br>                     │<br>              ┌──────┴──────┐<br>              ▼             ▼<br>           COMMIT        ROLLBACK</pre><p>The Unit of Work coordinates these operations and controls the transaction boundary.</p><h3>The Problem Without Unit of Work</h3><p>Consider a simple service:</p><pre>OrderService</pre><pre>    createOrder()<br>        ↓<br>    orderRepository.save()<br>        ↓<br>    inventoryRepository.update()<br>        ↓<br>    paymentRepository.save()</pre><p>What happens if:</p><pre>orderRepository.save()       → SUCCESS<br>inventoryRepository.update() → SUCCESS<br>paymentRepository.save()     → FAILURE</pre><p>We have a problem.</p><p>Some changes were already persisted.</p><p>This can lead to:</p><ul><li>Inconsistent data</li><li>Difficult recovery</li><li>Manual cleanup</li><li>Complicated error handling</li><li>Business logic that becomes tightly coupled with transaction management</li></ul><p>We need a way to say:</p><blockquote><em>“These operations belong together. Treat them as one unit.”</em></blockquote><p>That’s exactly what Unit of Work provides.</p><h3>Unit of Work in Action</h3><p>With UoW, the flow becomes:</p><pre>BEGIN TRANSACTION<br>        │<br>        ▼<br>Create Order<br>        │<br>        ▼<br>Update Inventory<br>        │<br>        ▼<br>Create Payment Record<br>        │<br>        ▼<br>Everything successful?<br>      /       \<br>    YES        NO<br>     │          │<br>     ▼          ▼<br>  COMMIT      ROLLBACK</pre><p>If everything succeeds:</p><pre>COMMIT</pre><p>If something fails:</p><pre>ROLLBACK</pre><p>The database returns to its previous consistent state.</p><h3>A Simple Real-World Example</h3><p>Let’s take an e-commerce system.</p><p>A customer purchases:</p><pre>Product: MacBook<br>Quantity: 1</pre><p>The application needs to perform three operations:</p><pre>1. Create Order<br>2. Decrease Inventory<br>3. Create Payment Record</pre><p>These operations are logically connected.</p><p>If the order is created but inventory isn’t updated, we have a problem.</p><p>If inventory is reduced but the order isn’t created, we have a problem.</p><p>Therefore, these operations can be treated as one <strong>Unit of Work</strong>.</p><pre>                Place Order<br>                    │<br>                    ▼<br>              Unit of Work<br>                    │<br>       ┌────────────┼────────────┐<br>       ▼            ▼            ▼<br>   Order Repo   Inventory Repo  Payment Repo<br>       │            │            │<br>       └────────────┼────────────┘<br>                    ▼<br>               Transaction<br>                    │<br>             ┌──────┴──────┐<br>             ▼             ▼<br>          COMMIT        ROLLBACK</pre><h3>Unit of Work vs Database Transaction</h3><p>These two concepts are related, but they are <strong>not the same thing</strong>.</p><h3>Database Transaction</h3><p>A transaction is a database mechanism.</p><p>It provides properties such as:</p><ul><li>Atomicity</li><li>Consistency</li><li>Isolation</li><li>Durability</li></ul><p>Typical flow:</p><pre>BEGIN<br>   ↓<br>SQL Operation 1<br>   ↓<br>SQL Operation 2<br>   ↓<br>SQL Operation 3<br>   ↓<br>COMMIT</pre><p>Or:</p><pre>BEGIN<br>   ↓<br>SQL Operation<br>   ↓<br>ERROR<br>   ↓<br>ROLLBACK</pre><h3>Unit of Work</h3><p>Unit of Work is an <strong>application-level design pattern</strong>.</p><p>It coordinates multiple operations that belong to the same business operation.</p><p>So you can think about it like this:</p><pre>Application<br>    │<br>    ▼<br>Unit of Work<br>    │<br>    ▼<br>Database Transaction<br>    │<br>    ▼<br>Database</pre><p>A useful way to remember this:</p><blockquote><strong><em>Transaction provides atomicity at the database level.</em></strong><em><br></em><strong><em>Unit of Work defines and coordinates the logical unit of work at the application level.</em></strong></blockquote><h3>Unit of Work + Repository Pattern</h3><p>Unit of Work becomes particularly powerful when combined with the <strong>Repository Pattern</strong>.</p><p>The Repository is responsible for data access.</p><p>For example:</p><pre>OrderRepository<br>InventoryRepository<br>PaymentRepository</pre><p>The Unit of Work coordinates them.</p><pre>                 Service<br>                    │<br>                    ▼<br>              Unit of Work<br>              /     |      \<br>             /      |       \<br>            ▼       ▼        ▼<br>        Order     Inventory  Payment<br>        Repo        Repo       Repo<br>            \        |        /<br>             \       |       /<br>              ▼      ▼      ▼<br>                 Database</pre><p>This creates a clean separation of responsibilities.</p><h3>Repository</h3><blockquote><em>“How do I interact with this data?”</em></blockquote><h3>Unit of Work</h3><blockquote><em>“Which operations should participate in the same transaction?”</em></blockquote><h3>Service</h3><blockquote><em>“What business operation am I trying to perform?”</em></blockquote><p>This separation makes the application easier to understand and maintain.</p><h3>A Simple Go Implementation</h3><p>Let’s see how this can look in Go using PostgreSQL.</p><p>A simplified Unit of Work interface could look like:</p><pre>type UnitOfWork interface {<br>    Begin(ctx context.Context) error<br>    Commit(ctx context.Context) error<br>    Rollback(ctx context.Context) error<br>    Orders() OrderRepository<br>    Inventory() InventoryRepository<br>    Payments() PaymentRepository<br>}</pre><p>The service can then use the Unit of Work:</p><pre>func (s *OrderService) PlaceOrder(<br>    ctx context.Context,<br>    order Order,<br>) error {<br>      if err := s.uow.Begin(ctx); err != nil {<br>        return err<br>    }<br>    if err := s.uow.Orders().Create(ctx, order); err != nil {<br>        s.uow.Rollback(ctx)<br>        return err<br>    }<br>    if err := s.uow.Inventory().Decrease(<br>        ctx,<br>        order.ProductID,<br>        order.Quantity,<br>    ); err != nil {<br>        s.uow.Rollback(ctx)<br>        return err<br>    }<br>    if err := s.uow.Payments().Create(ctx, order); err != nil {<br>        s.uow.Rollback(ctx)<br>        return err<br>    }<br>    return s.uow.Commit(ctx)<br>}</pre><p>The important thing here is not the exact implementation.</p><p>The important concept is:</p><pre>BEGIN<br>  ↓<br>Operation A<br>  ↓<br>Operation B<br>  ↓<br>Operation C<br>  ↓<br>COMMIT</pre><p>or:</p><pre>BEGIN<br>  ↓<br>Operation A<br>  ↓<br>Operation B<br>  ↓<br>ERROR<br>  ↓<br>ROLLBACK</pre><h3>Where Should the Transaction Boundary Live?</h3><p>This is one of the most important design decisions.</p><p>A common mistake is allowing every repository to create its own transaction.</p><p>For example:</p><pre>OrderRepository<br>    → BEGIN<br>    → INSERT<br>    → COMMIT</pre><pre>InventoryRepository<br>    → BEGIN<br>    → UPDATE<br>    → COMMIT</pre><pre>PaymentRepository<br>    → BEGIN<br>    → INSERT<br>    → COMMIT</pre><p>This defeats the purpose.</p><p>Why?</p><p>Because these are now <strong>three independent transactions</strong>.</p><p>Instead, the transaction boundary should generally surround the entire business operation:</p><pre>            BEGIN<br>               │<br>       ┌───────┼────────┐<br>       ▼       ▼        ▼<br>     Order   Inventory Payment<br>       │       │        │<br>       └───────┼────────┘<br>               ▼<br>             COMMIT</pre><p>Now all operations participate in the same transaction.</p><h3>An Important Rule</h3><p>A transaction should generally be kept <strong>as short as reasonably possible</strong>.</p><p>Avoid doing this:</p><pre>BEGIN TRANSACTION<br>      ↓<br>Update Database<br>      ↓<br>Call External API<br>      ↓<br>Wait for response<br>      ↓<br>Call Another Service<br>      ↓<br>Send Email<br>      ↓<br>COMMIT</pre><p>Why?</p><p>Because the database transaction remains open while external systems are being called.</p><p>That can lead to:</p><ul><li>Long-running transactions</li><li>Connection pool exhaustion</li><li>Lock contention</li><li>Increased latency</li><li>Reduced database throughput</li></ul><p>A better approach is to carefully separate database atomicity from external side effects.</p><p>And this leads us to another important architectural concept.</p><h3>Unit of Work Does NOT Solve Distributed Transactions</h3><p>This is where things become interesting.</p><p>Suppose your architecture looks like this:</p><pre>Order Service<br>      │<br>      ├── Order DB<br>      │<br>      └── Kafka<br>             │<br>             ▼<br>       Payment Service<br>             │<br>             ▼<br>        Payment DB</pre><p>Your Unit of Work can control:</p><pre>Order DB</pre><p>But it cannot automatically make this atomic:</p><pre>Order DB<br>+<br>Payment DB<br>+<br>Kafka</pre><p>These are different resources.</p><p>A local Unit of Work cannot guarantee:</p><blockquote><em>“Commit everything everywhere or rollback everything everywhere.”</em></blockquote><p>For distributed workflows, patterns such as:</p><ul><li><strong>Saga Pattern</strong></li><li><strong>Transactional Outbox</strong></li><li><strong>Compensating Transactions</strong></li><li><strong>Event-driven Architecture</strong></li></ul><p>may be more appropriate.</p><h3>Unit of Work + Outbox Pattern</h3><p>This is a particularly useful combination in distributed systems.</p><p>Suppose we need to create an order and publish an event:</p><pre>Create Order<br>     +<br>Create OrderCreated Event</pre><p>Instead of directly publishing to Kafka inside the transaction, we can store the event in an <strong>Outbox table</strong>.</p><pre>       Unit of Work<br>               │<br>       ┌───────┴────────┐<br>       ▼                ▼<br>   Order Table      Outbox Table<br>       │                │<br>       └───────┬────────┘<br>               ▼<br>             COMMIT<br>               │<br>               ▼<br>        Outbox Publisher<br>               │<br>               ▼<br>             Kafka</pre><p>Now the order and the event record are committed together.</p><p>If the transaction succeeds:</p><pre>Order       → Saved<br>Outbox Event → Saved</pre><p>A separate publisher can later publish the event to Kafka.</p><p>This dramatically improves reliability in event-driven systems.</p><h3>When Should You Use Unit of Work?</h3><p>Unit of Work is useful when:</p><h3>1. Multiple database operations must succeed together</h3><pre>Create Order<br>+<br>Update Inventory<br>+<br>Create Payment Record</pre><h3>2. Multiple repositories participate in one business operation</h3><pre>OrderRepository<br>InventoryRepository<br>PaymentRepository</pre><h3>3. Rollback is important</h3><p>If one operation fails, previous operations should not remain committed.</p><h3>4. You want a clear transaction boundary</h3><p>Instead of every repository independently managing transactions, the application has a clear business-level transaction.</p><h3>When Should You NOT Use It?</h3><p>Not every database operation needs a Unit of Work.</p><p>For something simple like:</p><pre>GET /users/123</pre><p>where you are simply reading one record, introducing a complex UoW abstraction may add unnecessary complexity.</p><p>Similarly, if two operations are intentionally independent:</p><pre>Update User Profile<br>+<br>Send Analytics Event</pre><p>they may not belong to the same transaction.</p><p>The goal isn’t:</p><blockquote><em>“Use Unit of Work everywhere.”</em></blockquote><p>The goal is:</p><blockquote><strong><em>Use it where multiple operations form one logical business transaction.</em></strong></blockquote><h3>Common Mistakes</h3><h3>❌ Creating a transaction inside every repository</h3><p>This creates independent transactions instead of one logical transaction.</p><h3>❌ Keeping transactions open for too long</h3><p>Avoid external API calls and unnecessary processing inside a database transaction.</p><h3>❌ Assuming UoW solves distributed transactions</h3><p>It usually doesn’t.</p><h3>❌ Making every service method use UoW</h3><p>Simple operations don’t necessarily need this abstraction.</p><h3>❌ Mixing transaction ownership</h3><p>The application should have a clear understanding of <strong>who owns and controls the transaction boundary</strong>.</p><h3>A Simple Mental Model</h3><p>I like to think about the three concepts this way:</p><pre>Repository<br>    ↓<br>&quot;How do I access the data?&quot;<br>Transaction<br>    ↓<br>&quot;How do I make database changes atomic?&quot;<br>Unit of Work<br>    ↓<br>&quot;Which operations belong to the same business transaction?&quot;</pre><p>This mental model makes the pattern much easier to understand.</p><h3>Unit of Work in Modern Backend Architecture</h3><p>In a typical backend service, you might see something like:</p><pre>                  API / Controller<br>                       │<br>                       ▼<br>                  Service Layer<br>                       │<br>                       ▼<br>                 Unit of Work<br>                       │<br>            ┌──────────┼──────────┐<br>            ▼          ▼          ▼<br>         Order      Inventory   Payment<br>       Repository  Repository  Repository<br>            │          │          │<br>            └──────────┼──────────┘<br>                       ▼<br>                    Database</pre><p>And when the system becomes distributed:</p><pre>Service<br>                    │<br>                    ▼<br>              Unit of Work<br>                    │<br>             ┌──────┴──────┐<br>             ▼             ▼<br>          Business      Outbox<br>            Data          Event<br>             │             │<br>             └──────┬──────┘<br>                    ▼<br>                  COMMIT<br>                    │<br>                    ▼<br>                  Kafka<br>                    │<br>          ┌─────────┴─────────┐<br>          ▼                   ▼<br>   Payment Service      Notification</pre><p>This is where a relatively simple design pattern starts connecting to larger system-design concepts.</p><h3>Final Takeaway</h3><p>The <strong>Unit of Work pattern</strong> is fundamentally about <strong>consistency and transaction boundaries</strong>.</p><p>It helps us group related operations into one logical unit:</p><pre>Operation A<br>    +<br>Operation B<br>    +<br>Operation C<br>    =<br>One Unit of Work</pre><p>Either:</p><pre>Everything succeeds → COMMIT</pre><p>or:</p><pre>Something fails → ROLLBACK</pre><p>And the most important distinction to remember is:</p><blockquote><strong><em>Repository manages data access.</em></strong><em><br></em><strong><em>Transaction provides atomicity.</em></strong><em><br></em><strong><em>Unit of Work coordinates a business operation across multiple data-access operations.</em></strong></blockquote><p>Once you understand Unit of Work, it becomes much easier to reason about more advanced patterns such as <strong>Transactional Outbox, Saga, Event-Driven Architecture, and distributed consistency</strong>.</p><h3>💡 One Last Thought</h3><p>A good backend design is not just about making individual database operations work.</p><p>It is about understanding <strong>which operations belong together, what happens when something fails, and where the transaction boundary should exist.</strong></p><p>That’s the real value of the <strong>Unit of Work pattern</strong>.</p><p>#SystemDesign #DesignPatterns #BackendEngineering #SoftwareArchitecture #Golang #GoLang #Database #Microservices #DistributedSystems #PostgreSQL #BackendDevelopment #SoftwareEngineering</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=76bf7f478028" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Implicit Interface Implementation in Go: A Real Backend Example]]></title>
            <link>https://medium.com/@arjun.devb25/implicit-interface-implementation-in-go-a-real-backend-example-3c946f9d10f9?source=rss-f027b3325552------2</link>
            <guid isPermaLink="false">https://medium.com/p/3c946f9d10f9</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[golang]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[backend-development]]></category>
            <dc:creator><![CDATA[Arjun Singh]]></dc:creator>
            <pubDate>Wed, 05 Aug 2026 19:47:39 GMT</pubDate>
            <atom:updated>2026-08-05T19:47:39.782Z</atom:updated>
            <content:encoded><![CDATA[<p>One of my favorite Go features is <strong>implicit interface implementation</strong>.</p><p>Unlike Java or C#, Go doesn’t require a type to explicitly declare that it implements an interface.</p><p>Let’s look at a real-world example.</p><p>Suppose you’re building a <strong>Course Service</strong>. Whenever a new course is created, you need to publish an event to Kafka.</p><p>First, define the behavior your application needs.</p><pre>type Sender interface {<br>    Send(<br>        ctx context.Context,<br>        event events.CourseCreatedEvent,<br>    ) error<br>}</pre><p>Notice that this interface only describes <strong>what</strong> should happen.</p><p>It doesn’t care <strong>how</strong> it’s implemented.</p><p>Now let’s create a Kafka implementation.</p><pre>type KafkaSender struct {<br>    producer *kafka.Producer<br>}</pre><pre>func (k *KafkaSender) Send(<br>    ctx context.Context,<br>    event events.CourseCreatedEvent,<br>) error {</pre><pre>    // Serialize event</pre><pre>    // Publish to Kafka</pre><pre>    return nil<br>}</pre><p>Did you notice something?</p><p>KafkaSender never says</p><pre>implements Sender</pre><p>There is no keyword.</p><p>There is no annotation.</p><p>There is no registration.</p><p>Yet this works perfectly.</p><pre>var sender Sender = &amp;KafkaSender{}</pre><p>The Go compiler checks that KafkaSender has a method named</p><pre>Send(context.Context, events.CourseCreatedEvent) error</pre><p>If it does, it automatically satisfies the interface.</p><h3>What Happens If We Miss a Method?</h3><p>Imagine someone accidentally changes the implementation.</p><pre>func (k *KafkaSender) Send(<br>    event events.CourseCreatedEvent,<br>) error {<br>    return nil<br>}</pre><p>The context.Context parameter is missing.</p><p>Now this won’t compile.</p><pre>var sender Sender = &amp;KafkaSender{}</pre><p>Compiler error:</p><pre>*KafkaSender does not implement Sender<br>    wrong type for method Send</pre><p>Even without an implements keyword, Go still provides <strong>compile-time safety</strong>.</p><h3>Swapping Implementations Is Easy</h3><p>Tomorrow, suppose your company decides to publish events using RabbitMQ instead of Kafka.</p><p>You simply write another implementation.</p><pre>type RabbitMQSender struct {<br>    conn *amqp.Connection<br>}</pre><pre>func (r *RabbitMQSender) Send(<br>    ctx context.Context,<br>    event events.CourseCreatedEvent,<br>) error {</pre><pre>    // Publish to RabbitMQ</pre><pre>    return nil<br>}</pre><p>Nothing else changes.</p><pre>func CreateCourse(<br>    sender Sender,<br>) error {</pre><pre>    // Save course...</pre><pre>    sender.Send(ctx, event)</pre><pre>    return nil<br>}</pre><p>Now you can inject whichever implementation you want.</p><pre>CreateCourse(&amp;KafkaSender{})</pre><pre>CreateCourse(&amp;RabbitMQSender{})</pre><p>The business logic doesn’t know — or care — which messaging system is being used.</p><h3>Testing Becomes Trivial</h3><p>The same interface also makes testing much cleaner.</p><pre>type MockSender struct {<br>    Events []events.CourseCreatedEvent<br>}</pre><pre>func (m *MockSender) Send(<br>    ctx context.Context,<br>    event events.CourseCreatedEvent,<br>) error {</pre><pre>    m.Events = append(m.Events, event)<br>    return nil<br>}</pre><p>Now your unit test doesn’t need Kafka running.</p><pre>mock := &amp;MockSender{}</pre><pre>service := CourseService{<br>    sender: mock,<br>}</pre><pre>service.CreateCourse(ctx, req)</pre><p>No Docker.</p><p>No Kafka container.</p><p>No mocking framework.</p><p>Just a small struct that implements the same interface.</p><h3>How Java Would Do It</h3><p>In Java, you’d explicitly declare the implementation.</p><pre>public class KafkaSender implements Sender {</pre><pre>    @Override<br>    public void send(CourseCreatedEvent event) {<br>        // Publish to Kafka<br>    }<br>}</pre><p>The class must explicitly state:</p><pre>implements Sender</pre><p>Go removes this ceremony.</p><p>It simply asks:</p><blockquote><strong><em>“Does this type provide the required behavior?”</em></strong></blockquote><p>If the answer is yes, it satisfies the interface automatically.</p><h3>Why This Design Is Powerful</h3><p>This approach offers several practical benefits:</p><ul><li><strong>Looser coupling</strong> — Business logic depends on behavior, not concrete implementations.</li><li><strong>Easy replacement</strong> — Swap Kafka for RabbitMQ, SNS, or any other transport without changing your service layer.</li><li><strong>Simple testing</strong> — Create lightweight mocks without external libraries.</li><li><strong>Cleaner code</strong> — No implements keyword or boilerplate.</li><li><strong>Compile-time safety</strong> — The compiler still verifies that all required methods are present.</li></ul><p>This kind of example resonates with Go backend developers because it’s exactly how interfaces are used in production: defining contracts at the service boundary while keeping implementations interchangeable.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3c946f9d10f9" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building Our Own PMD — Part 4: Traversing the AST with the Visitor Pattern]]></title>
            <link>https://medium.com/@arjun.devb25/building-our-own-pmd-part-4-traversing-the-ast-with-the-visitor-pattern-63374c185b20?source=rss-f027b3325552------2</link>
            <guid isPermaLink="false">https://medium.com/p/63374c185b20</guid>
            <category><![CDATA[system-design-interview]]></category>
            <category><![CDATA[clean-code]]></category>
            <category><![CDATA[java8]]></category>
            <category><![CDATA[backend-development]]></category>
            <category><![CDATA[personal-development]]></category>
            <dc:creator><![CDATA[Arjun Singh]]></dc:creator>
            <pubDate>Sat, 25 Jul 2026 18:34:09 GMT</pubDate>
            <atom:updated>2026-07-25T18:34:09.273Z</atom:updated>
            <content:encoded><![CDATA[<p>In the previous article, we successfully parsed Java source code into an <strong>Abstract Syntax Tree (AST)</strong> using JavaParser.</p><p>At this point, we have transformed a Java file into a structured tree that represents classes, methods, variables, loops, expressions, and many other language constructs.</p><p>However, one important question remains:</p><blockquote><strong><em>How do we inspect every node in that tree without writing hundreds of nested loops?</em></strong></blockquote><p>The answer is the <strong>Visitor Pattern</strong>.</p><p>The Visitor Pattern is one of the core design patterns behind static analysis tools like <strong>PMD (Programming Mistake Detector)</strong>, <strong>Checkstyle</strong>, and many IDE inspections.</p><p>Understanding this pattern is essential because every static analysis rule begins by traversing the AST.</p><h3>Why Traversing an AST Is Difficult</h3><p>Imagine the following Java class.</p><pre>public class UserService {</pre><pre>    public void saveUser() {</pre><pre>        if (true) {<br>            System.out.println(&quot;Saving...&quot;);<br>        }<br>    }<br>}</pre><p>Its simplified AST looks like this:</p><pre>CompilationUnit<br>        │<br>        └── ClassDeclaration<br>                 │<br>                 └── MethodDeclaration<br>                          │<br>                          └── IfStatement<br>                                   │<br>                                   └── MethodCallExpression</pre><p>Suppose we want to inspect every method call.</p><p>One option would be to manually navigate every child node.</p><pre>CompilationUnit</pre><pre>↓</pre><pre>Class</pre><pre>↓</pre><pre>Method</pre><pre>↓</pre><pre>If Statement</pre><pre>↓</pre><pre>Method Call</pre><p>Now imagine doing this for:</p><ul><li>Nested loops</li><li>Anonymous classes</li><li>Lambda expressions</li><li>Switch expressions</li><li>Try-with-resources</li><li>Records</li><li>Inner classes</li></ul><p>The traversal logic quickly becomes difficult to maintain.</p><h3>The Visitor Pattern</h3><p>Instead of manually navigating every node, we delegate the traversal to a <strong>Visitor</strong>.</p><p>The Visitor automatically walks through the AST and invokes callback methods whenever it encounters a node of interest.</p><p>Conceptually:</p><pre>Visitor</pre><pre>↓</pre><pre>CompilationUnit</pre><pre>↓</pre><pre>Class</pre><pre>↓</pre><pre>Method</pre><pre>↓</pre><pre>If Statement</pre><pre>↓</pre><pre>Method Call</pre><pre>↓</pre><pre>Return</pre><p>The visitor handles the navigation.</p><p>Our responsibility is simply deciding what to do when a particular node is visited.</p><h3>Why PMD Uses Visitors</h3><p>Every PMD rule focuses on a specific kind of node.</p><p>For example:</p><p>RuleInterested NodeEmpty Catch BlockCatchClauseUnused VariableVariableDeclaratorLong MethodMethodDeclarationNaming ConventionClassOrInterfaceDeclarationSystem.out.println() DetectionMethodCallExpr</p><p>Instead of traversing the entire AST manually for every rule, PMD relies on visitors to locate the relevant nodes efficiently.</p><h3>A Simple Analogy</h3><p>Imagine you’re inspecting every room in a hotel.</p><p>Without a visitor:</p><ul><li>Walk into Room 1</li><li>Open every cupboard</li><li>Check every drawer</li><li>Move to Room 2</li><li>Repeat</li></ul><p>Now imagine hiring a guide.</p><p>The guide walks through the entire hotel and simply tells you:</p><blockquote><em>“You’re now entering Room 101.”</em></blockquote><blockquote><em>“Here’s Room 102.”</em></blockquote><blockquote><em>“Here’s Room 103.”</em></blockquote><p>You no longer worry about navigation.</p><p>You focus only on what you’re looking for.</p><p>The Visitor Pattern works in exactly the same way.</p><h3>Traversing the AST</h3><p>When JavaParser parses a Java file, every element becomes a node.</p><p>The visitor walks through those nodes in a predictable order.</p><pre>CompilationUnit</pre><pre>↓</pre><pre>Package</pre><pre>↓</pre><pre>Imports</pre><pre>↓</pre><pre>Class</pre><pre>↓</pre><pre>Fields</pre><pre>↓</pre><pre>Methods</pre><pre>↓</pre><pre>Statements</pre><pre>↓</pre><pre>Expressions</pre><p>As each node is visited, we have an opportunity to inspect it.</p><p>This is where our static analysis logic lives.</p><h3>Separation of Responsibilities</h3><p>One of the biggest advantages of the Visitor Pattern is the separation of concerns.</p><p>Instead of combining traversal and rule logic, they remain independent.</p><pre>Parser</pre><pre>↓</pre><pre>AST</pre><pre>↓</pre><pre>Visitor<br>       │<br>       ├── Naming Rule<br>       ├── Performance Rule<br>       ├── Design Rule<br>       ├── Security Rule<br>       └── Best Practice Rule</pre><p>The parser builds the AST.</p><p>The visitor traverses it.</p><p>Each rule analyzes only the nodes it cares about.</p><p>This architecture makes the system modular, testable, and easy to extend.</p><h3>Why This Design Scales</h3><p>Imagine your analyzer grows from one rule to one hundred rules.</p><p>Without visitors, each rule would need its own traversal logic.</p><p>That would lead to duplicated code and inconsistent behavior.</p><p>With the Visitor Pattern:</p><ul><li>Traversal logic is reused.</li><li>Rules remain independent.</li><li>New rules can be added without modifying existing ones.</li><li>Maintenance becomes significantly easier.</li></ul><p>This is one of the reasons mature static analysis tools have remained maintainable even as they evolved over many years.</p><h3>Preparing for Our First Rule</h3><p>Now that we understand how traversal works, we’re finally ready to analyze code.</p><p>In the next article, we’ll implement our first real static analysis rule.</p><p>We’ll detect calls to:</p><pre>System.out.println()</pre><p>and generate a violation report similar to PMD.</p><p>Although this rule is intentionally simple, it introduces the same workflow used by professional static analysis tools:</p><ul><li>Visit a node</li><li>Inspect it</li><li>Evaluate a condition</li><li>Report a violation</li></ul><p>Once this pattern is understood, building more sophisticated rules becomes a natural extension.</p><h3>Final Thoughts</h3><p>The Visitor Pattern is one of the most important concepts in static code analysis.</p><p>It allows analyzers to traverse complex syntax trees without coupling navigation logic to business rules.</p><p>By separating traversal from analysis, tools like PMD can support hundreds of independent rules while keeping the codebase modular and extensible.</p><p>In the next part of this series, we’ll put this knowledge into practice and write our first working static analysis rule using JavaParser.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=63374c185b20" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building Our Own PMD — Part 3: Parsing Java Source Code and Exploring the Abstract Syntax Tree…]]></title>
            <link>https://medium.com/@arjun.devb25/building-our-own-pmd-part-3-parsing-java-source-code-and-exploring-the-abstract-syntax-tree-9e3c2227f246?source=rss-f027b3325552------2</link>
            <guid isPermaLink="false">https://medium.com/p/9e3c2227f246</guid>
            <category><![CDATA[clean-code]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[developer]]></category>
            <category><![CDATA[backend-engineering]]></category>
            <category><![CDATA[software-development]]></category>
            <dc:creator><![CDATA[Arjun Singh]]></dc:creator>
            <pubDate>Fri, 24 Jul 2026 17:08:18 GMT</pubDate>
            <atom:updated>2026-07-24T17:08:18.063Z</atom:updated>
            <content:encoded><![CDATA[<h3>Building Our Own PMD — Part 3: Parsing Java Source Code and Exploring the Abstract Syntax Tree (AST)</h3><p>In the previous article, we designed the architecture of a static code analyzer and learned that every tool like <strong>PMD (Programming Mistake Detector)</strong> follows a similar pipeline:</p><pre>Java Source Code<br>        │<br>        ▼<br>      Parser<br>        │<br>        ▼<br>Abstract Syntax Tree (AST)<br>        │<br>        ▼<br>   Rule Engine<br>        │<br>        ▼<br>Violation Report</pre><p>Today, we’re going to build the <strong>first working component</strong> of our analyzer: the <strong>parser</strong>.</p><p>By the end of this article, you’ll understand:</p><ul><li>Why parsing is necessary</li><li>What an Abstract Syntax Tree (AST) really is</li><li>How to parse Java code using JavaParser</li><li>How to inspect the structure of a Java program</li></ul><p>This is the foundation of every static analysis tool.</p><h3>Why Do We Need a Parser?</h3><p>Suppose we have the following Java class.</p><pre>public class UserService {</pre><pre>    public void saveUser() {<br>        System.out.println(&quot;Saving...&quot;);<br>    }<br>}</pre><p>To us, this is easy to understand.</p><p>We immediately recognize:</p><ul><li>A class</li><li>A method</li><li>A method invocation</li></ul><p>But to a computer, it’s just a sequence of characters.</p><pre>p u b l i c c l a s s U s e r S e r v i c e ...</pre><p>Before we can analyze code, we must convert those characters into a meaningful structure.</p><p>That’s exactly what a parser does.</p><h3>What Happens During Parsing?</h3><p>A parser reads Java source code and validates it against the Java language grammar.</p><p>If the syntax is correct, it constructs an internal representation called an <strong>Abstract Syntax Tree (AST)</strong>.</p><p>Conceptually:</p><pre>Java File</pre><pre>↓</pre><pre>Parser</pre><pre>↓</pre><pre>AST</pre><p>The parser doesn’t care about indentation or blank lines.</p><p>It cares about language constructs like:</p><ul><li>Classes</li><li>Interfaces</li><li>Methods</li><li>Variables</li><li>Loops</li><li>Conditions</li><li>Expressions</li></ul><h3>Introducing JavaParser</h3><p>Building a Java parser from scratch would require implementing the entire Java grammar.</p><p>Instead, we’ll use <strong>JavaParser</strong>, an open-source library that already understands Java syntax.</p><p>Add the dependency:</p><pre>&lt;dependency&gt;<br>    &lt;groupId&gt;com.github.javaparser&lt;/groupId&gt;<br>    &lt;artifactId&gt;javaparser-core&lt;/artifactId&gt;<br>    &lt;version&gt;3.27.1&lt;/version&gt;<br>&lt;/dependency&gt;</pre><p>Now we can focus on analysis rather than parsing.</p><h3>Parsing Our First Java File</h3><p>Imagine we have:</p><pre>public class UserService {</pre><pre>    public void saveUser() {</pre><pre>        int total = 100;</pre><pre>        System.out.println(total);<br>    }<br>}</pre><p>Parsing it is surprisingly simple:</p><pre>CompilationUnit cu =<br>    StaticJavaParser.parse(new File(&quot;UserService.java&quot;));</pre><p>That’s all.</p><p>Behind the scenes, JavaParser reads the source file, validates the syntax, and constructs the AST.</p><p>The returned CompilationUnit represents the root node of the tree.</p><h3>Understanding the AST</h3><p>The AST for our example looks conceptually like this:</p><pre>CompilationUnit<br>        │<br>        ├── ClassDeclaration<br>        │       │<br>        │       └── UserService<br>        │<br>        └── MethodDeclaration<br>                │<br>                ├── VariableDeclaration<br>                │<br>                └── MethodCallExpression</pre><p>Notice something interesting.</p><p>The AST does <strong>not</strong> store formatting.</p><p>Whether your code uses two spaces, four spaces, or tabs, the AST remains exactly the same.</p><p>This makes static analysis independent of formatting.</p><h3>Why Is the AST So Powerful?</h3><p>Suppose we want to detect every use of:</p><pre>System.out.println()</pre><p>We could search for the text &quot;println&quot;.</p><p>But what happens here?</p><pre>String text = &quot;System.out.println&quot;;</pre><p>A simple text search would incorrectly report this as a violation.</p><p>An AST-based analyzer understands that this is merely a string literal — not a method invocation.</p><p>This is why professional tools rely on parsing instead of regular expressions.</p><h3>Every Rule Starts With the AST</h3><p>Once the AST has been created, every rule follows the same pattern.</p><pre>Visit Node</pre><pre>↓</pre><pre>Inspect Node</pre><pre>↓</pre><pre>Condition Matches?</pre><pre>↓</pre><pre>Create Violation</pre><p>Whether you’re checking:</p><ul><li>Empty catch blocks</li><li>Naming conventions</li><li>Unused variables</li><li>Long methods</li></ul><p>Everything begins by visiting AST nodes.</p><h3>Where We’re Heading Next</h3><p>So far, our analyzer can:</p><p>✅ Parse Java source code</p><p>✅ Build an AST</p><p>The next logical step is to inspect that tree.</p><p>In <strong>Part 4</strong>, we’ll implement our first visitor and write a real static analysis rule that detects System.out.println() calls.</p><p>This will be the first time our analyzer behaves like a real PMD rule.</p><h3>Final Thoughts</h3><p>Parsing is the foundation of every static analysis tool.</p><p>Without a parser, code is just text.</p><p>With a parser, code becomes a structured tree that software can understand, navigate, and analyze.</p><p>This single transformation — from source code to an Abstract Syntax Tree — is what makes tools like PMD, Checkstyle, and many IDE inspections possible.</p><p>Now that we can build an AST, we’re finally ready to start writing rules — the heart of every static code analyzer.</p><p>#Java #PMD #StaticAnalysis #CodeQuality #BackendDevelopment #SoftwareEngineering #JavaDeveloper #Maven #CleanCode #DeveloperTools #OpenSource #AST #Programming #TechCommunity</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9e3c2227f246" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building Our Own PMD (Programming Mistake Detector) — Part 2: Designing a Static Code Analyzer]]></title>
            <link>https://medium.com/@arjun.devb25/building-our-own-pmd-programming-mistake-detector-part-2-designing-a-static-code-analyzer-21a85e04a302?source=rss-f027b3325552------2</link>
            <guid isPermaLink="false">https://medium.com/p/21a85e04a302</guid>
            <category><![CDATA[java]]></category>
            <category><![CDATA[clean-code]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[static-analysis]]></category>
            <dc:creator><![CDATA[Arjun Singh]]></dc:creator>
            <pubDate>Wed, 22 Jul 2026 09:45:33 GMT</pubDate>
            <atom:updated>2026-07-22T09:45:33.517Z</atom:updated>
            <content:encoded><![CDATA[<h3>Building Our Own PMD — Part 2: Designing a Static Code Analyzer</h3><p>In the first part of this series, we explored what <strong>PMD (Programming Mistake Detector)</strong> is and how it performs <strong>static code analysis</strong> without executing a Java application.</p><p>We learned that PMD parses Java source code into an <strong>Abstract Syntax Tree (AST)</strong> and evaluates it against a collection of rules to identify code quality issues.</p><p>Now it’s time to answer a more interesting question:</p><blockquote><strong><em>If we wanted to build our own static code analyzer, where would we begin?</em></strong></blockquote><p>Rather than jumping directly into writing code, this article focuses on the architecture behind a static analysis tool. Understanding these building blocks makes it much easier to appreciate how tools like PMD are designed.</p><h3>What Does a Static Analyzer Actually Do?</h3><p>At a high level, every static analyzer follows the same workflow:</p><pre>Java Source Code<br>        │<br>        ▼<br>Lexical &amp; Syntax Parsing<br>        │<br>        ▼<br>Abstract Syntax Tree (AST)<br>        │<br>        ▼<br>Rule Engine<br>        │<br>        ▼<br>Violation Report</pre><p>Although the implementation details vary, this pipeline is common across tools such as PMD, Checkstyle, SpotBugs, and many IDE inspections.</p><p>Let’s break down each stage.</p><h3>Step 1: Reading the Source Code</h3><p>Everything begins with a Java source file.</p><pre>public class UserService {</pre><pre>    public void saveUser() {<br>        System.out.println(&quot;Saving user&quot;);<br>    }<br>}</pre><p>At this stage, the analyzer simply sees a text file.</p><p>It doesn’t understand classes, methods, or variables yet.</p><p>The first challenge is transforming plain text into something a program can understand.</p><h3>Step 2: Parsing the Code</h3><p>This is the responsibility of the <strong>parser</strong>.</p><p>A parser validates the Java syntax and constructs an internal representation of the program.</p><p>Instead of treating the source code as text, it recognizes language constructs such as:</p><ul><li>Classes</li><li>Interfaces</li><li>Methods</li><li>Variables</li><li>Loops</li><li>Conditions</li><li>Expressions</li><li>Method invocations</li></ul><p>Most Java-based analyzers rely on an existing parser rather than implementing one from scratch.</p><p>Popular options include:</p><ul><li>JavaParser</li><li>Eclipse JDT</li><li>OpenJDK Compiler (javac APIs)</li></ul><p>For this series, we’ll use <strong>JavaParser</strong> because it provides a clean API and exposes the Abstract Syntax Tree directly.</p><h3>Step 3: Building the Abstract Syntax Tree (AST)</h3><p>Once parsing succeeds, the source code becomes an <strong>Abstract Syntax Tree</strong>.</p><p>Consider this example:</p><pre>public class UserService {</pre><pre>    public void saveUser() {</pre><pre>        int total = 100;</pre><pre>        System.out.println(total);<br>    }<br>}</pre><p>The AST looks conceptually like this:</p><pre>CompilationUnit<br>        │<br>        ├── ClassDeclaration<br>        │       │<br>        │       └── UserService<br>        │<br>        └── MethodDeclaration<br>                │<br>                ├── VariableDeclaration<br>                │<br>                └── MethodCallExpression</pre><p>Notice that comments, spaces, and formatting disappear.</p><p>The AST captures the <strong>structure</strong> of the program rather than its appearance.</p><p>This is one of the key reasons static analysis is reliable.</p><p>Searching for &quot;println&quot; using regular expressions would produce many false positives.</p><p>Searching an AST for a MethodCallExpression named println is much more precise.</p><h3>Step 4: Traversing the AST</h3><p>Once the AST is available, the analyzer needs to inspect every relevant node.</p><p>This is typically implemented using the <strong>Visitor Pattern</strong>.</p><p>Instead of manually navigating every child node, a visitor walks through the tree automatically.</p><p>Conceptually:</p><pre>CompilationUnit</pre><pre>↓</pre><pre>Visit Class</pre><pre>↓</pre><pre>Visit Method</pre><pre>↓</pre><pre>Visit Variable</pre><pre>↓</pre><pre>Visit Method Call</pre><pre>↓</pre><pre>Visit Catch Block</pre><p>Each visit gives the analyzer an opportunity to evaluate a rule.</p><p>This design keeps the traversal logic separate from the rule logic, making the analyzer much easier to maintain.</p><h3>Step 5: Designing the Rule Engine</h3><p>The Rule Engine is the heart of every static analysis tool.</p><p>Each rule answers a specific question about the source code.</p><p>Examples include:</p><ul><li>Is this variable ever used?</li><li>Is the catch block empty?</li><li>Is this method too complex?</li><li>Does this class violate our naming convention?</li><li>Is System.out.println() used in production code?</li></ul><p>Each rule operates independently.</p><p>Conceptually:</p><pre>AST</pre><pre>↓</pre><pre>Unused Variable Rule</pre><pre>↓</pre><pre>Empty Catch Rule</pre><pre>↓</pre><pre>Naming Rule</pre><pre>↓</pre><pre>Performance Rule</pre><pre>↓</pre><pre>Design Rule</pre><p>Since rules are independent, adding new rules does not require changing the parser.</p><p>This modular architecture is one of the reasons PMD has remained extensible for years.</p><h3>Step 6: Reporting Violations</h3><p>Whenever a rule detects an issue, it creates a violation.</p><p>A useful report generally contains:</p><ul><li>File name</li><li>Rule name</li><li>Line number</li><li>Description</li><li>Severity</li></ul><p>For example:</p><pre>UserService.java</pre><pre>Line 15</pre><pre>Rule : AvoidSystemOut</pre><pre>Severity : Warning</pre><pre>Message :<br>Avoid using System.out.println() in production code.</pre><p>Professional tools often support multiple output formats such as XML, HTML, JSON, and SARIF, making them easy to integrate with CI/CD pipelines and IDEs.</p><h3>Why Not Use Regular Expressions?</h3><p>A common question is:</p><blockquote><em>“Why can’t we simply search Java files using regex?”</em></blockquote><p>Consider the following code:</p><pre>String text = &quot;System.out.println&quot;;</pre><p>A regular expression searching for println would incorrectly report this as a violation.</p><p>Now consider:</p><pre>System.out.println(&quot;Hello&quot;);</pre><p>This is an actual method invocation.</p><p>A parser understands the difference because it recognizes the language grammar.</p><p>This is why every mature static analysis tool relies on parsing and AST traversal instead of plain text matching.</p><h3>Our Architecture</h3><p>The analyzer we’ll build throughout this series will have a simple but extensible architecture.</p><pre>                +------------------+<br>                | Java Source File |<br>                +------------------+<br>                          |<br>                          v<br>                +------------------+<br>                |    JavaParser    |<br>                +------------------+<br>                          |<br>                          v<br>                +------------------+<br>                |       AST        |<br>                +------------------+<br>                          |<br>                          v<br>                +------------------+<br>                |   Rule Engine    |<br>                +------------------+<br>                 |       |        |<br>                 |       |        |<br>                 v       v        v<br>             Rule1   Rule2   Rule3<br>                 \      |      /<br>                  \     |     /<br>                   v    v    v<br>               Violation Report</pre><p>As the project grows, adding new rules becomes straightforward because the parser and reporting components remain unchanged.</p><h3>What’s Next?</h3><p>Now that we’ve designed the architecture, we’re finally ready to write some code.</p><p>In the next article, we’ll create a Maven project, integrate <strong>JavaParser</strong>, parse a real Java source file, and inspect the generated AST.</p><p>From there, we’ll implement our first custom rule and begin building a functional static code analyzer.</p><h3>Final Thoughts</h3><p>Building a static analyzer isn’t about searching source code for keywords.</p><p>It’s about understanding the structure of a programming language, representing that structure as an Abstract Syntax Tree, and applying well-defined rules to it.</p><p>Once you understand these building blocks, tools like PMD become much less mysterious. Instead of seeing them as black boxes, you begin to recognize the engineering patterns that power modern IDEs, compilers, and code quality platforms.</p><p>In the next part of this series, we’ll move from architecture to implementation and start building our analyzer one component at a time.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=21a85e04a302" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[ Building Our Own PMD — Part 1: Understanding How Static Code Analysis Works]]></title>
            <link>https://medium.com/@arjun.devb25/building-our-own-pmd-part-1-understanding-how-static-code-analysis-works-786823361f60?source=rss-f027b3325552------2</link>
            <guid isPermaLink="false">https://medium.com/p/786823361f60</guid>
            <category><![CDATA[developer-tools]]></category>
            <category><![CDATA[clean-code]]></category>
            <category><![CDATA[backend-engineering]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[development]]></category>
            <dc:creator><![CDATA[Arjun Singh]]></dc:creator>
            <pubDate>Sat, 18 Jul 2026 14:34:26 GMT</pubDate>
            <atom:updated>2026-07-18T14:34:26.926Z</atom:updated>
            <content:encoded><![CDATA[<p>Have you ever run a Maven build and seen something like this?</p><pre>[ERROR] Failed to execute goal org.apache.maven.plugins:maven-pmd-plugin</pre><p>Your project compiles successfully, your tests pass, yet the build still fails because of <strong>PMD</strong>.</p><p>At first, this can be frustrating.</p><p>But then a question naturally comes to mind:</p><blockquote><strong><em>How does PMD know my code has a problem without even running my application?</em></strong></blockquote><p>That’s exactly what we’ll explore in this series.</p><p>In this first part, we’ll understand <strong>what PMD is, how it works internally, and why static code analysis has become an essential part of modern software development.</strong></p><h3>What is PMD?</h3><p><strong>PMD (Programming Mistake Detector)</strong> is an open-source <strong>static code analysis</strong> tool that scans your source code and reports potential issues <strong>without executing the program</strong>.</p><p>Unlike the Java compiler, which checks whether your code is syntactically correct, PMD focuses on identifying code quality issues such as:</p><ul><li>Unused variables</li><li>Empty catch blocks</li><li>Long or overly complex methods</li><li>Duplicate code</li><li>Poor design practices</li><li>Performance issues</li><li>Maintainability concerns</li></ul><p>Think of it as an automated code reviewer that never gets tired.</p><h3>Compiler vs PMD</h3><p>Many developers assume that if their code compiles successfully, everything is fine.</p><p>Not necessarily.</p><p>Consider this example:</p><pre>public void processOrder() {<br>    int totalAmount = 100;<br>}</pre><p>The Java compiler accepts this code because it’s valid Java.</p><p>However, PMD reports:</p><blockquote><strong><em>Unused Local Variable</em></strong></blockquote><p>The application works, but the code contains unnecessary logic that should be cleaned up.</p><p>This highlights an important distinction:</p><p>Java CompilerPMDChecks syntaxChecks code qualityProduces bytecodeProduces quality reportsRequired to run the applicationOptional but highly recommendedFinds compilation errorsFinds maintainability and design issues</p><p>Both tools have different responsibilities.</p><h3>Static Analysis vs Runtime Analysis</h3><p>When your application runs, the JVM executes the compiled bytecode.</p><pre>Java Source Code<br>        │<br>        ▼<br>Java Compiler<br>        │<br>        ▼<br>Bytecode (.class)<br>        │<br>        ▼<br>JVM Execution</pre><p>PMD follows a completely different path.</p><pre>Java Source Code<br>        │<br>        ▼<br>Source Code Parser<br>        │<br>        ▼<br>Abstract Syntax Tree (AST)<br>        │<br>        ▼<br>Rule Engine<br>        │<br>        ▼<br>Violation Report</pre><p>Notice something interesting.</p><p>The application never starts.</p><p>No bytecode is executed.</p><p>PMD only understands the structure of your source code.</p><h3>The Secret Behind PMD: Abstract Syntax Tree (AST)</h3><p>The real power of PMD comes from the <strong>Abstract Syntax Tree</strong>, commonly called an <strong>AST</strong>.</p><p>Imagine writing:</p><pre>public class UserService {</pre><pre>    public void save() {<br>        System.out.println(&quot;Saving...&quot;);<br>    }<br>}</pre><p>We see plain text.</p><p>PMD doesn’t.</p><p>It transforms the code into a tree-like structure.</p><pre>CompilationUnit<br>      │<br>      ├── ClassDeclaration<br>      │        │<br>      │        ├── UserService<br>      │<br>      └── MethodDeclaration<br>               │<br>               └── MethodCall<br>                        │<br>                        └── println()</pre><p>Instead of searching for text patterns, PMD walks through this tree and inspects each node.</p><p>This makes the analysis much more reliable than simple string matching.</p><h3>What Exactly Is a Rule?</h3><p>A rule is simply a condition applied to the AST.</p><p>For example:</p><pre>IF</pre><pre>Variable is declared</pre><pre>AND</pre><pre>Variable is never used</pre><pre>THEN</pre><pre>Report violation</pre><p>Another example:</p><pre>IF</pre><pre>Catch block is empty</pre><pre>THEN</pre><pre>Report violation</pre><p>Every warning you see from PMD is produced by one of these rules.</p><h3>Why Do Companies Use PMD?</h3><p>Imagine a project with:</p><ul><li>500 developers</li><li>Millions of lines of Java code</li><li>Hundreds of pull requests every day</li></ul><p>Reviewers should spend their time discussing:</p><ul><li>Architecture</li><li>Business logic</li><li>Scalability</li><li>Security</li></ul><p>— not repeatedly pointing out:</p><ul><li>Remove unused variables.</li><li>Don’t swallow exceptions.</li><li>Reduce method complexity.</li><li>Avoid duplicate code.</li></ul><p>PMD automates these repetitive checks, allowing engineers to focus on solving business problems instead of enforcing basic coding standards.</p><h3>Can We Build Our Own PMD?</h3><p>Absolutely.</p><p>At its core, every static analysis tool consists of four building blocks:</p><ol><li>A parser that understands source code.</li><li>An Abstract Syntax Tree (AST).</li><li>A rule engine that evaluates the AST.</li><li>A reporting mechanism that displays violations.</li></ol><p>This architecture is surprisingly approachable once you understand the fundamentals.</p><p>In the next article, we’ll start building a <strong>mini PMD</strong> ourselves and explore how to parse Java code into an AST using JavaParser.</p><h3>What’s Coming Next?</h3><p>In <strong>Part 2</strong>, we’ll stop discussing theory and start writing code.</p><p>We’ll build a simple static analyzer that can:</p><ul><li>Parse Java source files</li><li>Traverse an AST</li><li>Detect unused variables</li><li>Identify empty catch blocks</li><li>Generate a basic violation report</li></ul><p>By the end of the series, you’ll have a working understanding of how professional static analysis tools like PMD are designed under the hood.</p><h3>Final Thoughts</h3><p>Understanding PMD isn’t just about learning another build tool.</p><p>It’s about understanding how modern developer tools “read” your code.</p><p>Once you grasp concepts like parsing, ASTs, and rule engines, you’ll begin to see the foundations behind IDE inspections, linters, security scanners, and even parts of modern compilers.</p><p>Sometimes the best way to appreciate a tool isn’t just to use it — it’s to understand how it’s built.</p><p><strong>Stay tuned for Part 2, where we’ll start building our own mini PMD from scratch.</strong></p><p>#Java #PMD #StaticAnalysis #CodeQuality #BackendDevelopment #SoftwareEngineering #JavaDeveloper #Maven #CleanCode #DeveloperTools #OpenSource #AST #Programming #TechCommunity</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=786823361f60" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Adaptive Bitrate Streaming Explained: How Video Platforms Deliver Smooth Playback at Scale]]></title>
            <link>https://medium.com/@arjun.devb25/adaptive-bitrate-streaming-explained-how-video-platforms-deliver-smooth-playback-at-scale-2645418e84fa?source=rss-f027b3325552------2</link>
            <guid isPermaLink="false">https://medium.com/p/2645418e84fa</guid>
            <category><![CDATA[software-architecture]]></category>
            <category><![CDATA[system-design-interview]]></category>
            <category><![CDATA[video-streaming-service]]></category>
            <category><![CDATA[abs]]></category>
            <category><![CDATA[backend-engineering]]></category>
            <dc:creator><![CDATA[Arjun Singh]]></dc:creator>
            <pubDate>Mon, 22 Dec 2025 18:26:54 GMT</pubDate>
            <atom:updated>2025-12-22T18:26:54.279Z</atom:updated>
            <content:encoded><![CDATA[<h3>Introduction</h3><p>Have you ever noticed that a video starts playing instantly, even on a slow network, and then automatically improves its quality when your internet becomes faster?</p><p>This smooth experience is not magic — it is the result of a well-designed system called <strong>Adaptive Bitrate Streaming (ABR)</strong>. Modern platforms like TikTok, YouTube, Netflix, and Instagram rely heavily on this technique to deliver seamless video playback across millions of devices and network conditions.</p><p>In this article, we will explore <strong>what Adaptive Bitrate Streaming is, why it is required, how it works internally, and why it is a critical concept in system design interviews</strong>.</p><h3>The Problem with Traditional Video Streaming</h3><p>Earlier video streaming systems used a <strong>single video file</strong> for all users.</p><h3>Why did this fail?</h3><ul><li>High-quality videos caused buffering on slow networks</li><li>Low-end devices struggled to decode large video files</li><li>Startup time was high</li><li>One video quality could not satisfy all users</li></ul><h3>Example</h3><p>A 4K video might work perfectly on a high-end phone with fast Wi-Fi but would be completely unwatchable on a budget phone using mobile data.</p><p>This limitation created the need for a smarter and adaptive approach.</p><h3>What Is Adaptive Bitrate Streaming?</h3><p><strong>Adaptive Bitrate Streaming</strong> is a video delivery technique where the same video is available in <strong>multiple versions</strong>, each with different:</p><ul><li>Resolutions</li><li>Bitrates</li><li>Encodings</li></ul><p>The video player dynamically selects the most suitable version <strong>in real time</strong> based on:</p><ul><li>Internet speed</li><li>Device performance</li><li>Screen resolution</li><li>Network stability</li></ul><p>The primary goal is simple:</p><blockquote><em>Deliver the best possible video quality without buffering.</em></blockquote><h3>Why Adaptive Bitrate Streaming Is Necessary</h3><p>Modern video platforms must support:</p><ul><li>Millions of users</li><li>Different device types</li><li>Highly variable network conditions</li></ul><p>Adaptive Bitrate Streaming solves these challenges by:</p><ul><li>Adjusting quality dynamically</li><li>Preventing playback interruptions</li><li>Optimizing bandwidth usage</li><li>Improving overall user experience</li></ul><p>Without ABR, smooth video streaming at global scale would not be feasible.</p><h3>What Happens When You Upload a Video?</h3><p>When a creator uploads a video, platforms do far more than just store it.</p><h3>Step 1: Original Upload</h3><p>The raw video file is uploaded and stored temporarily.</p><h3>Step 2: Transcoding</h3><p>The video is converted into multiple resolutions such as:</p><ul><li>144p, 240p, 360p</li><li>480p, 720p</li><li>1080p, 4K</li></ul><p>Each resolution has a corresponding <strong>bitrate</strong>, controlling how much data is streamed per second.</p><h3>Step 3: Multiple Formats</h3><p>To support different browsers and devices, the video may be encoded into formats such as:</p><ul><li>H.264</li><li>H.265 (HEVC)</li><li>VP9 or AV1</li></ul><h3>Step 4: Chunking</h3><p>Each video version is split into small segments, usually <strong>2–6 seconds long</strong>.<br>These segments are streamed instead of a single large file.</p><h3>How Adaptive Bitrate Streaming Works During Playback</h3><p>When a user presses “Play”:</p><ol><li>The player evaluates network speed and device capability</li><li>Playback starts with a low-quality segment to avoid buffering</li><li>As conditions improve, higher-quality segments are requested</li><li>If the network degrades, the player switches to lower quality</li></ol><p>This switching happens <strong>seamlessly</strong>, without stopping the video.</p><p>The user experiences smooth playback without being aware of these transitions.</p><h3>Why Videos Are Streamed in Chunks</h3><p>Chunk-based delivery provides several benefits:</p><ul><li>Faster startup time</li><li>Seamless quality switching</li><li>Reduced memory usage</li><li>Fault tolerance during network drops</li></ul><p>Instead of downloading an entire video, the player only fetches what it needs next.</p><h3>Role of Content Delivery Networks (CDNs)</h3><p>After processing, video segments are distributed across <strong>Content Delivery Networks (CDNs)</strong>.</p><h3>Why CDNs matter:</h3><ul><li>Content is served from nearby locations</li><li>Latency is reduced</li><li>Load is distributed efficiently</li><li>Scalability is improved during traffic spikes</li></ul><p>CDNs are essential for delivering video reliably at scale.</p><h3>Popular Adaptive Streaming Protocols</h3><p>Adaptive Bitrate Streaming is implemented using industry standards:</p><ul><li><strong>HLS (HTTP Live Streaming)</strong> — widely used and Apple-supported</li><li><strong>MPEG-DASH</strong> — open standard with high flexibility</li></ul><p>Both protocols rely on:</p><ul><li>Manifest files</li><li>Chunk-based delivery</li><li>Standard HTTP requests</li></ul><h3>Real-World Example</h3><p>Imagine watching a video while commuting:</p><ul><li>Inside metro → slow network → 360p</li><li>Outside station → better network → 720p</li><li>Home Wi-Fi → fast network → 1080p</li></ul><p>The quality changes automatically without stopping playback.</p><p>This is Adaptive Bitrate Streaming in action.</p><h3>Key Benefits of Adaptive Bitrate Streaming</h3><ul><li>Smooth and uninterrupted playback</li><li>Minimal buffering</li><li>Efficient bandwidth usage</li><li>Device-aware video delivery</li><li>Highly scalable architecture</li></ul><p>From both user experience and backend design perspectives, ABR is indispensable.</p><h3>System Design Perspective</h3><p>From a system design viewpoint, Adaptive Bitrate Streaming involves:</p><ul><li>Media processing pipelines</li><li>Distributed object storage</li><li>CDN-based delivery</li><li>Intelligent client-side logic</li><li>Monitoring and optimization systems</li></ul><p>It is a perfect example of how strong backend design directly improves user experience.</p><h3>System Design Interview Notes</h3><p>Adaptive Bitrate Streaming is a <strong>high-frequency topic</strong> in system design interviews, especially for video platforms.</p><h3>Why Do We Need Adaptive Bitrate Streaming?</h3><p>To handle varying network conditions and device capabilities while ensuring smooth playback.</p><h3>Problems Solved by ABR</h3><ul><li>Network fluctuations</li><li>Device diversity</li><li>High startup latency</li><li>Buffering during playback</li><li>Inefficient bandwidth usage</li></ul><h3>High-Level Design Flow</h3><ol><li>User uploads video</li><li>Video is temporarily stored</li><li>Transcoding generates multiple qualities</li><li>Video is chunked into segments</li><li>Segments are stored and distributed via CDN</li><li>Client dynamically selects quality</li></ol><h3>Key Components</h3><ul><li>Upload Service</li><li>Transcoding Pipeline</li><li>Object Storage</li><li>CDN</li><li>Adaptive Video Player</li><li>Monitoring and Analytics</li></ul><h3>Why Is Chunking Important?</h3><p>Chunking enables fast startup, adaptive switching, and fault tolerance during unstable networks.</p><h3>Why Are CDNs Required?</h3><p>CDNs reduce latency, improve availability, and support large-scale concurrent traffic.</p><h3>HLS vs MPEG-DASH (High Level)</h3><p>AspectHLSDASHStandardApple-drivenOpen standardCompatibilityVery highPlatform-agnosticFlexibilityModerateHigh</p><h3>Common Interview Follow-Up Questions</h3><ul><li>How would you reduce video storage cost?</li><li>How would you support millions of concurrent viewers?</li><li>How do you monitor video quality?</li><li>How does ABR impact backend scalability</li></ul><h3>Conclusion</h3><p>Adaptive Bitrate Streaming is one of the most important technologies behind modern video platforms.</p><p>A video is uploaded once, processed intelligently, and delivered optimally to users across different devices and network conditions.</p><p>For engineers and system designers, understanding ABR provides deep insight into how large-scale media systems are built and optimized today.</p><h3>Final Thought</h3><p>The next time a video adjusts its quality without you noticing, remember — <br>that seamless experience is the result of carefully designed systems working together in real time.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2645418e84fa" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Profiling in Golang: A Practical Guide with JSON Processing Example]]></title>
            <link>https://medium.com/@arjun.devb25/profiling-in-golang-a-practical-guide-with-json-processing-example-af02433122b4?source=rss-f027b3325552------2</link>
            <guid isPermaLink="false">https://medium.com/p/af02433122b4</guid>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[systems-thinking]]></category>
            <category><![CDATA[golang]]></category>
            <category><![CDATA[backend-development]]></category>
            <category><![CDATA[design-thinking]]></category>
            <dc:creator><![CDATA[Arjun Singh]]></dc:creator>
            <pubDate>Mon, 01 Sep 2025 18:04:08 GMT</pubDate>
            <atom:updated>2025-09-01T18:04:08.585Z</atom:updated>
            <content:encoded><![CDATA[<p>When building Go applications, performance issues are not always obvious. Your code might look clean and efficient, but under production load, you may suddenly face <strong>high CPU usage</strong>, <strong>increased memory consumption</strong>, or <strong>slow response times</strong>.</p><p>Even senior developers sometimes struggle to identify these bottlenecks. The reason? Performance problems rarely come from the place you expect.</p><p>This is where <strong>profiling in Go</strong> comes in — giving you data-driven insights into how your program behaves in real-world conditions.</p><h3>What is Profiling?</h3><p><strong>Profiling</strong> is the process of collecting runtime statistics about your program. It answers questions like:</p><ul><li>Which functions consume the most CPU time?</li><li>Where is memory being allocated?</li><li>How many goroutines are running, and why are some blocked?</li></ul><p>Go ships with <strong>pprof</strong>, a built-in profiling and performance analysis tool that helps you visualize this data.</p><h3>Types of Profiles in Go</h3><ul><li><strong>CPU Profile</strong> → Shows where your program spends most CPU cycles.</li><li><strong>Heap (Memory) Profile</strong> → Tracks memory allocations and usage.</li><li><strong>Goroutine Profile</strong> → Captures the state of all goroutines.</li><li><strong>Block &amp; Mutex Profiles</strong> → Show contention and blocking issues.</li></ul><h3>Example: JSON Processing API</h3><p>Imagine we’re building a service that accepts a JSON payload and transforms it into a different structure before returning it.</p><h3>Step 1: Service Implementation</h3><pre>package main<br>import (<br>    &quot;encoding/json&quot;<br>    &quot;log&quot;<br>    &quot;net/http&quot;<br>    _ &quot;net/http/pprof&quot; // Enables profiling endpoints<br>)<br>type Input struct {<br>    Name    string `json:&quot;name&quot;`<br>    Age     int    `json:&quot;age&quot;`<br>    Country string `json:&quot;country&quot;`<br>}<br>type Output struct {<br>    Username string `json:&quot;username&quot;`<br>    Adult    bool   `json:&quot;adult&quot;`<br>    Location string `json:&quot;location&quot;`<br>}<br>func transformHandler(w http.ResponseWriter, r *http.Request) {<br>    var input Input<br>    if err := json.NewDecoder(r.Body).Decode(&amp;input); err != nil {<br>        http.Error(w, &quot;Invalid JSON&quot;, http.StatusBadRequest)<br>        return<br>    }<br>    // Simulate some &quot;heavy&quot; computation<br>    for i := 0; i &lt; 500000; i++ {<br>        _ = i * 2 // Dummy loop for CPU load<br>    }<br>    output := Output{<br>        Username: input.Name,<br>        Adult:    input.Age &gt;= 18,<br>        Location: input.Country,<br>    }<br>    w.Header().Set(&quot;Content-Type&quot;, &quot;application/json&quot;)<br>    json.NewEncoder(w).Encode(output)<br>}<br>func main() {<br>    http.HandleFunc(&quot;/transform&quot;, transformHandler)<br>    log.Println(&quot;Server running at :8080&quot;)<br>    log.Fatal(http.ListenAndServe(&quot;:8080&quot;, nil))<br>}</pre><p>Run it:</p><pre>go run main.go</pre><p>Now POST some JSON:</p><pre>curl -X POST http://localhost:8080/transform \<br>-H &quot;Content-Type: application/json&quot; \<br>-d &#39;{&quot;name&quot;:&quot;Arjun&quot;,&quot;age&quot;:25,&quot;country&quot;:&quot;India&quot;}&#39;</pre><h3>Step 2: Enabling Profiling</h3><p>Because we imported net/http/pprof, profiling endpoints are automatically available at:</p><ul><li>debug/pprof/profile (CPU profile)</li><li>/debug/pprof/heap (memory usage)</li><li>/debug/pprof/goroutine (goroutines dump)</li></ul><p>Example: capture a 20-second CPU profile</p><pre>curl -o cpu.pprof &quot;http://localhost:8080/debug/pprof/profile?seconds=20&quot;</pre><h3>Step 3: Analyzing the Profile</h3><p>Run:</p><pre>go tool pprof cpu.pprof</pre><p>Inside the shell:</p><ul><li>top → Shows functions consuming CPU.</li><li>list transformHandler → Zoom into a specific function.</li><li>web → Generate a flame graph in your browser.</li></ul><p>Example top output:</p><pre>Showing nodes accounting for 3.50s, 87.50% of 4.00s total<br>      flat  flat%   sum%        cum   cum%<br>     2.50s 62.50% 62.50%      2.50s 62.50%  main.transformHandler<br>     1.00s 25.00% 87.50%      1.00s 25.00%  runtime.memmove</pre><p>This clearly shows that most CPU is wasted inside the loop in transformHandler.</p><h3>Step 4: Optimizing the Service</h3><p>Let’s remove the dummy loop and make transformations efficient:</p><pre>// Remove heavy loop<br>output := Output{<br>    Username: input.Name,<br>    Adult:    input.Age &gt;= 18,<br>    Location: input.Country,<br>}</pre><p>Re-run profiling, and the CPU hot path disappears 🎉</p><h3>Step 5: Profile-Guided Optimization (PGO)</h3><p>Starting with Go 1.20, we can feed real profiling data back into the compiler so it can optimize <strong>based on actual production usage</strong>.</p><ol><li>Collect a profile:</li></ol><pre>curl -o cpu.pprof &quot;http://localhost:8080/debug/pprof/profile?seconds=30&quot;</pre><p>2. Save it as default.pgo:</p><ul><li>mv cpu.pprof default.pgo</li></ul><p>3 .Rebuild:</p><ul><li>go build -pgo=auto -o json_service</li></ul><p>Benchmarks typically show <strong>2–5% performance improvements</strong> automatically.</p><h3>Why Developers Struggle with Profiling</h3><ol><li><strong>Too much data</strong> → pprof outputs can look overwhelming.</li><li><strong>Wrong environment</strong> → profiling locally vs profiling under real production traffic gives different results.</li><li><strong>Short capture windows</strong> → a 2-second profile often misses real bottlenecks.</li><li><strong>Misinterpretation</strong> → not every hot function needs optimization; sometimes that’s just where the app is supposed to spend time.</li></ol><h3>Best Practices</h3><p>✅ Profile under realistic load (use hey or wrk to simulate traffic).<br> ✅ Always capture <strong>CPU + Heap + Goroutine profiles</strong> together.<br> ✅ Keep profiles for historical comparison.<br> ✅ Use <strong>PGO</strong> and commit default.pgo to version control.<br> ✅ Benchmark before and after changes.</p><h3>Conclusion</h3><p>Profiling is not just about fixing “slow code.” It’s about understanding <em>how your Go program behaves in production</em>. With Go’s built-in <strong>pprof</strong> and <strong>PGO</strong>, you can identify bottlenecks, optimize critical paths, and continuously improve performance.</p><p>Mastering profiling is one of the skills that separates intermediate Go developers from true experts.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=af02433122b4" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>