<?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 Vikash Gupta on Medium]]></title>
        <description><![CDATA[Stories by Vikash Gupta on Medium]]></description>
        <link>https://medium.com/@hiimvikash?source=rss-6530c2ff5590------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*yFEQKICoZtqVEb4LTu4QWg.png</url>
            <title>Stories by Vikash Gupta on Medium</title>
            <link>https://medium.com/@hiimvikash?source=rss-6530c2ff5590------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 24 Nov 2026 13:28:51 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@hiimvikash/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[4. What Guarantees Does a Kafka Producer Actually Provide?]]></title>
            <link>https://hiimvikash.medium.com/4-what-guarantees-does-a-kafka-producer-actually-provide-3426a6cdd6ee?source=rss-6530c2ff5590------2</link>
            <guid isPermaLink="false">https://medium.com/p/3426a6cdd6ee</guid>
            <category><![CDATA[event-driven-architecture]]></category>
            <category><![CDATA[distributed-systems]]></category>
            <category><![CDATA[microservices]]></category>
            <category><![CDATA[apache-kafka]]></category>
            <category><![CDATA[kafka]]></category>
            <dc:creator><![CDATA[Vikash Gupta]]></dc:creator>
            <pubDate>Sat, 14 Nov 2026 13:42:48 GMT</pubDate>
            <atom:updated>2026-11-14T13:42:48.357Z</atom:updated>
            <content:encoded><![CDATA[<p>In the last three blogs, we started with a problem and gradually discovered why we need a messaging system and how Kafka helps us solve it.</p><p>We understood topics, partitions, brokers, replication, consumer groups, and offsets. We also saw how these pieces fit together to form Kafka’s basic architecture.</p><p>But so far, we’ve mostly looked at Kafka from the outside.</p><p>Now, let’s take a step inside from <strong>Producers side </strong>and understand<strong>: How does data enter Kafka?</strong></p><p>Imagine we have our ShopNow application. Whenever a customer places an order, our order service creates an OrderCreated event and sends it to Kafka.</p><p>Something like this:</p><pre>{<br>  &quot;event&quot;: &quot;OrderCreated&quot;,<br>  &quot;orderId&quot;: &quot;ORD-101&quot;,<br>  &quot;customerId&quot;: &quot;CUST-42&quot;,<br>  &quot;amount&quot;: 1499<br>}</pre><p>Our application has created the event. We know that Kafka has topics and partitions where these events can be stored.</p><p>But <strong>what actually happens after our application decides to send this event to Kafka?</strong></p><ul><li>Does the producer send it to any broker?</li><li>How does it decide which partition should store the event?</li><li>Should it send every event immediately, or collect multiple events and send them together?</li><li>And what happens if Kafka stores the event, but our producer never receives the response?</li></ul><p>Let’s imagine we are building this mechanism ourselves and discover what problems we would face.</p><h3>1. How Does the Producer Know Which Broker to Contact?</h3><p>Let’s begin with something we already know.</p><p>A Kafka cluster can have multiple brokers. A topic can have multiple partitions, and each partition has a leader broker responsible for handling writes.</p><p>Suppose our orders topic has three partitions distributed across three brokers.</p><p>For simplicity, imagine the leaders are arranged like this:</p><pre>┌──────────────────────────────────────────────┐<br>│                Kafka Cluster                 │<br>│                                              │<br>│  ┌─────────────────┐  ┌─────────────────┐    │<br>│  │    Broker 1     │  │    Broker 2     │    │<br>│  │                 │  │                 │    │<br>│  │  Partition 0    │  │  Partition 1    │    │<br>│  │  Leader         │  │  Leader         │    │<br>│  │                 │  │                 │    │<br>│  │  Follower: P1   │  │  Follower: P0   │    │<br>│  └─────────────────┘  └─────────────────┘    │<br>│                                              │<br>│              ┌─────────────────┐             │<br>│              │    Broker 3     │             │<br>│              │                 │             │<br>│              │  Partition 2    │             │<br>│              │  Leader         │             │<br>│              │                 │             │<br>│              │  Follower: P1   │             │<br>│              └─────────────────┘             │<br>└──────────────────────────────────────────────┘</pre><p>Now, our order service wants to send the OrderCreated event. Which broker should it contact? remember what we learned in the previous blog.</p><p><strong>A write to a partition must go through that partition’s leader.</strong></p><p>If our event belongs to Partition 1, Broker 2 is the broker responsible for handling that write. <strong>So, our producer needs to know which broker leads the partition it wants to write to.</strong></p><p>But wait. How does the producer learn about the brokers and partitions in the first place?</p><p>After all, our producer cannot magically know which broker is responsible for a particular partition. It needs some information about the Kafka cluster before it can send an event.</p><h4>How does the producer discover the cluster?</h4><p>Let’s think about what Kafka needs to keep track of.</p><p>Imagine we have a Kafka cluster with three brokers. Our orders topic has three partitions, and each partition has a leader.</p><p>Now, Kafka needs to maintain information such as:</p><ul><li>Which topics exist in the cluster?</li><li>How many partitions does each topic have?</li><li>Which brokers host those partitions?</li><li>Which broker is currently the leader of each partition?</li></ul><p>This information is called <strong>cluster metadata</strong>. But here’s another question: <strong><em>Who is responsible for managing this metadata?</em></strong></p><p>Kafka needs a component that keeps track of the cluster’s structure and coordinates changes whenever something happens. like:</p><ul><li>When a new topic is created, its partition information needs to be recorded.</li><li>When a broker goes down, a new leader may need to be elected for its partitions.</li><li>When partition leadership changes, the cluster needs to know about the change.</li></ul><p>Kafka handles this responsibility through something called <strong>KRaft controllers</strong>. This are a group of nodes responsible for managing and coordinating changes to the cluster metadata. Think of them as the management team of a building, while brokers are the departments where the actual work happens.</p><p>In production, controllers can run on a separate set of servers from brokers. Kafka also allows both roles to run on the same machines.</p><p>Now, our next question is: <strong><em>If controllers manage the cluster metadata, does the producer connect directly to them to discover the cluster?</em></strong></p><p>No.</p><p>The producer gets this information through Kafka brokers.</p><p>But how does it know which broker to contact initially? That’s where bootstrap.servers comes in.</p><p>When configuring a Kafka producer, we provide it with a list of broker addresses:</p><pre>bootstrap.servers=broker1:9092, broker2:9092, broker3:9092</pre><p>These addresses are called <strong>bootstrap servers</strong>.</p><p>They are not a special type of server, nor are they the addresses of KRaft controllers. They are simply the initial broker addresses that the producer can use to connect to the Kafka cluster.</p><p>Think of them as the <strong>starting points for discovering the cluster.</strong></p><p>Let’s understand the complete flow.</p><pre>┌──────────────────────┐<br>│   KRaft Controllers  │<br>│                      │<br>│ Manage cluster       │<br>│ metadata             │<br>└──────────┬───────────┘<br>           │ Coordinate metadata changes<br>           ▼<br>┌──────────────────────┐<br>│    Kafka Brokers     │<br>│                      │<br>│  Broker 1            │<br>│  Broker 2            │<br>│  Broker 3            │<br>└──────────────────────┘<br><br><br>┌────────────┐   1. Initial connection    ┌────────────┐<br>│            │ ─────────────────────────► │            │<br>│  Producer  │                            │  Broker 1  │<br>│            │ ◄───────────────────────── │            │<br>└────────────┘   2. Cluster metadata      └────────────┘<br>                       response<br>      │<br>      │ 3. Identifies the target<br>      │    partition&#39;s leader<br>      ▼<br>┌────────────┐   4. Produce request<br>│            │ ─────────────────────────► ┌────────────┐<br>│  Producer  │                            │  Broker 2  │<br>│            │                            │            │<br>└────────────┘                            │ Partition  │<br>                                          │   Leader   │<br>                                          └────────────┘</pre><p>Let’s break this down:</p><ol><li>The producer connects to one reachable broker from the configured bootstrap.servers. It requests cluster metadata from that broker.</li><li>The broker provides information about topics, partitions, and their current leaders.</li><li>The producer identifies the leader of the partition where the event needs to go.</li><li>It sends the event directly to that partition’s leader.</li></ol><p>One important thing to understand here is that <strong>bootstrap servers are not central servers through which every event must pass</strong>.</p><p>They simply help the producer discover the cluster. Once the producer knows which broker leads the target partition, it can communicate directly with that broker.</p><p>Also, the producer doesn’t need to contact a bootstrap server every time it sends an event.</p><p><strong>Why? </strong>Because the producer caches the cluster metadata it receives and reuses it for subsequent sends. It refreshes that metadata when needed, such as when it becomes outdated or a request reveals that the partition leader has changed.</p><p>Think about what happens when Broker 2 goes down and it was the leader of Partition 1.</p><p>Kafka may elect another <strong><em>In-Sync-Replica</em></strong> as the new leader. But our producer might still believe Broker 2 is the leader because its cached metadata hasn’t been updated yet.</p><p>What happens then?</p><p>The producer might initially try sending the event to the old leader and encounter a connection failure or receive an error indicating that Broker 2 is no longer the leader.</p><p>It can then refresh its metadata and retry against the current leader, depending on the failure and retry behaviour.</p><p>So, the producer doesn’t need to know the cluster’s state perfectly at every moment. It needs a way to discover that state and recover when its information becomes outdated.</p><p>We’ve solved our first problem. Our producer now knows how to discover the cluster and find the broker responsible for its target partition.</p><p>But before we send the event, let’s think about another problem.</p><h3>2. Should We Send Every Event Immediately?</h3><p>Imagine ShopNow is receiving thousands of orders every second.</p><p>Every time an order is placed, our producer could immediately send a network request to Kafka. One event arrives, one request is sent. Another event arrives, another request is sent. And this continues thousands of times every second.</p><p>Would this work?</p><p>Yes. But let’s think about what happens when we send every event separately.</p><p>Every request has some overhead. We need to communicate with the broker, send the request, and handle the response.</p><p>Now, what if we could collect multiple events and send them together?</p><p>For example, instead of sending five events in five separate requests, we could group them into one batch.</p><pre>Event 1 ─┐<br>Event 2 ─┤<br>Event 3 ─┼──&gt; One Batch ───&gt; Kafka Broker<br>Event 4 ─┤<br>Event 5 ─┘</pre><p>This is the idea behind <strong>batching</strong>.</p><p>By sending multiple records together, we can reduce request overhead and use the network more efficiently. Even a small wait of 5 or 10 milliseconds can significantly improve throughput, because each network request can carry more messages.</p><p>But this introduces another question.</p><p><strong>How many events should we collect before sending a batch?</strong></p><p>Suppose we wait until we have 1,000 events.</p><p>That might help us send data efficiently, but the first event would have to wait for the other 999 events to arrive.</p><ul><li>What if the other events take a long time to arrive? Our first event would be unnecessarily delayed.</li><li>On the other hand, if we send every event immediately, we might not benefit much from batching.</li></ul><p>So, we need to balance two things:</p><ul><li><strong>Throughput:</strong> How much data can we send or process over a period of time?</li><li><strong>Latency:</strong> How long does an individual event take to move through the system?</li></ul><p>Kafka gives us configurations such as batch.size and linger.ms to manage this trade-off.</p><ul><li>batch.size controls the target size of a batch in bytes for a partition.</li><li>linger.ms allows the producer to wait briefly for more records to arrive before sending a batch that hasn&#39;t filled up.</li></ul><p>If a batch fills up before the waiting time expires, the producer can send it without waiting for the full linger period.</p><p>But there’s another detail we should understand.</p><p>Our producer might be sending events to multiple partitions. Should it mix records from all those partitions into one batch?</p><p>No. The producer maintains batches for individual partitions because each partition is an independent ordered log.</p><p>However, a single produce request can contain batches for multiple partitions led by the same broker. This lets the producer group network work efficiently while keeping each partition’s records separate.</p><h4>Can we make sending these batches even more efficient?</h4><p>Think about it. If our batch contains many records with similar data, we’re sending a lot of repeated information over the network.</p><p>Can we reduce the size of the batch before sending it?</p><p>Yes. Kafka supports <strong>compression</strong>.</p><p>The producer can compress the batch before sending it to Kafka. This reduces the amount of data that needs to travel over the network.</p><p>Of course, compression also takes some CPU time, so we need to balance network usage with the extra work required to compress and decompress the data.</p><p>Now, let’s think about another situation.</p><p>What if our application is producing events faster than Kafka can receive them?</p><p>The producer cannot send all these records immediately. So, it temporarily keeps them in memory until they can be sent. During this time, the producer groups records into batches based on their target partitions. Once a batch is ready, it sends it to the corresponding partition leader.</p><p>But memory is limited.</p><p><strong>What happens when the producer’s buffer becomes full?</strong></p><p>It cannot keep accepting records forever. Kafka uses a setting called buffer.memory to control how much memory the producer can use to hold records waiting to be sent.</p><p>When this memory fills up, the producer waits for some space to become available. If enough space doesn’t become available within the allowed time, the producer reports an error.</p><p>So, batching helps us send records efficiently, compression helps reduce the data sent over the network, and buffering helps the producer manage records that are waiting to be sent.</p><p>But there’s still one important question we haven’t answered.</p><p><strong>Which partition should receive our event in the first place?</strong></p><h3>3. How Should We Choose a Partition for Each Event?</h3><p>Let’s return to our orders topic.</p><p>It has three partitions:</p><pre>orders<br>  |<br>  |--- Partition 0<br>  |--- Partition 1<br>  |--- Partition 2</pre><p>Our order service wants to publish an event for ORD-101.</p><p>Which partition should receive it?</p><p>We could choose a partition randomly. But let’s think about what might happen if we do that.</p><p>Suppose ShopNow produces these events for the same order: OrderCreated , PaymentCompleted , OrderShipped .</p><p>These events are related. Ideally, we want them to be processed in the order they were produced.</p><p>But if we place them in different partitions, Kafka does not guarantee their relative order across those partitions.</p><p>So, how can we keep related events together?</p><h4>What if we use a key?</h4><p>A Kafka record can have a key as well as a value.</p><p>For example, we could use the order ID as the key:</p><pre>{<br>  &quot;key&quot;: &quot;ORD-101&quot;,<br>  &quot;value&quot;: {<br>    &quot;event&quot;: &quot;OrderCreated&quot;,<br>    &quot;amount&quot;: 1499<br>  }<br>}</pre><p>Why would we do that?</p><p>Because we want events belonging to the same order to be routed consistently to the same partition.</p><p>The producer’s partitioner uses the key to select a partition. In the usual keyed-partitioning behavior, it hashes the key and uses the result to choose from the available partitions.</p><p>Conceptually, the process looks like this:</p><pre>           Key: ORD-101<br>                |<br>                v<br>           Hash the Key<br>                |<br>                v<br>        Select a Partition<br>                |<br>                v<br>           Partition 1</pre><p>Now, imagine we publish three events using ORD-101 as the key.</p><p>If they are routed to the same partition, Kafka can preserve their relative order within that partition as they are appended.</p><p>This is why choosing a good key matters.</p><p>We aren’t simply choosing a field to put inside a message. We are deciding how events are distributed across the system and which events can benefit from partition-level ordering.</p><h4>What happens when a key is absent?</h4><p>Imagine we have a Kafka topic with 3 partitions and our application is continuously producing events. Since these records don’t have keys, the producer has no key to use for choosing a partition.</p><p>A simple approach would be to distribute records across partitions one by one:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RBTxBr8qjzGQQ4SfGJ29hA.png" /></figure><p>But there’s a problem.</p><p>The producer maintains separate batches for different partitions. If records keep switching partitions, each batch may take longer to fill up.</p><p><strong>Can we do something better?</strong></p><p>Yes. Instead of switching partitions for every record, the producer can stick to one partition for some time. Let’s see how:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*du64XRcwW522oR0g4bRAnA.png" /></figure><p><strong>Why is this better? </strong>Compare the two approaches:</p><ul><li>Without sticky partitioning, records may get spread across partitions too quickly, leaving smaller batches.</li><li>With sticky partitioning, records stay with one partition for a while, giving its batch more opportunity to grow.</li></ul><p>Larger batches generally mean fewer requests and better network efficiency.</p><p>One important detail: <strong><em>Sticky partitioning</em></strong> doesn’t mean the producer waits forever to fill a batch. <em>Batch size</em> and <em>delivery timing</em> settings still apply. The producer can send a batch when it becomes full or when the configured linger time expires.</p><p>So, the simple idea is: <strong>Stay with one partition for a while → build a larger batch → send it → switch to another partition.</strong></p><p>This allows it to collect more records into a batch before sending them.</p><h4>What happens when our application grows and we add more partitions?</h4><p>Let’s say our orders topic initially has three partitions.</p><p>Whenever we publish an event with the key ORD-101, our producer sends it to Partition 1.</p><p>Now, as ShopNow grows, we’re receiving more orders and want to distribute the workload across more partitions.</p><p>So, we increase the number of partitions from 3 to 6.</p><p>But here’s something we should think about. <strong>Will events with the key </strong><strong>ORD-101 still go to Partition 1?</strong></p><p>Not necessarily. Why?</p><p>Because the producer uses the key and the number of available partitions to decide where an event should go.</p><p>When we change the number of partitions, the same key might now map to a different partition.</p><p>For example:</p><pre>Before increasing partitions: ORD-101 ──&gt; Partition 1<br>After increasing partitions: ORD-101 ──&gt; Partition 4</pre><p>Now, remember that Kafka doesn’t move our older records when we add partitions.</p><p>So, the older events for ORD-101 are still in Partition 1, while newer events might start going to Partition 4.</p><p><strong>Can you see the problem here?</strong></p><p>Suppose we have these events: OrderCreated, PaymentCompleted, OrderShipped</p><p>The first two events might be in Partition 1, while the last one might go to Partition 4.</p><p>Since Kafka doesn’t guarantee ordering across partitions, a consumer might process OrderShipped before PaymentCompleted.</p><p>This is why increasing the number of partitions needs some planning, especially when our application depends on events being processed in order.</p><p>Adding partitions gives us more room to distribute the workload, but it can also change where future events with the same key are stored.</p><h4>What if one partition receives much more traffic than others?</h4><p>Let’s take another situation.</p><p>Imagine ShopNow has 10 partitions.</p><p>Most customers place only a few orders, but we also have one large customer who generates thousands of events every minute.</p><p>Now, suppose we’re using customerId as our partition key.</p><p>All events belonging to that customer will be routed to the same partition.</p><p>As a result, one partition might receive thousands of events while the remaining partitions are handling much less traffic.</p><p>This is called a <strong>hot partition</strong>. Think of it like having 10 checkout counters in a supermarket, but almost everyone is standing in just one queue. Even though we have 10 counters, most of the workload is still going through one counter.</p><p><strong>Can we solve this by adding more partitions? </strong>Not necessarily.</p><p>The problem isn’t that we have too few partitions. The problem is that one key is generating too much traffic, and all events with that key are going to the same partition.</p><p>So, we might need to <strong><em>rethink our partition key.</em></strong></p><p>For example, instead of using customerId, we could use orderId.</p><p>This would distribute different orders from the same customer across different partitions, while keeping events belonging to the same order together.</p><p>But notice the trade-off:</p><ul><li>If we use customerId, we can keep all events of that customer together in one partition.</li><li>If we use orderId, we can keep events of the same order together, but events belonging to different orders from that customer may go to different partitions.</li></ul><p>So, which one should we choose? It depends on what we need to keep in order. If our application needs ordering for each order, orderId is a better choice.</p><p>If it needs ordering across all events belonging to a customer, customerId might be more appropriate, provided it doesn&#39;t create an unacceptable traffic imbalance.</p><p><strong>This brings us to an important lesson about partition keys.</strong></p><p>Choosing a partition key is not just about deciding where to store an event. it’s an architectural decision :</p><ul><li>Which events should stay together?</li><li>Which events need to maintain their order?</li><li>How evenly will the workload be distributed across partitions?</li></ul><p>A good partition key helps us balance these requirements.</p><p>And with that, we’ve understood how a producer discovers the cluster, prepares records, and decides which partition should receive them.</p><p>But there’s still one important part of the producer’s journey left to understand.</p><p><strong>What happens after the producer sends a record to Kafka? How does it know whether the record was successfully stored?</strong></p><h3>4. What Actually Happens When the Producer Sends a Record?</h3><p>Let’s connect everything we’ve learned so far.</p><p>Our producer has created the OrderCreated event, selected a partition, discovered its leader, and prepared the record for sending, waiting inbuffer.memory .</p><p>Now it sends a produce request to the partition leader. But what happens when the request reaches the broker?</p><p>Remember what we learned earlier: Kafka stores each partition as an ordered log. Whenever a new record arrives, it gets appended to the end of that partition’s log.</p><p>For example, suppose Partition 1 currently contains:</p><pre>Partition 1<br>Offset 0  → ORD-095<br>Offset 1  → ORD-098<br>Offset 2  → ORD-100</pre><p>Now our producer sends ORD-101. The partition leader appends this record to its local log and assigns it the next offset.</p><pre>Partition 1<br>Offset 0  → ORD-095<br>Offset 1  → ORD-098<br>Offset 2  → ORD-100<br>Offset 3  → ORD-101</pre><p>Notice something important.</p><p>The offset belongs to the partition, not to the topic as a whole. Every partition maintains its own sequence of offsets.</p><p>This is also how Kafka maintains ordering within a partition: records are appended to its log in sequence.</p><h4>Does the producer send the record to every replica?</h4><p>No. The producer sends the record only to the partition leader.</p><p>The leader handles the write, and the follower replicas fetch records from the leader to keep their copies updated.</p><p>So, our producer doesn’t need to send the same record separately to every replica. Kafka handles replication internally.</p><p>But this brings us to another question.</p><p><strong>The leader has stored the record, but how does our producer know that the write was successful?</strong></p><h4>How does the producer know where the record was stored?</h4><p>When Kafka successfully handles a produce request, it can return metadata to the producer, including:</p><ul><li>Topic name</li><li>Partition number</li><li>Offset assigned to the record</li></ul><p>This tells our producer where Kafka placed the event.</p><p>But there’s something we haven’t considered yet.</p><ul><li>The leader might have appended the record to its local log, but should it acknowledge the write immediately?</li><li>What if the leader crashes before the record is replicated?</li><li>Should the producer already consider the write successful?</li></ul><p>To understand this, we need to look at acknowledgements.</p><h3>5. When Should Kafka Acknowledge a Write?</h3><p>Imagine the leader has appended ORD-101 to its local log.</p><p>Now, when should it send a confirmation back to our producer?</p><p>Should it acknowledge immediately after writing to its own log, or wait until follower replicas have received the record?</p><p>Think about the trade-off.</p><p>The sooner we acknowledge the write, the less time our producer has to wait. But waiting for replication provides stronger protection against losing an acknowledged record when a broker fails.</p><p>Kafka gives us a configuration called acks to control how much confirmation the producer waits for.</p><p>Let’s understand its three options.</p><h4>What happens when acks=0?</h4><p>With acks=0, the producer doesn&#39;t wait for an acknowledgement from the broker.</p><p>It sends the request and considers the send complete without knowing whether Kafka actually received the record.</p><p>For example, if our network connection fails while sending ORD-101, the producer might not even know that the request was lost.</p><p>This reduces waiting for a response, but provides no confirmation that the broker stored the record.</p><h4>What happens when acks=1?</h4><p>With acks=1, the leader acknowledges the write after appending the record to its own local log.</p><p>It doesn’t wait for follower replicas to acknowledge that they have received the record.</p><p>Let’s imagine this scenario:</p><ol><li>The leader receives ORD-101.</li><li>It appends the record to its local log.</li><li>It sends an acknowledgement to the producer.</li><li>The producer receives the acknowledgement.</li><li>Before the record is replicated, the leader crashes.</li></ol><p>Now, depending on which replica becomes the new leader, the acknowledged record could be lost.</p><p>Why?</p><p>Because the acknowledgement only confirmed the leader’s local write. It didn’t confirm that the follower replicas had received the record.</p><p>So, the producer received confirmation, but that didn’t guarantee protection against this kind of leader failure.</p><h4>What happens when acks=all?</h4><p>With acks=all, the leader waits for all replicas currently in the In-Sync Replicas (ISR) to acknowledge the write before completing the request.</p><p>Remember, ISR contains the replicas that Kafka currently considers sufficiently caught up to participate in this acknowledgement condition.</p><p>But what does “all” actually mean?</p><p>Suppose our partition has three configured replicas:</p><pre>Partition 1<br>Broker 1 → Leader   (ISR)<br>Broker 2 → Follower (ISR)<br>Broker 3 → Follower (Not in ISR)</pre><p>Here, only two replicas are currently in the ISR.</p><p>With acks=all, the leader waits for the current ISR replicas, not every configured replica regardless of its state.</p><p>This gives us stronger protection against losing acknowledged records if the leader fails. But here’s another question.</p><p><strong>What if only one replica is currently in the ISR? Should Kafka still accept the write?</strong></p><p>This is where another configuration becomes important: min.insync.replicas.</p><h4>What is min.insync.replicas?</h4><p>It controls the minimum number of in-sync replicas that must be available for a write to succeed when using acks=all.</p><p>For example, suppose we configure:</p><pre>replication.factor=3<br>min.insync.replicas=2<br>acks=all</pre><p>This means:</p><ul><li>We have three replicas assigned to the partition.</li><li>At least two replicas must be in the ISR for the write to be accepted.</li><li>If only one replica remains in the ISR, Kafka rejects the write instead of accepting it with fewer replicas than required.</li></ul><p>Notice the trade-off here.</p><p>Kafka may reject writes during certain failures rather than accept them with a weaker replication condition. This helps us control how much replication protection we require before considering a write successful. Let’s summarize:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*URdVQ9KHZxq1mCgFwFwB6Q.png" /></figure><p>One important thing to remember: acks=all and min.insync.replicas work together. The first controls the acknowledgement condition, while the second establishes the minimum ISR size required for accepting the write.</p><p>So, when we configure acknowledgements, we aren’t simply choosing how long to wait.</p><p><strong>We’re deciding what level of replication confirmation is sufficient for our application to consider a write successful.</strong></p><h3>6. What Happens When the Producer Doesn’t Receive an Acknowledgement?</h3><p>Let’s imagine the following situation.</p><p>Our producer sends ORD-101 to the partition leader.</p><p>The leader receives the request, successfully appends the record to its log, and sends an acknowledgement back to the producer.</p><p>But something goes wrong.</p><p>The acknowledgement gets lost somewhere along the way because of a network issue. Now, from our producer’s perspective, something is unclear.</p><p><strong>Did Kafka store the record, or did the request fail?</strong></p><p>The producer cannot know for sure.</p><p><em>A timeout only tells us that a response wasn’t received within the expected time. It doesn’t necessarily mean the write failed.</em></p><p>So, what should our producer do? It can try sending the same record again. This is called a <strong>retry</strong>.</p><p>Kafka producers support retries so that temporary failures don’t immediately result in lost records.</p><p>But think about what could happen here.</p><p>The first request might have already succeeded, even though the acknowledgement never reached our producer. When the producer retries, Kafka might receive the same record again.</p><p>We could end up with:</p><pre>Partition 1<br>Offset 0 → ORD-095<br>Offset 1 → ORD-098<br>Offset 2 → ORD-100<br>Offset 3 → ORD-101<br>Offset 4 → ORD-101</pre><p>Now the same logical event has been stored twice. Imagine what could happen if our order service processes both records.</p><p>We might <em>create the same order twice</em>, <em>send two confirmation emails</em>, or <em>trigger the same operation more than once.</em></p><p>Retries help us recover from failures, but they can also introduce duplicate records.</p><p><strong>Can Kafka recognize when a producer is retrying the same record?</strong></p><p>Yes. This is where idempotent producers come into the picture.</p><h4>How does an idempotent producer help?</h4><p>Kafka supports a feature called <strong>idempotent production</strong>.</p><p>Let’s understand the idea with our same example.</p><p>When idempotence is enabled, Kafka assigns the producer an identity and uses sequence numbers to track the records it sends to each partition.</p><p>Think of these sequence numbers as a way for Kafka to recognize the order of records sent by a particular producer.</p><p>For example:</p><ol><li>The producer sends ORD-101 with sequence number 0.</li><li>The leader stores the record successfully.</li><li>The acknowledgement gets lost.</li><li>The producer retries the same record using the same sequence number.</li></ol><p>Now, the broker can recognize that this is a retry of a record it has already stored. Instead of appending another copy, Kafka identifies the duplicate and avoids storing it again.</p><p>So, even though our producer had to retry the request, we don’t end up with another copy of that record in the partition.</p><p><strong><em>That’s the basic idea behind idempotent production.</em></strong></p><p><strong>But does this mean our application can never process duplicate events?</strong></p><p>No.</p><p>Idempotent production protects against duplicate writes caused by producer retries within Kafka’s supported producer session and protocol.</p><p>It doesn’t automatically prevent our application from publishing the same business event again as a new send. It also doesn’t guarantee that a consumer or an external service will never process an operation more than once.</p><p>For example, if our consumer reads an order event and sends a payment request to an external payment service, producer idempotence alone cannot prevent that payment operation from happening twice.</p><p>We’ll need to consider consumer-side processing and other mechanisms for that. For now, remember this distinction:</p><ul><li><strong>Retries</strong> help the producer recover from temporary failures.</li><li><strong>Idempotence</strong> helps prevent duplicate records caused by those retries.</li></ul><p>Modern Kafka producer clients enable idempotence by default when the relevant configurations are compatible.</p><h3>7. What guarantees have we understood so far?</h3><p>Let’s connect everything we’ve learned.</p><p>When our producer sends a record to Kafka, different parts of the producer and broker work together to provide different guarantees.</p><p><strong>1. Ordering guarantee</strong></p><p>Kafka maintains the order of records within a partition.</p><p>If related events use the same key and are routed to the same partition, Kafka can preserve their relative order as they are appended.</p><p>However, Kafka does not guarantee ordering across different partitions.</p><p><strong>2. Replication and durability</strong></p><p>Kafka replicates partition data across brokers.</p><p>With acks=1, the leader acknowledges after its local write.</p><p>With acks=all and an appropriate min.insync.replicas setting, the producer waits for a stronger replication condition before considering the write successful.</p><p>This provides better protection against certain broker failures, although no configuration should be interpreted as an absolute guarantee against every possible failure.</p><p><strong>3. Retry support</strong></p><p>When temporary failures occur, the producer can retry sending records rather than immediately giving up.</p><p>However, a timeout doesn’t necessarily mean the original write failed. Retrying without idempotence can result in duplicate records.</p><p><strong>4. Idempotent production</strong></p><p>Kafka can recognize duplicate writes caused by producer retries and prevent those duplicate records from being appended again.</p><p>This makes the producer’s write path more reliable without requiring us to simply avoid retries.</p><p>But remember, these guarantees have boundaries.</p><p>Producer idempotence doesn’t automatically make our entire application exactly-once. It doesn’t guarantee that external business operations or consumer processing will happen only once.</p><p>For those scenarios, we’ll need to explore additional mechanisms such as consumer-side idempotency and Kafka transactions.</p><p>And with that, we’ve understood the important responsibilities of a Kafka producer: discovering the cluster, choosing a partition, preparing batches, sending records, handling acknowledgements, and recovering from failures.</p><h3>8. Let’s Put Everything Together</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yWch1YYb1FvmA2qp_e6k9A.png" /></figure><p>Let’s take a moment to reflect on what we’ve learned. When our application sends an event to Kafka:</p><ul><li>The producer discovers the cluster using bootstrap servers and learns which broker leads the target partition.</li><li>It chooses a partition based on the key or the configured partitioning strategy.</li><li>It can accumulate records into batches and compress them to use network resources more efficiently.</li><li>It sends a produce request to the partition leader, which appends records to its log.</li><li>The acknowledgement configuration determines what the producer waits for before considering the send successful.</li><li>If a request times out, the producer may need to retry because it cannot always know whether the original write succeeded.</li><li>Idempotent producer behavior helps prevent duplicate records caused by certain retries.</li><li>Buffers, timeouts, and retry policies help the producer deal with situations where Kafka cannot keep up or becomes temporarily unavailable.</li></ul><p>We started with a simple question: what happens when an application sends an event to Kafka?</p><p>Now we can see that it involves much more than sending a network request.</p><p>Every part of this journey exists to solve a particular problem: finding the right destination, sending data efficiently, storing it in the right place, deciding when a write is successful, and handling failures.</p><p>And that’s how we should understand Kafka — not as a collection of configurations to memorize, but as a set of engineering decisions that solve real problems.</p><blockquote>Thank you for reading. See you in the next part!</blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3426a6cdd6ee" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[3. Kafka Fundamentals: Let’s Build It From Scratch]]></title>
            <link>https://hiimvikash.medium.com/3-kafka-fundamentals-lets-build-it-from-scratch-5fc8434c1995?source=rss-6530c2ff5590------2</link>
            <guid isPermaLink="false">https://medium.com/p/5fc8434c1995</guid>
            <category><![CDATA[kafka-consumer-group]]></category>
            <category><![CDATA[kafka]]></category>
            <category><![CDATA[broker]]></category>
            <category><![CDATA[apache-kafka]]></category>
            <dc:creator><![CDATA[Vikash Gupta]]></dc:creator>
            <pubDate>Mon, 26 Oct 2026 08:57:20 GMT</pubDate>
            <atom:updated>2026-10-27T05:44:22.991Z</atom:updated>
            <content:encoded><![CDATA[<p>In the <a href="https://hiimvikash.medium.com/2-we-understand-the-problem-now-how-do-we-solve-it-7b948a9dc12f">last</a> blog, we explored different approaches to help our services work independently.</p><p>We started with a database, explored message queues using BullMQ, discovered fan-out with RabbitMQ, and finally arrived at event streaming.</p><p>We ended with a question: <strong>How does Apache Kafka actually make event streaming possible?</strong></p><p>Imagine our ShopNow application has finally started using Kafka.</p><p>When a customer places an order, our order service publishes an OrderCreated event to Kafka.</p><p>The payment service, inventory service, and analytics service can then consume that event independently.</p><p>Sounds simple enough. But let’s pause for a moment.</p><p><strong>What actually happens when our order service sends an event to Kafka?</strong></p><p>What is an event? Where does that event go? Where is it stored? How do other services find it? And how does Kafka handle millions of events without everything becoming a bottleneck?</p><p>Instead of memorizing Kafka’s architecture, let’s figure out what we would need to build such a system ourselves.</p><h3>1. First, What Are We Actually Sending?</h3><p>Let’s return to our ShopNow application.</p><p>Whenever something happens in our application, we may want to share that information with other services.</p><p>For example, when a customer places an order, our application could produce an event like this:</p><pre>{<br>  &quot;event&quot;: &quot;OrderCreated&quot;,<br>  &quot;orderId&quot;: &quot;ORD-101&quot;,<br>  &quot;userId&quot;: &quot;USER-42&quot;,<br>  &quot;amount&quot;: 1499,<br>  &quot;currency&quot;: &quot;INR&quot;<br>}</pre><p>This is just a JSON object describing something that happened. Our application could produce similar events for other situations.</p><pre>When a payment succeeds:<br>{<br>  &quot;event&quot;: &quot;payment-success&quot;,<br>  &quot;paymentId&quot;: &quot;PAY-501&quot;,<br>  &quot;orderId&quot;: &quot;ORD-101&quot;,<br>  &quot;amount&quot;: 1499,<br>  &quot;status&quot;: &quot;SUCCESS&quot;<br>}<br><br>When inventory is reserved:<br>{<br>  &quot;event&quot;: &quot;inventory-reserved&quot;,<br>  &quot;orderId&quot;: &quot;ORD-101&quot;,<br>  &quot;productId&quot;: &quot;PROD-25&quot;,<br>  &quot;quantity&quot;: 2<br>}<br><br>When a customer registers:<br>{<br>  &quot;event&quot;: &quot;user-signup&quot;,<br>  &quot;userId&quot;: &quot;USER-42&quot;,<br>  &quot;email&quot;: &quot;customer@example.com&quot;,<br>  &quot;registeredAt&quot;: &quot;2026-10-25T10:30:00Z&quot;<br>}</pre><p>Notice something interesting.</p><p>All these records are JSON objects, but they describe different things that happened in our application.</p><p>Now imagine ShopNow grows and starts generating thousands or even millions of these records.</p><p>Where should we put them?</p><p>Should we throw every event into one giant collection, mixing orders, payments, inventory changes, and customer registrations together?</p><p>We could, but finding and organizing related events would become difficult for new consumer who joins later.</p><p><strong>We need a way to group related events into separate streams. </strong>This brings us to our next idea.</p><h3>2. Second, How Should We Organize These Events?</h3><p>Imagine arranging all our events into groups based on what they represent.</p><ul><li>Order-related events go into an orders stream.</li><li>Payment-related events go into a payments stream.</li><li>Inventory-related events go into an inventory stream.</li><li>Customer-related events go into a customers stream.</li></ul><p>In Kafka, these named streams are called <strong>topics</strong>.</p><p>For example, our orders topic might contain records like these:</p><pre>{<br>  &quot;event&quot;: &quot;OrderCreated&quot;,<br>  &quot;orderId&quot;: &quot;ORD-101&quot;,<br>  &quot;amount&quot;: 1499<br>},<br>{<br>  &quot;event&quot;: &quot;OrderShipped&quot;,<br>  &quot;orderId&quot;: &quot;ORD-103&quot;,<br>  &quot;trackingId&quot;: &quot;TRK-9001&quot;<br>},<br>{<br>  &quot;event&quot;: &quot;OrderCancelled&quot;,<br>  &quot;orderId&quot;: &quot;ORD-102&quot;,<br>  &quot;reason&quot;: &quot;Customer request&quot;<br>}</pre><p>These events describe different things that happened to orders, so we might organize them in the <strong>same topic</strong>.</p><p>A <strong>topic</strong> is a named stream of records. It doesn’t require every record to have exactly the same JSON structure, although designing consistent event schemas is important.</p><p>We’ve now solved our first problem: <strong>we have a way to organize related events.</strong></p><p>But another problem appears as our application grows.</p><p>What happens when our orders topic starts receiving millions of records?</p><p>Can we distribute the storage and workload across multiple machines instead of relying on one long log handled by a single machine?</p><p>Let’s figure that out next.</p><h3>3. Third, What Happens When Millions of Events Arrive?</h3><p>Till now, we’ve organised events from different categories into their respective <em>logical divisions</em> called <strong>topics</strong>.</p><p>Now, let’s continue designing Kafka by focusing on a single orders topic.</p><p>Remember, every time an order is placed, ShopNow publishes an event to the orders topic.</p><p>Now, imagine ShopNow has gone viral across the globe. We’re receiving millions of order events from different countries.</p><p>All these events are going into the same orders topic.</p><p>Suppose you open the admin dashboard and want to answer questions like:</p><ul><li>How many orders came from India today?</li><li>Which country generated the highest revenue?</li><li>How many orders were placed in the US in the last hour?</li></ul><p>To answer these questions, our analytics consumer needs to process order events and calculate the required statistics.</p><p>But here’s the problem: <strong>if all these events are kept in one enormous sequence, processing this growing stream can become a challenge.</strong></p><p>As the volume of events grows, we need a better way to organise and process the stream.</p><p>What if we could divide the events into multiple smaller sequences based on our requirements?</p><p>Let’s understand this with an example. An order event might look something like this:</p><pre>{<br>  &quot;event&quot;: &quot;OrderCreated&quot;,<br>  &quot;orderId&quot;: &quot;ORD-101&quot;,<br>  &quot;country&quot;: &quot;IN&quot;,<br>  &quot;amount&quot;: 1499<br>}<br><br>Another order might come from the US:<br>{<br>  &quot;event&quot;: &quot;OrderCreated&quot;,<br>  &quot;orderId&quot;: &quot;ORD-102&quot;,<br>  &quot;country&quot;: &quot;US&quot;,<br>  &quot;amount&quot;: 2500<br>}</pre><p>Notice that each event contains a country code.</p><p><strong>What if we could organise these events based on the country they belong to?</strong></p><p>For example, we could use the country code as the key when publishing each event.</p><p>Conceptually, our orders topic could be divided like this:</p><pre>                orders topic<br>                      |<br>          ┌───────────┼───────────┐<br>          |           |           |<br>          v           v           v<br>     Partition 0  Partition 1  Partition 2<br>        Key: IN      Key: US      Key: UK<br>        India        US           UK<br>        India        US           UK<br>        India        US           UK</pre><p><em>This is a simplified illustration. In a real Kafka setup, a partition can contain events from multiple countries.</em></p><p>Now, our analytics consumer can process events from these partitions and calculate country-wise order statistics.</p><p>But here’s the interesting part.</p><p><strong>We decide how to divide our event stream based on our requirements.</strong></p><p>In our example, we used the country code as the key because we wanted to organise events by country. In another system, we might use a user ID, an order ID, or some other key, depending on what we’re trying to achieve.</p><p>We also decide how many partitions our topic should have.</p><p>Kafka gives us the building blocks, but choosing the number of partitions and deciding how events should be distributed across them are design decisions we make when building our system.</p><p>These smaller, independently ordered sequences within a topic are called <strong>partitions</strong>.</p><h4>But Which Partition Should Receive an Event? — hashed key approach.</h4><p>We’ve divided our orders topic into three partitions.</p><p>When a new event arrives, should it go to Partition 0, Partition 1, or Partition 2?</p><p>We need a rule to make that decision.</p><p>One simple approach is to distribute events in a round-robin fashion: the first event goes to Partition 0, the next to Partition 1, then Partition 2, and the cycle repeats.</p><p>But there’s another possibility.</p><p>What if we want events belonging to the same order to go to the same partition? This would be useful when we want to preserve the order of events for that partition.</p><p>Kafka supports this through a concept called a <strong>partition key.</strong></p><p>Let’s first understand something important: <strong>a partition key isn’t a special field that must be added to your event.</strong> It’s simply a piece of information that the producer chooses to use when deciding which partition should receive the event.</p><p>Look at our event again:</p><pre>{<br>  &quot;event&quot;: &quot;OrderCreated&quot;,<br>  &quot;orderId&quot;: &quot;ORD-101&quot;,<br>  &quot;userId&quot;: &quot;user-109&quot;<br>  &quot;country&quot;: &quot;IN&quot;,<br>  &quot;amount&quot;: 1499<br>}</pre><p>The orderId, country, and amount are all pieces of information in the event.</p><p>If our goal is to group events by country, we could choose country as the partitioning key.</p><p>If our goal is to keep events belonging to the same order together, we could choose orderId instead.</p><p>The information itself isn’t special. <strong>It’s called a partition key because we’re using it to determine which partition receives the event.</strong></p><p>For example, a producer could publish an event using ORD-101 as its key:</p><pre>Key:   ORD-101<br>Value: OrderCreated event</pre><p>The producer can hash the key and use the result to determine which partition receives the event.</p><p>Think of the process like this:</p><pre>       Event<br>         |<br>         v<br>    Message Key<br>      ORD-101<br>         |<br>         v<br>     Hash Key<br>         |<br>         v<br>  Select Partition<br>         |<br>         v<br>   Append Event</pre><p>When multiple events use the same key, they are generally directed to the same partition, provided the partitioning configuration remains unchanged.</p><p>This is useful because <strong>Kafka preserves the order of records within a partition, but not across different partitions.</strong></p><p>And if a producer doesn’t provide a key, Kafka can use a different partitioning strategy.</p><p>Notice how these two ideas work together:</p><ul><li><strong>Topics</strong> organise related events into named streams.</li><li><strong>Partitions</strong> divide a topic into multiple ordered sequences.</li><li><strong>Partition keys</strong> help determine which partition receives an event.</li></ul><p>We’ve now figured out how a single topic can be divided and how events can be assigned to its partitions.</p><h3>4. We Need A Machine</h3><p>So far, we’ve discovered two ways to organise our data:</p><ul><li><strong>Topics</strong> group related events.</li><li><strong>Partitions</strong> divide a topic into multiple ordered sequences of records.</li></ul><p>But we’ve only discussed how to organise our data. We haven’t answered a fundamental question yet.</p><p><strong>Where do these events actually live?</strong></p><p>A topic is a logical concept. A partition defines an ordered sequence of event logically distributed across multiple partitions. But neither of these is a physical machine.</p><p>Our events still need disk space to be stored. And when a producer sends an event or a consumer requests records, some machine needs to handle that request.</p><p>Let’s think about how we would design this.</p><h4>First, We Need a Machine to Store Our Data</h4><p>Imagine we’re building Kafka from scratch, and we have just one machine available.</p><p>We install Kafka on this machine and let it store our partition data and handle requests from producers and consumers.</p><p>This machine can store partitions belonging to multiple topics. For example, it could store partitions from both our orders and users topics.</p><pre>                 One Kafka Server<br>                     Broker 1<br>              ┌─────────────────────┐<br>              │                     │<br>              │     Topic: orders   │<br>              │   ┌───────────────┐ │<br>              │   │ Partition 0   │ │<br>              │   ├───────────────┤ │<br>              │   │ Partition 1   │ │<br>              │   └───────────────┘ │<br>              │                     │<br>              │     Topic: users    │<br>              │   ┌───────────────┐ │<br>              │   │ Partition 0   │ │<br>              │   ├───────────────┤ │<br>              │   │ Partition 1   │ │<br>              │   └───────────────┘ │<br>              │                     │<br>              └─────────────────────┘</pre><p>A server running Kafka that stores and serves partition data of multiple topic is called a <strong>broker</strong>.</p><p>Notice that a broker doesn’t belong to just one topic. It can store multiple partitions from multiple topics.</p><h4>Let’s Play With Our Single Broker</h4><p>Before we move forward, let’s understand how our design works with just one broker.</p><p>Imagine our Kafka server is running, and we’ve created two topics: orders and users. For now, let&#39;s focus only on the orders topic, which has three partitions.</p><p>Whenever a new order is placed, the producer sends an event to Kafka. Kafka’s producer-side partitioning logic determines which partition receives that event.</p><p>Let’s publish a few events and see what happens.</p><p><strong>Event 1: A customer places an order.</strong></p><pre>{<br>  &quot;event&quot;: &quot;OrderCreated&quot;,<br>  &quot;orderId&quot;: &quot;ORD-101&quot;,<br>  &quot;amount&quot;: 1499<br>}</pre><p>Suppose this event is assigned to Partition 0.</p><p><strong>Event 2: Another customer places an order.</strong></p><pre>{<br>  &quot;event&quot;: &quot;OrderCreated&quot;,<br>  &quot;orderId&quot;: &quot;ORD-102&quot;,<br>  &quot;amount&quot;: 2500<br>}</pre><p>This time, suppose the event goes to Partition 1.</p><p><strong>Event 3: A third order arrives.</strong></p><pre>{<br>  &quot;event&quot;: &quot;OrderCreated&quot;,<br>  &quot;orderId&quot;: &quot;ORD-103&quot;,<br>  &quot;amount&quot;: 999<br>}</pre><p>Suppose it goes to Partition 0 again.</p><p>Our single broker now stores the following partition data:</p><pre>                   Broker 1<br>             ┌──────────────────────┐<br>             │                      │<br>             │   orders topic       │<br>             │                      │<br>             │   Partition 0        │<br>             │   ┌────────────────┐ │<br>             │   │ ORD-101        │ │<br>             │   │ ORD-103        │ │<br>             │   └────────────────┘ │<br>             │                      │<br>             │   Partition 1        │<br>             │   ┌────────────────┐ │<br>             │   │ ORD-102        │ │<br>             │   └────────────────┘ │<br>             │                      │<br>             │   Partition 2        │  <br>             │   ┌────────────────┐ │<br>             │   │ (empty)        │ │<br>             │   └────────────────┘ │<br>             │                      │<br>             └──────────────────────┘</pre><p>The partition assignments here are just an example; the actual destination depends on the producer’s partitioning strategy.</p><p>Notice something important: <strong>each partition maintains its own ordered sequence of records.</strong></p><p>When a new event is assigned to Partition 0, Kafka appends it to the end of that partition’s sequence. It doesn’t insert the event between older records.</p><p>This is why we describe a Kafka partition as an <strong>append-only log</strong>.</p><p>Think of it like a journal. You keep adding new entries at the end, one after another. The previous entries remain in their original positions while they’re retained.</p><p>Each record also has an offset, which identifies its position within that partition.</p><p>For example:</p><pre>Partition 0<br>Offset 0  →  ORD-101<br>Offset 1  →  ORD-103</pre><p>Offsets are local to each partition. Partition 1 has its own offsets, starting from 0 for this simplified example.</p><p>So, what have we learned from our little experiment?</p><ul><li>A producer publishes an event to a topic.</li><li>The producer’s partitioning logic determines which partition receives it.</li><li>The broker stores the partition’s records as an append-only sequence.</li><li>Each record has an offset within its partition.</li></ul><p>That’s the basic picture of Kafka working with a single broker.</p><p>But now let’s ask ourselves one last question before we move forward.</p><p><strong>What happens when one broker is no longer enough — or when the machine itself fails?</strong></p><p>That’s the next problem we need to solve as we continue designing Kafka.</p><h3>5. What If Our Single Broker Goes Down?</h3><p>Let’s recap what we’ve built so far.</p><p>We have one Kafka broker storing our orders topic, which contains multiple partitions. Whenever a producer publishes an event, it gets assigned to a partition and is appended to the end of that partition&#39;s sequence.</p><p>Everything works fine so far.</p><p>But now, let’s think about what happens when our system grows.</p><p>Our single broker is handling all the incoming events, storing all the records, and serving requests from consumers. As traffic and data grow, we might want to distribute this workload across multiple machines.</p><p>We can add more brokers and distribute our partitions among them.</p><p>But there’s another problem we need to consider.</p><p><strong>What happens if the machine storing our data suddenly crashes?</strong></p><p>Imagine our broker goes offline because of a hardware failure or some other issue.</p><p>Our producers can no longer publish events to that broker, and consumers may no longer be able to read the partitions it was serving.</p><p>Even though our data is divided into multiple partitions, all those partitions still depend on the same machine.</p><p>We’ve organised our data, but we haven’t protected it from machine failure.</p><p>So, how could we solve this? Think about it from first principles.</p><p>If losing one machine makes our data unavailable, <strong>what if we keep another copy of the same partition on a different machine?</strong></p><p>That way, if one machine goes down, another machine may still have the data we need.</p><ul><li>This idea of keeping copies of partition data on different machines is called <strong>replication</strong>.</li><li>And to make this possible, we need multiple Kafka brokers working together as one system. Such a group of brokers is called a <strong>Kafka cluster</strong>.</li></ul><p>Let’s explore how Kafka distributes partitions across brokers and keeps replicas available when a broker fails.</p><h3>6. How Does Kafka Keep Another Copy of Our Data?</h3><p>In the previous section, we discovered two important ideas:</p><ul><li><strong>Kafka cluster:</strong> Multiple brokers working together as one system.</li><li><strong>Replication:</strong> Keeping copies of the same partition on different brokers to help handle machine failures.</li></ul><p>Now, let’s understand how Kafka makes replication work.</p><h4>Two Copies, One Source of Truth</h4><p>Imagine we have two brokers, and both store a copy of Partition 0.</p><pre>            Broker 1                  Broker 2<br>       ┌──────────────┐          ┌──────────────┐<br>       │              │          │              │<br>       │  Partition 0 │          │  Partition 0 │<br>       │              │          │              │<br>       │   ORD-101    │          │   ORD-101    │<br>       │   ORD-103    │          │   ORD-103    │<br>       │              │          │              │<br>       └──────────────┘          └──────────────┘<br>             Copy 1                    Copy 2</pre><p>Now, suppose a new order event arrives.</p><p>Should the producer write it to both brokers independently?</p><p>That could create problems. What if one broker receives the event but the other doesn’t? What if they receive events in a different order?</p><p>We need a clear rule for coordinating these copies.</p><p>Kafka solves this by assigning different roles to the replicas of a partition.</p><p>One replica becomes the <strong>leader</strong>, while the other replicas act as <strong>followers</strong>.</p><h4>The Leader and the Followers</h4><p>Let’s say Broker 1 holds the leader replica of Partition 0, while Broker 2 holds a follower replica.</p><pre>             Broker 1                   Broker 2<br>        ┌──────────────┐           ┌──────────────┐<br>        │              │           │              │<br>        │  Partition 0 │           │  Partition 0 │<br>        │    LEADER    │ ────────&gt; │   FOLLOWER   │<br>        │              │  Replicate│              │<br>        └──────────────┘  records  └──────────────┘<br>                ▲<br>                │<br>           New events<br>                │<br>             Producer</pre><p>The leader handles writes for that partition. Followers fetch records from the leader to keep their copies up to date.</p><p>Kafka also has a term for replicas that are keeping up with the leader: <strong>In-Sync Replicas (ISR)</strong>. These are replicas that are sufficiently caught up with the leader to be considered in sync.</p><p>So, when a producer publishes a new event to Partition 0, it is written through the leader replica. The followers fetch and replicate that record, and those that remain sufficiently caught up can be part of the ISR.</p><p>This gives Kafka a coordinated way to maintain multiple copies of the same partition and helps it decide which replicas are eligible to take over if the leader fails.</p><h4>What If the Leader Broker Fails?</h4><p>Now let’s return to our original problem. <strong>Suppose Broker 1 goes offline.</strong></p><p>The leader replica of Partition 0 is no longer available. But Broker 2 still has a follower replica.</p><p>If Kafka has a suitable in-sync replica available, it can elect a new leader from the eligible replicas. Producers and consumers can then continue using the partition through its new leader.</p><pre>       Broker 1                   Broker 2<br>       OFFLINE                    NEW LEADER<br>    ┌──────────────┐           ┌──────────────┐<br>    │              │           │              │<br>    │  Partition 0 │           │  Partition 0 │<br>    │    LEADER    │           │    LEADER    │<br>    │              │           │              │<br>    └──────────────┘           └──────────────┘<br>                                     ▲<br>                                     │<br>                             Requests continue</pre><p>This is a simplified illustration. In a real cluster, whether a replica can become leader depends on Kafka’s replication state and configuration.</p><p>The important idea is that <strong>a broker failure doesn’t necessarily make a partition unavailable because another broker may have a usable copy.</strong></p><p>That’s the benefit of replication.</p><h3>7. Let’s Connect the Pieces — Checkpoint 1</h3><p>We’ve now discovered how the pieces of Kafka’s architecture fit together:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yZe1qRk2Qn2Z_8HR_u9LSA.png" /></figure><ul><li><strong>Topics</strong> organise related events.</li><li><strong>Partitions</strong> divide a topic into ordered sequences of records.</li><li><strong>Brokers</strong> store and serve partition data.</li><li><strong>Clusters</strong> allow multiple brokers to work together as one system.</li><li><strong>Replication</strong> keeps copies of partitions on different brokers.</li><li><strong>Leaders and followers</strong> coordinate how those copies are written and maintained.</li></ul><p>We’ve built a basic picture of how Kafka stores and protects event data.</p><p>But we still haven’t answered another important question from the <em>beginning of our journey:</em></p><p><strong>How do our services actually read these events, keep track of their progress, and resume reading if they restart?</strong></p><p>Let’s explore how consumers work in Kafka next.</p><h3>8. How Do Consumers Read Events and Remember Their Progress?</h3><h4>First, Let’s Read Some Events</h4><p>Imagine our ShopNow application has an analytics service that wants to read events from the orders topic.</p><p>Our topic contains these records:</p><pre>Partition 0<br>Offset 0  →  ORD-101<br>Offset 1  →  ORD-103<br>Offset 2  →  ORD-105<br>Offset 3  →  ORD-107<br>Offset 4  →  ORD-109<br>...</pre><p>The analytics service connects to Kafka and starts reading records from the partition.</p><p>Suppose it has processed records up to offset 2.</p><p>So far, everything looks fine.</p><p>But now, imagine the analytics service suddenly crashes.</p><p>When it restarts, how will it know where to continue?</p><p>Should it start reading from offset 0 and process everything again? Or should it continue from where it stopped?</p><p>We need a way to remember its progress.</p><h4>The Problem: Who Remembers the Last Read Offset?</h4><p>One simple idea would be to let the analytics service save its last processed offset in its own memory.</p><p>But what happens when the service crashes? Its in-memory state disappears.</p><p>We could save the offset in a database, but then every service would need to manage its own progress-tracking mechanism.</p><p>And what if we run multiple instances of the same service to process events in parallel? How do we coordinate their progress and decide which instance should read which partition?</p><p>We need a better approach.</p><p><strong>What if Kafka could remember the reading progress for a group of consumers, rather than making every consumer manage everything independently?</strong></p><p>This brings us to the idea of a consumer group.</p><h4>Meet the Consumer Group</h4><p>In Kafka, consumers can work together as part of a <strong>consumer group</strong>.</p><p>Think of a consumer group as a team of consumers working together to read a topic.</p><p>For example, our analytics service might have a consumer group called analytics-group.</p><pre>             Kafka Cluster<br>                   |<br>             orders topic<br>                   |<br>          ┌────────┴────────┐<br>          |                 |<br>     Partition 0       Partition 1<br>          |                 |<br>          v                 v<br>      Consumer 1         Consumer 2<br>          |                 |<br>          └────────┬────────┘<br>                   |<br>            analytics-group</pre><p>Here, two consumers from the same group can read different partitions in parallel.</p><p>Kafka coordinates the assignment of partitions to consumers within the group. This allows us to add more consumers and distribute the work.</p><p>But there’s an important rule:</p><p><strong>Within one consumer group, a partition is assigned to at most one consumer at a time.</strong></p><p>For example, Consumer 1 can read Partition 0 while Consumer 2 reads Partition 1. They don’t both get assigned Partition 0 at the same time.</p><p>What if we have three partitions but only two consumers? One consumer can be assigned multiple partitions.</p><p>And what if we add more consumers than there are partitions? Some consumers will have no partition assigned until the assignments change.</p><p>This is how Kafka distributes partition-reading work within a consumer group.</p><h4>How Does Kafka Remember Our Progress?</h4><p>Now let’s return to our original problem.</p><p>Suppose analytics-group is reading Partition 0.</p><p>The consumer processes records at offsets 0, 1, and 2. It then commits its progress to Kafka.</p><p>Conceptually, Kafka maintains a mapping like this:</p><pre>Consumer Group       Topic       Partition      Committed Offset<br>----------------------------------------------------------------<br>analytics-group      orders      Partition 0          3<br>analytics-group      orders      Partition 1          7</pre><p>Notice something important.</p><p>Kafka doesn’t maintain just one offset for the entire consumer group. It tracks progress separately for each topic partition.</p><p>In this simplified example, the committed offset 3 means the group can resume reading Partition 0 from offset 3 next.</p><p>Why 3 and not 2?</p><p>Because Kafka consumers commonly commit the <strong>next offset to read</strong>, rather than the offset of the last record processed.</p><p>Now, suppose Consumer 1 crashes.</p><p>When a consumer in the same group takes over Partition 0, it can retrieve the group’s committed offset and resume from the appropriate position.</p><p>The consumer doesn’t have to start from the beginning, provided the required records are still available and the progress was committed.</p><p>One important detail: Kafka’s committed offset represents the progress the consumer has saved, not necessarily every record it has already processed. If a consumer crashes before committing its latest progress, some records may be processed again.</p><p>That’s why consumers should be designed to handle retries and possible duplicate processing.</p><h4>Why Do We Need Consumer Groups?</h4><p>Consumer groups solve two related problems.</p><p><strong>1. Remembering progress</strong></p><p>Kafka stores committed offsets for each consumer group’s topic partitions, so consumers can resume from saved progress after restarts or reassignment.</p><p><strong>2. Processing in parallel</strong></p><p>Multiple consumers in the same group can read different partitions at the same time, allowing work to be distributed across consumer instances.</p><p>There’s one more useful consequence.</p><p>Imagine both our analytics service and inventory service need to read the same orders topic.</p><p>They can use different consumer groups:</p><pre>                   orders topic<br>                         |<br>               ┌─────────┴─────────┐<br>               |                   |<br>        analytics-group      inventory-group<br>               |                   |<br>        Analytics Service     Inventory Service</pre><p>Each group maintains its own reading progress. The analytics service can read an event without moving the inventory service’s committed offset.</p><p>So, <strong>different consumer groups can independently read the same events, while consumers within one group share the work across partitions.</strong></p><h3>9. Let’s Connect the Pieces — Checkpoint 2</h3><p>We’ve now added another important part to our Kafka architecture:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gVLBxbf2I120i0uLagJvYQ.png" /></figure><ul><li><strong>Topics</strong> organise related events.</li><li><strong>Partitions</strong> divide topics into ordered sequences.</li><li><strong>Brokers</strong> store and serve partition data.</li><li><strong>Replication</strong> keeps copies of partition data on different brokers.</li><li><strong>Consumer groups</strong> coordinate consumers that work together to read partitions.</li><li><strong>Committed offsets</strong> let each consumer group remember its progress for each partition.</li></ul><p>We’ve now seen both sides of Kafka’s basic journey: producers write events, and consumers read them while keeping track of their progress.</p><p><em>Thank you for reading! See you in the next part!</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5fc8434c1995" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[2. We Understand the Problem. Now, How Do We Solve It?]]></title>
            <link>https://hiimvikash.medium.com/2-we-understand-the-problem-now-how-do-we-solve-it-7b948a9dc12f?source=rss-6530c2ff5590------2</link>
            <guid isPermaLink="false">https://medium.com/p/7b948a9dc12f</guid>
            <category><![CDATA[database]]></category>
            <category><![CDATA[background-jobs]]></category>
            <category><![CDATA[task-queues]]></category>
            <category><![CDATA[event-streaming]]></category>
            <category><![CDATA[message-queue]]></category>
            <dc:creator><![CDATA[Vikash Gupta]]></dc:creator>
            <pubDate>Sat, 24 Oct 2026 17:31:45 GMT</pubDate>
            <atom:updated>2026-10-24T17:31:45.517Z</atom:updated>
            <content:encoded><![CDATA[<p>In the <a href="https://hiimvikash.medium.com/1-before-we-talk-about-kafka-lets-understand-the-problem-babfaac8f135">last</a> blog, we discussed why services sometimes need to work independently instead of waiting for each other.</p><p>Let’s continue with our <em>ShopNow</em> application.</p><p>When a customer places an order, we want the order service to hand off some work so that the email, inventory, and analytics services can process it independently.</p><p>But this raises a simple question:</p><p><strong>Where should we put this work so that other services can pick it up later?</strong></p><p>Let’s explore a few approaches and discover the problems each one introduces.</p><h3>Approach A — Use a Database</h3><p>We already use PostgreSQL to store our orders. So, why not use it to store pending tasks as well?</p><p>For example, whenever a customer places an order, we could insert background tasks into a background_jobs table.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6gYXPfGrWOLYq3UqUHvuOg.png" /></figure><p>We can run a background worker that regularly checks this table, picks up pending tasks, processes them, and updates their status.</p><p>If the email service is temporarily unavailable, the task can remain pending until it can be processed.</p><p><strong>Sounds good, right?</strong></p><p>This approach can work well, but let’s think about what happens as our application grows.</p><h4>Concern 1 — Every service needs different information</h4><p>Consider our three tasks:</p><ul><li>The email service needs the customer’s email address and order details.</li><li>The inventory service needs product IDs and quantities.</li><li>The analytics service needs the order amount, timestamp, and perhaps product categories.</li></ul><p>These services don’t need exactly the same information.</p><p>If we store a large, generic payload containing every possible field, some services receive information they don’t need. If we create a separate task table for every service, we now have more tables and more task-management logic to maintain.</p><p>We can solve this with careful database design, but we need to think about how to organize and deliver work to different services.</p><h4>Concern 2 — We must build the job-processing mechanism ourselves</h4><p>As the workload grows, we need to handle several things:</p><ul><li>Prevent multiple workers from accidentally claiming the same task.</li><li>Retry failed tasks.</li><li>Track task status and clean up completed tasks.</li><li>Avoid repeatedly querying the database for pending work.</li><li>Ensure background jobs don’t unnecessarily compete with normal application queries.</li></ul><p>These problems are solvable, but we’re building and maintaining a job-processing system on top of our database.</p><p><strong>Can we use something designed specifically for background jobs instead?</strong></p><h3>Approach B — Use a Message Queue</h3><p>Instead of storing pending tasks in our own database table, imagine a system that accepts tasks and lets workers retrieve them when they’re ready.</p><p>This is the basic idea behind a message queue. But let’s explore a problem that can occur when multiple services need to process the same message.</p><h4>Problem — What happens when a message is consumed?</h4><p>Imagine we put an OrderCreated message into a single queue.</p><p>Both the email service and analytics service need to process it.</p><p>The email worker picks up the message and successfully sends the confirmation email. The queue then considers that job completed and removes it according to its processing semantics.</p><p>Now the analytics service tries to retrieve the same message.</p><p><strong>The message is no longer available in that queue.</strong></p><p>This is how a typical competing-consumer queue works: workers compete to process jobs, rather than each receiving an independent copy of every job.</p><h4>A practical solution — Separate queues for different services</h4><p>In the Node.js ecosystem, we can use <strong>BullMQ</strong>, which uses Redis to manage background jobs.</p><p>Our order service can add jobs to separate queues, and workers can process them independently.</p><p>For example:</p><ul><li><strong>email-queue</strong> contains the information needed to send emails.</li><li><strong>inventory-queue</strong> contains product IDs and quantities.</li><li><strong>analytics-queue</strong> contains the information needed for reporting.</li></ul><p>Notice that each service receives only the information relevant to its task. We don’t need to send the entire order object to every service.</p><p>BullMQ also provides features such as retries, delayed jobs, and worker concurrency to help manage background processing.</p><p>This is already a useful solution for many applications.</p><p><strong>But there is still a problem.</strong></p><p>Our order service now needs to know which queues should receive jobs whenever a new order is created.</p><p>Today, we might have three queues. Tomorrow, we might add queues for notifications, fraud detection, and recommendations.</p><p>Every time we introduce a new consumer, we may need to modify the order service to publish jobs to another queue.</p><p>Can we design this so that the order service simply announces that an order has been created, without knowing which services are interested in that event?</p><p>This leads us to our next approach.</p><h3>Approach C — Fan-Out Architecture</h3><p>Instead of having multiple services compete for one message, what if we could distribute the same message to multiple queues?</p><p>Imagine the order service publishes one OrderCreated message to a central messaging component.</p><p>That component sends a copy to each interested service’s queue.</p><ul><li>The email service receives its own copy.</li><li>The inventory service receives its own copy.</li><li>The analytics service receives its own copy.</li></ul><p>Each service can now process its copy independently.</p><p>If the email service is down, its queue can retain the pending message while the analytics service continues processing its own copy.</p><p>This pattern is called <strong>fan-out</strong>: one published message is distributed to multiple destinations.</p><p>Notice the difference:</p><ul><li><strong>Competing consumers:</strong> Multiple workers share the work in one queue.</li><li><strong>Fan-out:</strong> Multiple destinations receive copies of the same message so they can process it independently.</li></ul><p>Now the question becomes: how can we implement this architecture without manually publishing a separate message to every queue?</p><h4>Approach C — tool : Use RabbitMQ With Exchanges</h4><p>RabbitMQ gives us a way to implement this kind of routing using <strong>exchanges and queues</strong>.</p><p>Instead of publishing directly to a particular queue, the producer publishes a message to an exchange.</p><p>The exchange uses its routing rules to decide which queues should receive the message.</p><p>For our ShopNow application, we could use a fan-out exchange:</p><ol><li>The order service publishes an OrderCreated message to the exchange.</li><li>The exchange routes a copy to the email queue.</li><li>It routes another copy to the inventory queue.</li><li>It routes another copy to the analytics queue.</li><li>Each service processes its own queue independently.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZcsY3udBi7ka0zcGE1PDUw.png" /><figcaption>Conceptual flow: one publication, multiple independent queues.</figcaption></figure><p>This solves the problem of distributing a message to multiple services without requiring the producer to publish each copy itself.</p><p>RabbitMQ also supports other routing patterns, so fan-out is just one of the ways it can distribute messages.</p><p>But let’s ask one more question.</p><h4>What If We Need to Read the Same Information Again Later?</h4><p>Suppose <em>ShopNow</em> grows, and we introduce a new analytics service that needs to recalculate sales statistics for the last seven days.</p><p>With a conventional queue, messages may already have been acknowledged and removed after processing. The new service cannot simply go back and read those old messages from that queue.</p><p>We could retrieve the historical data from the database or build another mechanism to retain and replay messages.</p><p>But what if we want a system where retaining a stream of records and allowing consumers to read it independently are fundamental parts of the design?</p><p>This brings us to another approach: <strong>event streaming</strong>.</p><h3>Approach D — From Messaging Queues to Event Streaming</h3><p>So far, we’ve seen how message queues help us distribute work to different services.</p><p>But what if a new analytics service joins <em>ShopNow</em> and wants to read events from the last seven days? Or what if an existing service wants to read the same events again?</p><p>In a traditional queue, messages may already have been removed after processing. So, we need another way to retain messages and let consumers read them independently.</p><p><strong>Think of it like reading books.</strong></p><p>Imagine you’re reading three different books. You can stop reading one book today and continue from the same page tomorrow. You can also go back and read an earlier chapter whenever you want.</p><p>You keep a separate bookmark for each book, so you always know where you left off.</p><p>An event streaming system follows a similar idea:</p><ul><li><strong>Topics are like books.</strong> Each topic contains a stream of records.</li><li><strong>Consumers are like readers.</strong> Different consumers can read the same topic independently.</li><li><strong>Offsets are like bookmarks.</strong> They help consumers keep track of their reading position and continue from where they left off.</li></ul><p>A consumer can also move back to an earlier position and read the records again, as long as those records are still retained.</p><p>This means consumers can process the same stream independently, at their own pace, without removing records for everyone else.</p><p><strong>This is the idea behind event streaming, and Apache Kafka is built around this model.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*d1YfDiOJpbGAWpYsiI82Hg.png" /></figure><h3>Thankyou For Reading</h3><p>We started with a simple question: <strong>How can services perform work independently without making other services wait?</strong></p><p>Each approach solves a problem, and each comes with its own trade-offs. The right choice depends on what our application needs.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Nmpt4YyGXApb7m8ktOSxgg.png" /><figcaption>I was actually thinking of keeping this as the thumbnail for this blog.</figcaption></figure><p>But this journey raises another question.</p><p><strong>How does Apache Kafka actually make event streaming possible?</strong></p><p>How does it store millions of events, allow multiple consumers to read them independently, and keep everything working as the system grows?</p><p>In the next blog, we’ll start with Kafka’s basic architecture and understand how it works.</p><p>Then, we’ll gradually dive into its internal architecture and explore the engineering decisions behind it — why Kafka is designed the way it is, and how those decisions make its capabilities possible.</p><p>See you in the next one!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7b948a9dc12f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[1. Before We Talk About Kafka, Let’s Understand the Problem]]></title>
            <link>https://hiimvikash.medium.com/1-before-we-talk-about-kafka-lets-understand-the-problem-babfaac8f135?source=rss-6530c2ff5590------2</link>
            <guid isPermaLink="false">https://medium.com/p/babfaac8f135</guid>
            <category><![CDATA[apache-kafka]]></category>
            <category><![CDATA[kafka]]></category>
            <category><![CDATA[asynchronous]]></category>
            <category><![CDATA[synchronous]]></category>
            <dc:creator><![CDATA[Vikash Gupta]]></dc:creator>
            <pubDate>Sat, 24 Oct 2026 08:36:56 GMT</pubDate>
            <atom:updated>2026-10-24T08:44:17.575Z</atom:updated>
            <content:encoded><![CDATA[<p>Our goal is to discover the need for a messaging system ourselves, instead of starting with a definition from a textbook.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SWBJ6VzQl7LB7dHVfkLYtA.png" /></figure><h3>0. Synchronous vs Asynchronous Work</h3><p>Think about how you communicate with people in your daily life.</p><p><strong>Synchronous work is like calling someone on the phone.</strong> You call them, and you generally wait for them to answer so you can have a conversation. Both of you are involved in the interaction at the same time.</p><p><strong>Asynchronous work is like sending someone a WhatsApp message.</strong> You send the message and continue with your day. The other person can read it, reply, or take the required action whenever they’re available. You don’t need to wait for them to finish before moving on.</p><p>The same idea applies when applications communicate with each other.</p><ul><li><strong>Synchronous communication:</strong> One service sends a request to another service and waits for its response before continuing.</li><li><strong>Asynchronous communication:</strong> One service initiates work without having to wait for the other service to finish it. The work can be handled separately, and the result or acknowledgement can arrive later if needed.</li></ul><p>Our goal is to discover the need for a messaging system ourselves, instead of starting with a definition from a textbook.</p><h3>1. Start with a real-world problem</h3><p>Imagine we’re building an e-commerce application called <em>ShopNow</em>.</p><p>A customer clicks the Place Order button. What needs to happen?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Q1ZyEQ-BYkdtkKBMbopyjQ.png" /></figure><p>Here’s our first question: Should the order service perform every one of these tasks itself?</p><p>Initially, it might seem reasonable. Let’s implement that approach and discover its limitations.</p><h3>2. Approach A — One service calls everyone directly</h3><p>Suppose our Express backend directly calls the payment, inventory, email, and analytics services.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RBMamrd9hHzOsmnDJY7geg.png" /></figure><p>In Node.js, the logic might look something like this:</p><pre>app.post(&quot;/orders&quot;, async (req, res) =&gt; {<br>  const order = await db.orders.create({<br>    data: req.body,<br>  });<br><br>  await paymentService.process(order);<br>  await inventoryService.reserve(order);<br>  await emailService.sendConfirmation(order);<br>  await analyticsService.trackOrder(order);<br><br>  res.status(201).json(order);<br>});</pre><p>Now, should the customer have to wait for every one of these tasks to finish before receiving a response?</p><p>Some tasks may need to happen immediately, while others can be handled in the background. For example, the application may need to confirm that the order was accepted, but it doesn’t necessarily need to wait for an analytics dashboard to update.</p><p>This is where asynchronous work becomes useful. It allows us to <strong><em>separate tasks</em></strong> <strong>that need an immediate response</strong> <strong>from tasks</strong> <strong>that can be completed independently.</strong></p><h4>Problem 1 — Your application becomes tightly coupled</h4><p>Imagine the email service is unavailable.</p><p>Your order service directly depends on that service to complete its request. Depending on how the failure is handled, the customer may receive an error even though the order was already saved and the payment may have succeeded.</p><p>Now imagine you add a fraud-detection service, a loyalty-points service, and a recommendation service. The order service must know about more and more downstream services.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QS58zFNPq4xVIfH1sEr6qw.png" /></figure><p>The underlying issue isn’t that APIs are bad. Direct API calls are useful when a service needs an immediate answer.</p><p>The problem arises when the order service must coordinate many independent tasks that don’t at all need to finish before it can acknowledge the order.</p><blockquote><strong>First principle:</strong> If two operations don’t need to happen together, forcing them into the same synchronous workflow creates unnecessary dependencies.</blockquote><h4>Problem 2 — Latency accumulates</h4><p>Suppose each downstream service takes this long to respond.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wzIWy9czDutJG5ZlVn4Vkg.jpeg" /></figure><p>The total is the sum because our example uses sequential await calls.</p><p>Could we use Promise.all() to execute some calls concurrently? Yes. That can reduce waiting time, but it doesn&#39;t solve dependency failures, durable handoff, or the fact that downstream services may be unavailable.</p><p>And payment and inventory operations may have business dependencies that make blindly running everything in parallel unsafe.</p><blockquote><strong>First principle:</strong> Reducing latency and decoupling services are different problems.</blockquote><h4>Problem 3 — A temporary failure can cause lost work</h4><p>Let’s consider a more interesting scenario.</p><ol><li>The order service successfully saves order #101 in PostgreSQL.</li><li>It calls the email service.</li><li>The email service is down.</li><li>The order request fails or returns an error.</li></ol><p>The order exists, but the confirmation email hasn’t been sent.</p><p>What happens when the email service comes back online?</p><p>Nothing automatically tells it that an email is still pending, unless we have built a retry mechanism or stored that work somewhere.</p><p>We could add retries, but now we must answer more questions:</p><ul><li>How many times should we retry?</li><li>What if the email service is down for an hour?</li><li>Where do we store the pending work?</li><li>What if the application crashes before retrying?</li><li>What if a retry sends the same email twice?</li></ul><blockquote>We have discovered a new requirement: <strong>we need a reliable way to hand work to another service, even when that service is temporarily unavailable.</strong></blockquote><h4>Problem 4 — The producer and consumer work at different speeds</h4><p>Let’s say our application receives 1,000 orders per second, but the email service can process only 300 email jobs per second.</p><p>If we require every request to wait for the email service, its capacity can limit the order workflow.</p><p>If we keep sending work faster than the email service can handle it, the system needs a way to absorb the excess work and let the email service catch up.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2lFuqb5YhYEkx0V4K8g_ww.png" /></figure><p>This is where asynchronous messaging becomes especially useful.</p><p>A messaging system can accept work at one rate and let consumers process it at another rate. The system still needs sufficient storage, monitoring, and capacity planning.</p><h3>3. Approach B — Let Services Work Independently</h3><h4>Let’s list what our architecture needs.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4lGBwEX1vntBLvGRVbuXKg.png" /></figure><p>We’ve identified a<strong> </strong>few<strong> problems:</strong><em> the order service depends on other services, tasks can get lost when a service is down, and some services process work slower than others.</em></p><p><strong>So, how can we solve these problems? </strong>In Approach A, our order service directly calls the payment, inventory, email, and analytics services. This means it has to coordinate all of them.</p><p>But think about our WhatsApp analogy. Instead of calling someone and waiting for them to respond, we can send them a message and continue with our work.</p><p><strong>Can we apply the same idea to our application?</strong></p><p>Imagine that when a customer places an order, the order service saves it and puts the required background work somewhere safe. The email service can pick up the task when it’s available, and the analytics service can process the information independently.</p><p>The order service no longer needs to wait for every service to finish its work.</p><h4>How would this look?</h4><ol><li>The customer places an order.</li><li>The order service saves the order.</li><li>It hands off the required information for background processing.</li><li>The email, inventory, and analytics services process their respective tasks independently.</li></ol><p>For example, if the email service is temporarily down, the order service doesn’t need to keep waiting for it. The pending email task can remain stored until the email service is ready to process it.</p><h4>But where do we store this work?</h4><p>We need something that can accept work from one service, keep it available, and allow another service to retrieve it later.</p><p>We could build our own system using a database and a background worker. But then we’d need to handle pending tasks, retries, failures, and multiple workers ourselves.</p><p>This is the basic idea behind a <strong>messaging system</strong>: <em>one application sends information, and another application can process it separately.</em></p><p>This brings us to the next question: what kind of messaging system should we use, and how do different messaging systems work?</p><p>We’ll explore that before looking at Kafka itself.</p><h3>What We Figured Out :-</h3><p>We understood why services need to work independently and why reliable communication matters.</p><p>In the next blog, we’ll explore different approaches, from databases to messaging queues, and gradually discover Kafka and how it works.</p><p><em>Thankyou for reading.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=babfaac8f135" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[3.1. The OOP Core: Designing Better Classes with Inheritance.]]></title>
            <link>https://hiimvikash.medium.com/3-1-the-oop-core-designing-better-classes-with-inheritance-4228bbd1a25e?source=rss-6530c2ff5590------2</link>
            <guid isPermaLink="false">https://medium.com/p/4228bbd1a25e</guid>
            <category><![CDATA[oops-concepts]]></category>
            <category><![CDATA[inheritance]]></category>
            <category><![CDATA[object-oriented-design]]></category>
            <category><![CDATA[java]]></category>
            <dc:creator><![CDATA[Vikash Gupta]]></dc:creator>
            <pubDate>Thu, 30 Jul 2026 09:01:42 GMT</pubDate>
            <atom:updated>2026-07-30T09:01:42.955Z</atom:updated>
            <content:encoded><![CDATA[<p>If you’ve been following this series, in the last blog we built our very first class for a simple racing game. We created a Car class with fields like brand, model, and speed, along with methods such as start(), accelerate(), and displayStatus(). Then we created multiple car objects from that blueprint and watched each one maintain its own independent state.</p><p>Everything felt neat, organised, and honestly… pretty satisfying.</p><p>Let’s continue building that same racing game. Until now, our game only had cars. But one day, the game designer comes to us and says,</p><p><em>“Can we also let players race on bikes?” </em>Sounds like a reasonable request. So we create a Bike class.</p><p>Just like our Car class, it needs a brand, a model, and a speed. It also needs methods like start(), accelerate(), and displayStatus() because bikes also participate in races.</p><p>A few days later, another request arrives.</p><p><em>“Let’s make the game more interesting by adding trucks as well.” </em>Alright. Now we create a Truck class. And once again, we’re writing the same fields…brand, model, speed. And the same methods… start(), accelerate(), displayStatus().</p><p>At this point, something starts feeling… odd.</p><p>Not because the code is wrong. The game still works perfectly. But because we’re writing the same things over and over again.</p><p>Now imagine it’s a few months later. The game introduces a new feature.</p><p>Every vehicle in the game should now have a unique registrationNumber.</p><p>Suddenly, you have to update the Car class. Then the Bike class. Then the Truck class. And every other vehicle class you’ve added to the game.</p><p>The exact same change…In multiple places.</p><p>A few weeks later, another update comes in. Every vehicle should also have an engineNumber. Once again…The same update. Everywhere.</p><p>After doing this a few times, you naturally begin asking yourself,</p><p><em>“Why am I copying the same code into every vehicle?”</em></p><p><em>“These are all vehicles participating in the same racing game.”</em></p><p><em>“They already share so much in common.”</em></p><p>And that’s exactly the thought Object-Oriented Programming wants us to have.</p><p>Not every class is completely unique. Sometimes multiple classes are simply specialised versions of the same thing.</p><p>A <strong>Car is a Vehicle. </strong>A <strong>Bike is a Vehicle. </strong>A <strong>Truck is a Vehicle.</strong></p><p>Each one has its own identity and may have its own unique behaviour, but they all share a common set of properties and behaviours because, at the end of the day, they’re all vehicles.</p><p>So instead of rewriting those common things again and again, wouldn’t it be nice if we could define them just once and let every specialised class automatically get them?</p><p>That’s exactly the problem we’ll solve in this blog. And the OOP concept that helps us do that is called <strong>Inheritance</strong>.</p><h3>So… What Exactly Is Inheritance?</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tjAqeY1OSc4G50jGGQXetQ.png" /></figure><p>If we think about the problem we just faced, the issue wasn’t that our classes were wrong.</p><p>The problem was that <strong>they all shared a lot of common information</strong>, yet we were writing that common code again and again.</p><p>This is exactly where Inheritance comes in.</p><p>Inheritance allows one class to reuse the properties and behaviours of another class instead of writing everything from scratch.</p><p>Instead of creating everything again, it simply says, <em>“I’ll take everything that already exists there, and then I’ll add only what’s unique about me.”</em></p><p>Let’s go back to our racing game.</p><p>Every vehicle has: a<em> brand, </em>a <em>model, </em>a <em>speed. </em>Every vehicle can: start(), accelerate(), and displayStatus().</p><p>So rather than placing these members inside every individual class, we can create one common class called Vehicle.</p><p>Now the specialised classes simply build on top of it.</p><pre>Vehicle<br>│<br>├── Car<br>├── Bike<br>└── Truck</pre><p>Suddenly, our code becomes much cleaner.</p><ul><li>The Vehicle class contains everything common to all vehicles.</li><li>The Car class only contains things that are unique to cars.</li><li>The Bike class only contains things that are unique to bikes.</li><li>The Truck class only contains things that are unique to trucks.</li></ul><p>Instead of repeating ourselves, we’re simply reusing what already exists. And that’s the biggest purpose of inheritance.</p><p>Not to create deep class hierarchies. Not to make code look fancy. But to <strong>avoid duplication while modelling real-world relationships naturally.</strong></p><h3>Parent Class and Child Class</h3><p>Now that we have a common Vehicle class, let&#39;s learn the two most common terms you&#39;ll hear whenever people talk about inheritance.</p><p>The class whose properties and behaviours are reused is called the <strong>Parent Class</strong> (also known as the <strong>Base Class</strong> or <strong>Superclass</strong>).</p><pre>Vehicle</pre><p>The class that inherits from it is called the <strong>Child Class</strong> (also known as the <strong>Derived Class</strong> or <strong>Subclass</strong>).</p><pre>Vehicle<br>   △<br>   │<br>  Car</pre><p>Here,</p><ul><li>Vehicle is the Parent Class.</li><li>Car is the Child Class.</li></ul><p>Since Car inherits from Vehicle, it automatically gets access to all the reusable members defined inside Vehicle.</p><p>Instead of writing those members again, the child simply reuses them and focuses only on what’s unique about itself.</p><h3>The Most Important Rule of Inheritance</h3><p>Whenever you’re wondering whether inheritance is the right choice, ask yourself one simple question:</p><blockquote><strong><em>Can I honestly say</em> “A Child IS A Parent”?</strong></blockquote><p>For our example,</p><ul><li>A Car <strong>is a</strong> Vehicle. ✅</li><li>A Bike <strong>is a</strong> Vehicle. ✅</li><li>A Truck <strong>is a</strong> Vehicle. ✅</li></ul><p>These relationships make complete sense. That’s why inheritance fits naturally here.</p><p>This is called the <strong>IS-A Relationship</strong>, and it’s one of the easiest ways to recognise when inheritance is appropriate.</p><h3>Building Our First Inheritance Hierarchy</h3><p>Let’s go back to our racing game one last time. Visually, our design now looks like this:</p><pre>                Vehicle           <br>                   △<br>          ┌────────┼────────┐<br>          │        │        │<br>         Car      Bike    Truck</pre><p>Notice what’s happening here.</p><p>Vehicle sits at the top because it contains everything that is common to all vehicles.</p><p>Car, Bike, and Truck don&#39;t need to redefine those common members anymore. They simply build upon Vehicle and only add what&#39;s unique about themselves.</p><p>This relationship is exactly what we call <strong>Inheritance</strong>.</p><p>In Java, we express this relationship using the extends keyword.</p><pre>class Vehicle {<br>}</pre><pre>class Car extends Vehicle {<br>}<br>class Bike extends Vehicle {<br>}<br>class Truck extends Vehicle {<br>}</pre><p>The moment Java sees the extends keyword, It understands that <strong>Car, Bike and Truck is a Vehicle</strong>. This is why extends is often read as:</p><blockquote><strong><em>Car extends Vehicle</em></strong><em> → </em>Car inherits from Vehicle.</blockquote><p>Or even more naturally,</p><blockquote><strong>Car is a specialised version of Vehicle.</strong></blockquote><p>Now let’s make our Vehicle class contain everything that is common.</p><pre>class Vehicle {    <br>    protected String brand;<br>    protected String model;<br>    protected int speed;<br><br>    public void start() {<br>        System.out.println(&quot;Vehicle Started&quot;);<br>    }<br>    public void accelerate() {<br>        speed += 10;<br>        System.out.println(brand + &quot; - &quot; + model + &quot; is accelerating at&quot; +speed+ &quot; km/h&quot;);<br>    }<br>    public void displayStatus() {<br>        System.out.println(brand + &quot; &quot; + model + &quot; : &quot; + speed + &quot; km/h&quot;);<br>    }<br>}</pre><p>And now look at our Car class.</p><pre>class Car extends Vehicle {<br><br>    private boolean nitroActivated;<br><br>    public void activateNitro() {<br>        nitroActivated = true;<br>    }<br>}<br><br>class Bike extends Vehicle {<br><br>    private boolean swimMode;<br><br>    public void performSwim() {<br>        swimMode = true;<br>    }<br>}</pre><p>The Vehicle class already provides everything every vehicle needs, like starting, accelerating, and displaying its status.</p><p>The Car class only focuses on what&#39;s unique to a racing car.</p><p>In our game, cars have the ability to activate <strong>Nitro Boost</strong>, so that’s the only behaviour we added here.</p><h3>Let’s verify inheritance ourselves</h3><pre>public class Main {<br><br>    public static void main(String[] args) {<br><br>        Car ferrari = new Car();<br>        ferrari.brand = &quot;Ferrari&quot;;<br>        ferrari.model = &quot;488 GTB&quot;;<br>        ferrari.speed = 320;<br>        ferrari.accelerate();<br>        ferrari.activateNitro();<br><br>        Bike ducati = new Bike();<br>        ducati.brand = &quot;Ducati&quot;;<br>        ducati.model = &quot;Panigale V4&quot;;<br>        ducati.speed = 299;<br>        ducati.accelerate();<br>        ducati.performSwim();<br><br>        ferrari.displayStatus();<br>        ducati.displayStatus();<br>    }<br>}</pre><p><strong>Output</strong> :</p><pre>Ferrari - 488 GTB is accelerating at 330 km/h<br>Ducati - Panigale V4 is accelerating at 309 km/h<br>Brand: Ferrari, Model: 488 GTB, Speed: 320 km/h<br>Brand: Ducati, Model: Panigale V4, Speed: 299 km/h</pre><p><strong>you might be wondering…</strong></p><ul><li><em>“How can a </em><em>Car object use fields and methods that aren&#39;t even written inside the </em><em>Car class?&quot;</em></li><li>When we call ferrari.accelerate(), how does Java know where to find the accelerate() method ?</li><li><em>We only wrote one </em><strong><em>displayStatus()</em></strong><em> method inside the </em><strong><em>Vehicle</em></strong><em> class. Yet, when we call it using a </em><strong><em>Car</em></strong><em> object, it prints Ferrari’s details. And when we call the very same method using a Bike object, it prints Ducati’s details. How ?</em></li></ul><p>All of these questions have a single answer, and it lies in understanding the <strong>internal structure of an inherited object.</strong></p><h3>Internal Structure of an Inherited Object</h3><p>Let’s start with something we’re already familiar with. When we create a normal object like this : Vehicle vehicleObj=new Vehicle();</p><p>Java creates an object that contains everything defined inside the Vehicle class. You can visualize it like this:</p><pre>                Vehicle Object<br>        ┌─────────────────────────────┐<br>        │ brand                       │<br>        │ model                       │<br>        │ speed                       │<br>        │─────────────────────────────│<br>        │ start()                     │<br>        │ accelerate()                │<br>        │ displayStatus()             │<br>        └─────────────────────────────┘</pre><p>Nothing surprising here. The object simply contains everything that belongs to the Vehicle class.</p><p>Now let’s create a Car object. Car carObj=new Car();</p><p><em>At first glance, you might think Java creates an object that only contains the members written inside the </em><em>Car class. Something like this:</em></p><pre>                Car Object ❌<br>        ┌─────────────────────────────┐<br>        │ nitroActivated              │<br>        │─────────────────────────────│<br>        │ activateNitro()             │<br>        └─────────────────────────────┘</pre><p>But that’s <strong>not</strong> what actually happens.</p><p>Since Car extends Vehicle, Java first creates the <strong>Vehicle part</strong> of the object and then adds everything that belongs to the Car class. So the actual object looks like this:</p><pre>                 Car Object ✅<br>        ┌─────────────────────────────┐<br>        │        Vehicle Part         │<br>        │─────────────────────────────│<br>        │ brand                       │<br>        │ model                       │<br>        │ speed                       │<br>        │─────────────────────────────│<br>        │ start()                     │<br>        │ accelerate()                │<br>        │ displayStatus()             │<br>        ├─────────────────────────────┤<br>        │          Car Part           │<br>        │─────────────────────────────│<br>        │ nitroActivated              │<br>        │─────────────────────────────│<br>        │ activateNitro()             │<br>        └─────────────────────────────┘</pre><p>Take a moment to observe this structure carefully.</p><p>Although we created a <strong>Car object</strong>, it also contains the complete <strong>Vehicle part</strong> because <strong>a Car is a Vehicle</strong>.</p><p>And this one diagram already answers the first question we had.</p><blockquote>How can a Car object use fields and methods that aren&#39;t even written inside the Car class?</blockquote><p>Because those fields and methods are actually <strong>part of the object itself</strong>.</p><p>They aren’t borrowed from somewhere else. They exist inside <strong>every </strong><strong>Car object as part of its inherited </strong><strong>Vehicle portion.</strong></p><p>Now another interesting question comes up.</p><blockquote>If every Car object contains Vehicle part, does that mean two different Car or Bike objects share the same parent data?</blockquote><p>Let’s visualize them.</p><pre>                Ferrari (Car Object)<br>        ┌──────────────────────────────────┐ <br>        │         Vehicle Part             │<br>        │──────────────────────────────────│<br>        │ brand = Ferrari                  │<br>        │ model = 488 GTB                  │<br>        │ speed = 330                      │<br>        │──────────────────────────────────│<br>        │ start()                          │<br>        │ accelerate()                     │<br>        │ displayStatus()                  │<br>        ├──────────────────────────────────┤<br>        │           Car Part               │<br>        │──────────────────────────────────│<br>        │ nitroActivated = false           │<br>        │──────────────────────────────────│<br>        │ activateNitro()                  │<br>        └──────────────────────────────────┘<br><br>                 Ducati (Bike Object)<br>        ┌──────────────────────────────────┐<br>        │         Vehicle Part             │<br>        │──────────────────────────────────│<br>        │ brand = Ducati                   │<br>        │ model = Panigale V4              │<br>        │ speed = 309                      │<br>        │──────────────────────────────────│<br>        │ start()                          │<br>        │ accelerate()                     │<br>        │ displayStatus()                  │<br>        ├──────────────────────────────────┤<br>        │           Bike Part              │<br>        │──────────────────────────────────│<br>        │ swimMode = false                 │<br>        │──────────────────────────────────│<br>        │ performSwim()                    │<br>        └──────────────────────────────────┘   </pre><p>Both objects have a <strong>Vehicle part</strong>, but they are <strong>completely independent</strong> of each other.</p><p>Ferrari’s Vehicle part stores Ferrari&#39;s data. Ducati’s Vehicle part stores Ducati&#39;s data.</p><p>There is <strong>no shared </strong><strong>brand field</strong>, <strong>no shared </strong><strong>speed field</strong>, and <strong>no shared </strong><strong>model field</strong> between these objects.</p><p>Every object carries <strong>its own inherited state</strong>.<em> And this finally explains how same method produces different output.</em></p><p>When we execute: ferrari.displayStatus(); Java executes the displayStatus() method from <strong>Ferrari&#39;s own Vehicle part</strong>, so it prints Ferrari&#39;s details.</p><p>Likewise, when we execute: ducati.displayStatus(); Java executes the <strong>exact same method</strong>, but this time on <strong>Ducati’s own Vehicle part</strong>, so it prints Ducati’s details.</p><p>And because every object has its own inherited fields, the output is different.</p><blockquote>Classes define the blueprint. Objects hold the data. Inheritance reuses the blueprint, not the object.</blockquote><h4>How Java Finds Inherited Members</h4><p>Now let’s answer another question we had earlier.</p><blockquote>When we call ferrari.accelerate(), how does Java know where to find the accelerate() method?</blockquote><p>Java always starts searching from the object’s own class. In our case, the object <em>ferrari</em> is an instance of Car, so Java first checks the Car class.</p><pre>Car<br> │<br> ├── accelerate() ❌ Not Found<br> │<br> ▼<br>Vehicle<br> │<br> └── accelerate() ✅ Found</pre><p>Since Car doesn&#39;t define accelerate(), Java moves to its parent class, Vehicle, finds the method there, and executes it.</p><p>On the other hand, if we call: ferrari.activateNitro();, the search stops immediately because that method already exists inside the Car class.</p><pre>Car<br> │<br> └── activateNitro() ✅ Found</pre><p>That’s the basic lookup rule in inheritance.</p><blockquote>Java always searches from the child class first. If the requested member isn’t found, it keeps moving up the inheritance hierarchy until it finds it.</blockquote><p>Now here’s a more interesting question.</p><p><strong><em>What happens if both the parent and the child have a method with the same name? </em></strong>Which one will Java execute?</p><h3>What If the Child Wants to Do Things Differently?</h3><p>So far, every time we called: ferrari.accelerate();</p><p>Java searched the Car class, didn&#39;t find the method, moved to the Vehicle class, and executed the inherited implementation.</p><p>But what if our game designer comes back with another request?</p><blockquote><em>“A Ferrari shouldn’t accelerate like every other vehicle.”</em></blockquote><blockquote><em>“Cars should gain </em><strong><em>30 km/h</em></strong><em>, bikes should gain </em><strong><em>15 km/h</em></strong><em>, while trucks should still gain </em><strong><em>10 km/h</em></strong><em>.”</em></blockquote><p>Now we have a problem.</p><p>The Vehicle class currently has only one implementation:</p><pre>public void accelerate() {<br>    speed += 10;<br>}</pre><p>If every vehicle uses this method, then every vehicle accelerates in exactly the same way. But that’s not what we want anymore.</p><p>We want each child class to have its own version of accelerate(). Fortunately, Java allows us to do exactly that.</p><p><em>A child class can provide its </em><strong><em>own implementation</em></strong><em> of an inherited method. This is called </em><strong><em>Method Overriding</em></strong><em>.</em> For example, our Car class can override accelerate() like this:</p><pre>class Car extends Vehicle {<br>  private boolean nitroActivated;<br>    @Override<br>    public void accelerate() {<br>        speed += 30;<br>        System.out.println(brand + &quot; - &quot; + model + &quot; is accelerating at &quot; + speed + &quot; km/h&quot;);<br>    }<br>    public void activateNitro() {<br>        nitroActivated = true;<br>    }<br>}</pre><p>Notice something interesting. Both Vehicle and Car now have a method named accelerate().</p><p>So now when we execute: ferrari.accelerate();</p><p>Java starts searching from the Car class. This time, however, it immediately finds an accelerate() method inside Car itself.</p><pre>Car<br> │<br> └── accelerate() ✅ Found</pre><p>Since the method is found in the child class, Java doesn’t continue searching the parent. It simply executes the child’s implementation.</p><p>That’s exactly what <strong>Method Overriding</strong> means.</p><blockquote><strong>The child class provides its own implementation of an inherited method, replacing the parent’s implementation.</strong></blockquote><h3>The super Keyword</h3><p>So far, we’ve learned that a child class can inherit members from its parent and even override inherited methods.</p><p>But what if the child class wants to access something from its parent?</p><p>For example:</p><ul><li>We overrode a method, but we still want to execute the parent’s implementation.</li><li>Both the parent and child have a variable with the same name, and we want to access the parent’s variable.</li><li>We want to initialize the parent part of the object by calling its constructor.</li></ul><p>Java provides a single keyword for all these situations: <strong>super</strong>.</p><h4>What Exactly Is super?</h4><p>Remember the internal structure of a Car object that we saw earlier?</p><pre>           Car Object<br>┌──────────────────────────────┐<br>│        Vehicle Part          │<br>├──────────────────────────────┤<br>│          Car Part            │<br>└──────────────────────────────┘</pre><p>Whenever we write super, we&#39;re telling Java:</p><blockquote><strong>“Don’t work with the child part of this object. Work with its immediate parent part instead.”</strong></blockquote><p>You can think of super as a reference that points to the <strong>immediate parent portion of the current object.</strong></p><p>Because of that, super can be used in three different ways.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yjurBmPNH_RD3O4ouniZdQ.png" /></figure><p>Suppose we override accelerate() inside Car.</p><h4>1. Calling a Parent Method</h4><pre>@Override<br>public void accelerate() {<br>    super.accelerate();<br>    speed += 20;<br>}</pre><p>Here, super.accelerate(); tells Java,</p><blockquote><em>“Execute the </em><em>accelerate() method from the parent (</em><em>Vehicle) class.&quot;</em></blockquote><p>This allows us to reuse the parent’s implementation instead of writing everything again.</p><h4>2. Accessing a Parent Variable</h4><pre>class A{<br>  int a = 10;<br>}<br>class B extends A {<br>  int a = 20;<br>  void show(int a){<br>    sopln(a); // 30<br>    sopln(this.a); // 20<br>    sopln(super.a); // 10<br>  }<br>  <br>  psvm(){<br>    B ob1.new B();<br>    ob1.show(30);<br>  }<br>}</pre><h4>3. Calling the Parent Constructor</h4><pre>class Animal {<br><br>    Animal() {<br>        System.out.println(&quot;Animal Constructor&quot;);<br>    }<br>}<br><br>class Dog extends Animal {<br><br>    Dog() {<br>        System.out.println(&quot;Dog Constructor 🐶&quot;);<br>    }<br>}<br><br>public class Main {<br><br>    public static void main(String[] args) {<br>        new Dog();<br>    }<br>}<br><br>/** Output :-<br>Animal Constructor<br>Dog Constructor 🐶</pre><p>At first glance, this output looks a little surprising.</p><p>We only created a <strong>Dog</strong> object new Dog(); So why was the <strong>Animal</strong> constructor executed first?</p><p>We never explicitly called it. Where did it come from? and <strong>Why ?</strong></p><blockquote>A child constructor may <strong>depend on the parent part’s data</strong> that is initialized by the parent constructor. If Java allowed the child constructor to run first, it might try to use data that doesn’t exist yet.</blockquote><blockquote>To prevent this, Java always initializes the <strong>parent part</strong> of the object first and then the <strong>child part</strong>. That’s why super() is automatically inserted as the first statement of every child constructor (provided the parent has a no-argument constructor).</blockquote><p><strong>But what if the parent doesn’t have a no-argument constructor?</strong></p><blockquote>Java can’t automatically call it because it has <strong>no idea what values you want to pass</strong>. So instead of inserting super() automatically, <strong>we must explicitly call the appropriate parent constructor</strong> using super(...).</blockquote><p>For example :-</p><pre>class Employee {<br>    String empId;<br><br>    Employee(String id) {<br>        this.empId = id;<br>    }<br>}<br><br>class Developer extends Employee {<br><br>    Developer(int did) {<br>        super(&quot;DEV-&quot;+String.valueOf(did));<br>        System.out.println(empId); // DEV-103<br>    }<br>}</pre><p>If we don’t explicitly call super(...) here, the <strong>code won&#39;t compile </strong>❌ because the parent class doesn&#39;t have a no-argument constructor that Java can invoke automatically.</p><h4>Things to Remember</h4><p>Before we move on, here are a few important rules about super:</p><ul><li><strong>Constructors are not inherited.</strong> However, a child constructor can invoke the parent’s constructor using super(...).</li><li><strong>super can only be used inside a subclass.</strong> Since it refers to the <strong><em>immediate parent</em></strong> of the current object, it doesn&#39;t make sense to use it outside a child class.</li><li><strong>super cannot be used inside a </strong><strong>static method.</strong> Static methods belong to the class itself, not to any particular object. Since super refers to the parent portion of the <strong>current object</strong>, there is no object available inside a static method.</li><li><strong>super always refers to the immediate parent class.</strong> Even if there are multiple levels of inheritance, super can only access members of the direct parent, not grandparents or ancestors further up the hierarchy. (This follows directly from the definition of super as the immediate parent reference.)</li><li>The <strong>first statement</strong> inside every constructor must be either super(...) or this(...)—never both.</li></ul><pre>          Dog Object<br>┌──────────────────────────────┐<br>│         Animal Part          │<br>│──────────────────────────────│<br>│ name                         │<br>│ sound()                      │<br>├──────────────────────────────┤<br>│          Dog Part            │<br>│──────────────────────────────│<br>│ name                         │<br>│ sound()                      │<br>└──────────────────────────────┘<br><br>Inside Dog Class, <br>this.name -&gt; [use Dog Part] &amp; <br>super.name -&gt; [use Animal Part]</pre><h3>When to Use Inheritance</h3><p>Inheritance is powerful, but it should be used intentionally, only when it truly models a real-world relationship. Getting this decision wrong early in your design leads to code that’s hard to change, hard to test, and hard to reason about.</p><p>Here’s a practical checklist.</p><h4>Use inheritance when:</h4><ul><li>There is a clear “is-a” relationship<strong> </strong>(e.g., Dog is an Animal, Car is a Vehicle). If you can&#39;t say &quot;X is a Y&quot; naturally, inheritance is probably the wrong tool. These relationships belong in composition.</li><li>The parent class defines common behavior or data that children should share. For example, all vehicles have a startEngine() method, so putting it in the parent avoids duplicating it across every vehicle type.</li><li>The child class does not violate the behavior expected from the parent. If someone has a Vehicle reference pointing to an ElectricCar, every Vehicle method should still work as expected.</li><li>You want to promote code reuse through shared logic and structure, and the hierarchy is shallow (2–3 levels at most).</li></ul><h4>Avoid inheritance when:</h4><ul><li>The relationship is “has-a” or “uses-a” rather than “is-a”. A Car has an Engine, it is not an Engine. A Printer uses a Logger, it is not a Logger.</li><li>You want to combine behaviors from multiple sources dynamically. Inheritance locks you into a single parent at compile time, while composition lets you mix and match components freely.</li><li>You need runtime flexibility to swap behaviors. With composition, you can inject different implementations (swap a FileLogger for a ConsoleLogger). With inheritance, the parent relationship is fixed.</li><li>You want to avoid tight coupling between child and parent internals. Changes to a parent class ripple down to every child in the hierarchy, which is risky in large codebases.</li></ul><p>When in doubt, start with composition. You can always refactor toward inheritance later if a genuine “is-a” hierarchy emerges. Going the other direction, untangling a deep inheritance tree into composition, is much harder.</p><h3>Practical Example: Notification System</h3><p>Let’s apply inheritance to a completely different domain to show that these patterns aren’t limited to vehicles. Imagine you’re building a notification system that can send messages through different channels: email, SMS, and push notifications.</p><p>All notification types share common properties: a recipient, a message, and a timestamp. They all need a formatHeader() method that produces a consistent header format. But the send() method works differently for each channel, email needs a subject line, SMS has a character limit, and push notifications have a device token and priority level.</p><pre>import java.time.LocalDateTime;<br>import java.time.format.DateTimeFormatter;<br><br>class Notification {<br>    protected String recipient;<br>    protected String message;<br>    protected String timestamp;<br><br>    public Notification(String recipient, String message) {<br>        this.recipient = recipient;<br>        this.message = message;<br>        this.timestamp = LocalDateTime.now()<br>            .format(DateTimeFormatter.ofPattern(&quot;yyyy-MM-dd HH:mm:ss&quot;));<br>    }<br><br>    public String formatHeader() {<br>        return &quot;[&quot; + timestamp + &quot;] To: &quot; + recipient;<br>    }<br><br>    public void send() {<br>        System.out.println(formatHeader());<br>        System.out.println(&quot;Message: &quot; + message);<br>    }<br>}<br><br>class EmailNotification extends Notification {<br>    private String subject;<br><br>    public EmailNotification(String recipient, String message, String subject) {<br>        super(recipient, message);<br>        this.subject = subject;<br>    }<br><br>    @Override<br>    public void send() {<br>        System.out.println(formatHeader());<br>        System.out.println(&quot;Subject: &quot; + subject);<br>        System.out.println(&quot;Body: &quot; + message);<br>        System.out.println(&quot;Status: Email delivered&quot;);<br>    }<br>}<br><br>class SMSNotification extends Notification {<br>    private String phoneNumber;<br>    private static final int MAX_LENGTH = 160;<br><br>    public SMSNotification(String recipient, String message, String phoneNumber) {<br>        super(recipient, message);<br>        this.phoneNumber = phoneNumber;<br>    }<br><br>    @Override<br>    public void send() {<br>        System.out.println(formatHeader());<br>        System.out.println(&quot;Phone: &quot; + phoneNumber);<br>        String smsBody = message.length() &gt; MAX_LENGTH<br>            ? message.substring(0, MAX_LENGTH - 3) + &quot;...&quot;<br>            : message;<br>        System.out.println(&quot;SMS: &quot; + smsBody);<br>        System.out.println(&quot;Status: SMS sent (&quot; + smsBody.length() + &quot;/&quot; + MAX_LENGTH + &quot; chars)&quot;);<br>    }<br>}<br><br>class PushNotification extends Notification {<br>    private String deviceToken;<br>    private String priority;<br><br>    public PushNotification(String recipient, String message,<br>                            String deviceToken, String priority) {<br>        super(recipient, message);<br>        this.deviceToken = deviceToken;<br>        this.priority = priority;<br>    }<br><br>    @Override<br>    public void send() {<br>        System.out.println(formatHeader());<br>        System.out.println(&quot;Device: &quot; + deviceToken.substring(0, 8) + &quot;...&quot;);<br>        System.out.println(&quot;Priority: &quot; + priority);<br>        System.out.println(&quot;Alert: &quot; + message);<br>        System.out.println(&quot;Status: Push notification delivered&quot;);<br>    }<br>}<br><br>public class Main {<br>    public static void main(String[] args) {<br>        EmailNotification email = new EmailNotification(<br>            &quot;alice@example.com&quot;, &quot;Your order has been shipped!&quot;, &quot;Order Update&quot;);<br>        email.send();<br><br>        System.out.println();<br><br>        SMSNotification sms = new SMSNotification(<br>            &quot;Bob&quot;, &quot;Your verification code is 482910.&quot;, &quot;+1-555-0123&quot;);<br>        sms.send();<br><br>        System.out.println();<br><br>        PushNotification push = new PushNotification(<br>            &quot;Charlie&quot;, &quot;New message from Alice&quot;,<br>            &quot;d8a3f4b2c1e5a9b7&quot;, &quot;high&quot;);<br>        push.send();<br>    }<br>}</pre><h4>Why This Design Works</h4><ul><li><strong>Shared logic is written once.</strong> The recipient, message, and timestamp fields are defined in Notification. The formatHeader() method is inherited by all three notification types, producing a consistent header format across email, SMS, and push. If you want to change the timestamp format, you change one method.</li><li><strong>Each child encapsulates channel-specific complexity.</strong> SMSNotification handles the 160-character limit. PushNotification manages device tokens and priority. EmailNotification adds a subject line. None of these details leak into the parent or into each other.</li><li><strong>Adding a new channel is simple.</strong> Need Slack notifications? Create SlackNotification extends Notification, add a webhookUrl field, override send(). No existing code changes.</li></ul><p><em>That’s it. Thank you so much for reading!</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4228bbd1a25e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[03. The OOP Core: Classes & Objects Beyond Definitions]]></title>
            <link>https://hiimvikash.medium.com/03-the-oop-core-classes-objects-beyond-definitions-899976a0ceb1?source=rss-6530c2ff5590------2</link>
            <guid isPermaLink="false">https://medium.com/p/899976a0ceb1</guid>
            <category><![CDATA[class]]></category>
            <category><![CDATA[oops-in-java]]></category>
            <category><![CDATA[oops-concepts]]></category>
            <category><![CDATA[java]]></category>
            <dc:creator><![CDATA[Vikash Gupta]]></dc:creator>
            <pubDate>Tue, 21 Jul 2026 11:30:10 GMT</pubDate>
            <atom:updated>2026-07-21T11:40:20.166Z</atom:updated>
            <content:encoded><![CDATA[<p>We’ve finally reached the part everyone has heard about: <strong>Encapsulation. Inheritance. Polymorphism. Abstraction.</strong></p><p>And I’m guessing some of you are already thinking, <em>“Please don’t turn this into another textbook chapter.”</em></p><p>I promise, that’s not what I want either.</p><p>My goal isn’t to make you memorize fancy terms. It’s to help you experience them. So by the time we finally put names like <em>Encapsulation</em> or <em>Polymorphism</em> on the screen, they’ll be already familiar.</p><p>One more thing before we begin.</p><p>Throughout this series, all the examples and code will be in <strong>Java</strong>. Not because OOP belongs to Java — it doesn’t. I’m choosing Java simply because it’s the language I’ve been learning and writing since Class 9, so it’s the language I naturally think in when explaining these ideas.</p><p>The concepts themselves are much bigger than any programming language. So even if you write JavaScript, Python, C++, Go, or anything else, don’t worry about the syntax. Just focus on understanding the ideas.</p><p>You can always translate the code into your favorite language later… and if you get stuck, well, ChatGPT is just a prompt away.</p><p>We ended the last blog with a simple idea.</p><blockquote>Software is made up of independent things that collaborate with each other.</blockquote><p>We think in terms of <strong>things</strong>. Things that have <strong>information</strong>. Things that can <strong>perform actions. </strong>Things that exist independently from one another.</p><p>A <strong>Customer</strong>, A <strong>Product</strong>, An <strong>Order</strong>. A <strong>Payment</strong>. An <strong>Inventory</strong>. A <strong>Notification</strong>.</p><p>Once we’ve identified the things in our system, we need a way to describe them in code.</p><p>Because every object-oriented system starts with one simple question:</p><blockquote>How do I take the world I understand…and recreate it inside my program?</blockquote><p><strong>And <em>classes</em> and <em>objects</em> are OOP’s answer to that question.</strong></p><h3>Classes</h3><p>And now that we’ve agreed that software is made up of things, the next question becomes:</p><blockquote><strong>How do we actually describe those things in code?</strong></blockquote><p>Let’s go back to our racing game.</p><p>Suppose I ask you:</p><blockquote>“Tell me about your car.”</blockquote><p>You probably wouldn’t say, <em>“Well, it’s an instance of a class.”</em></p><p>You’d say something much simpler.</p><blockquote>“It’s a Hyundai i20.”, “It’s white in color.”, “It’s a petrol variant.”, “Its fuel tank is half full.”, “it’s v10 retro engine”</blockquote><p>And if I ask, <em>“What can it do?”</em>,</p><p>you’d probably answer:</p><blockquote>“It can accelerate.”, “It can brake.”, “It can honk.”, “It can lock and unlock.”, “It can turn on the headlights.”</blockquote><p>Notice what just happened.</p><p>Without knowing anything about OOP terminology, you naturally described your car in two ways.</p><p>First, you described <strong>what it has</strong>.</p><pre>Brand: Hyundai<br>Model: i20<br>Color: White<br>Fuel Type: Petrol<br>Fuel Level: Half tank<br>Engine Type: v10 retro<br>Odometer Reading: 35,000 km</pre><p>Then, you described <strong>what it can do</strong>.</p><pre>Accelerate<br>Brake<br>Honk<br>Lock<br>Unlock<br>Turn on headlights</pre><p>And that’s exactly how OOP starts thinking.</p><p>Every real-world thing can usually be understood by asking just two questions:</p><blockquote>What <strong>information</strong> does it carry? What <strong>actions</strong> can it perform?</blockquote><p>Now imagine you’re building this game and discussing it with your teammates before writing any code.</p><p>You might say:</p><blockquote>“Every car in our game should have a brand, a model, a speed, and Nitro information. Also, every car should be able to accelerate, brake, drift, and activate Nitro.”</blockquote><p>That statement doesn’t create a car. You can’t race with it. It’s simply a description of what a car should look like. And that description is what we call a <strong>Class</strong>.</p><blockquote>So if we translate everything we just discussed into Java, our “description” of a car would look something like this:</blockquote><pre>public class Car {<br>    // Attributes<br>    private String brand;<br>    private String model;<br>    private int speed;<br><br>    // Constructor<br>    public Car(String brand, String model) {<br>        this.brand = brand;<br>        this.model = model;<br>        this.speed = 0;<br>    }<br><br>    // Method to accelerate<br>    public void accelerate(int increment) {<br>        speed += increment;<br>    }<br><br>    // Method to display info<br>    public void displayStatus() {<br>        System.out.println(brand + &quot; is running at &quot; + speed + &quot; km/h.&quot;);<br>    }<br>}</pre><p>Notice how the code is simply a translation of our conversation.</p><ul><li>The things we said a car <strong>has</strong> became <strong>variables (also called fields or attributes)</strong>.</li><li>The things we said a car <strong>can do</strong> became <strong>methods (functions inside a class)</strong>.</li></ul><p>But here’s the important part. This code still hasn’t created a single car.</p><p>There isn’t a white Hyundai i20 anywhere in memory yet.</p><p>We’ve only written the <strong>description</strong> of what every car in our racing game should look like.</p><p>And that description is exactly what we call a <strong>Class</strong>.</p><p>But a class by itself doesn’t do anything. It’s just a template. To actually use it, we need to create objects.</p><h3>Objects</h3><p>But there’s still one problem.</p><p>We have a description of a car, but we still don’t have <strong>an actual car</strong>. A class by itself can’t participate in a race, accelerate, or drift. It’s simply a blueprint sitting inside our source code.</p><p>Imagine the player clicks <strong>“Start Race.”</strong> The game now needs to place an actual car on the track. A blueprint can’t do that. It needs something real — something with its own color, its own engine, its own fuel level, and its own speed.</p><p>That’s exactly what we create from a class.</p><p>Whenever we ask Java to build one actual thing from a class, it creates what we call an <strong>Object</strong>. You can think of it as saying:</p><blockquote>“Take this blueprint and build one actual car for me.”</blockquote><p>Let’s create a couple of cars from our Car class.</p><pre>public class Main {<br><br>    public static void main(String[] args) {<br><br>        Car corolla = new Car(&quot;Toyota&quot;, &quot;Corolla&quot;);<br>        Car mustang = new Car(&quot;Ford&quot;, &quot;Mustang&quot;);<br><br>        corolla.accelerate(20);<br>        mustang.accelerate(40);<br><br>        corolla.displayStatus();<br><br>        System.out.println(&quot;----------------&quot;);<br><br>        mustang.displayStatus();<br>    }<br>}</pre><pre>output :-<br><br>Toyota Corolla is running at 20 km/h.<br>-----------------<br>Ford Mustang is running at 40 km/h.</pre><p>At first glance, both cars look identical because they were created from the same Car blueprint. They both know how to accelerate, brake, honk, and perform every behavior defined in the class. But something important is happening behind the scenes.</p><p>When we called corolla.accelerate(20), only the Corolla&#39;s speed changed. The Mustang didn&#39;t suddenly start moving too. Later, when we accelerated the Mustang, it updated only its own speed.</p><p>That’s because every object maintains <strong>its own independent state</strong>. They all follow the same blueprint, but each object carries its <strong>own copy of the data</strong>..</p><p>That’s why your racing game can have hundreds of cars on the track. Every car on the track follows the same set of rules, yet each one has a different color, different engine upgrades, different fuel level, different speed, and maybe even a different Nitro level. The class defines <strong>what every car should look like</strong>, while each object stores <strong>its own unique information</strong>.</p><blockquote>You write the blueprint once, and then create as many independent objects as your application needs.</blockquote><h3>Real-world problem :</h3><p>Let’s leave the racing game behind and build something closer to the kind of software we write every day.</p><p>Imagine we’re building an <strong>order management system for a food delivery platform.</strong></p><h4>Requirements</h4><p>Suppose the Product Manager walks over to your desk and says:</p><ul><li>Customers should be able to create multiple orders.</li><li>Every order belongs to one customer.</li><li>An order can contain multiple products.</li><li>Each product has its own name and price.</li><li>Customers should be able to add products to an order.</li><li>Once an order is placed, no more products can be added.</li><li>The order should know its total amount.</li><li>We should be able to display the complete order details.</li></ul><p>Now, before writing a single line of code, let’s do what OOP encourages us to do. Instead of thinking about functions, let’s identify the <strong>things</strong> that exist in this system.</p><p>We immediately notice two important ones. <strong>Product &amp; Order. </strong>Now the interesting question becomes…</p><blockquote>What should each of them be responsible for?</blockquote><h4>Responsibility Discussion</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lAusTjT2NeqUtt03cIyVYQ.png" /></figure><p>A <strong>Product</strong> only job is to represent itself. So a Product should know things like: <em>productId</em>, <em>name</em> &amp; <em>price</em></p><p>That’s it.</p><pre>class Product {<br><br>    private String productId;<br>    private String name;<br>    private double price;<br><br>    public Product(String productId, String name, double price) {<br>        this.productId = productId;<br>        this.name = name;<br>        this.price = price;<br>    }<br><br>    public String getName() {<br>        return name;<br>    }<br><br>    public double getPrice() {<br>        return price;<br>    }<br>}</pre><p>An <strong>Order</strong> has a completely different responsibility. <strong>It should know</strong>:</p><ul><li>orderId</li><li>customerName</li><li>list of products</li><li>totalAmount</li><li>whether the order has been placed</li></ul><p>And it should be <strong>able</strong> <strong>to</strong>:</p><ul><li>add products</li><li>calculate the total</li><li>place the order</li><li>display the order</li></ul><pre>class Order {<br><br>    private String orderId;<br>    private String customerName;<br>    private List&lt;Product&gt; products;<br>    private double totalAmount;<br>    private boolean isPlaced;<br><br>    public Order(String orderId, String customerName) {<br>        this.orderId = orderId;<br>        this.customerName = customerName;<br>        this.products = new ArrayList&lt;&gt;();<br>        this.totalAmount = 0;<br>        this.isPlaced = false;<br>    }<br><br>    public void addProduct(Product product) {<br><br>        if (isPlaced) {<br>            System.out.println(&quot;Cannot modify a placed order.&quot;);<br>            return;<br>        }<br><br>        products.add(product);<br>        totalAmount += product.getPrice();<br>    }<br><br>    public void placeOrder() {<br><br>        if (products.isEmpty()) {<br>            System.out.println(&quot;Cannot place an empty order.&quot;);<br>            return;<br>        }<br><br>        isPlaced = true;<br>    }<br><br>    public void displayOrder() {<br><br>        System.out.println(&quot;Order ID : &quot; + orderId);<br>        System.out.println(&quot;Customer : &quot; + customerName);<br>        System.out.println();<br><br>        System.out.println(&quot;Products:&quot;);<br><br>        for (Product product : products) {<br>            System.out.println(&quot;- &quot; + product.getName() + &quot; : ₹&quot; + product.getPrice());<br>        }<br><br>        System.out.println();<br>        System.out.println(&quot;Total Amount : ₹&quot; + totalAmount);<br>        System.out.println(&quot;Status : &quot; + (isPlaced ? &quot;PLACED&quot; : &quot;PENDING&quot;));<br>    }<br>}</pre><p><strong>Usage</strong> :-</p><pre>public class FoodApp {<br><br>    public static void main(String[] args) {<br><br>        Product pizza = new Product(<br>                &quot;P101&quot;,<br>                &quot;Pizza&quot;,<br>                299<br>        );<br><br>        Product garlicBread = new Product(<br>                &quot;P102&quot;,<br>                &quot;Garlic Bread&quot;,<br>                149<br>        );<br><br>        Product coke = new Product(<br>                &quot;P103&quot;,<br>                &quot;Coke&quot;,<br>                79<br>        );<br><br>        Order order = new Order(<br>                &quot;ORD-101&quot;,<br>                &quot;Alice&quot;<br>        );<br><br>        order.addProduct(pizza);<br>        order.addProduct(garlicBread);<br>        order.addProduct(coke);<br><br>        order.placeOrder();<br><br>        order.displayOrder();<br>    }<br>}</pre><p><strong>Output</strong>:-</p><pre>Order ID : ORD-101<br>Customer : Alice<br><br>Products:<br>- Pizza : ₹299.0<br>- Garlic Bread : ₹149.0<br>- Coke : ₹79.0<br><br>Total Amount : ₹527.0<br>Status : PLACED</pre><h4>Did you notice something interesting in this line?</h4><pre>order.addProduct(pizza);</pre><p>This might look like just another method call, but it’s actually showing one of the biggest ideas behind Object-Oriented Programming.</p><p>Both order and pizza are <strong>objects</strong>. The Order object isn&#39;t receiving the product&#39;s name and price separately like this:</p><pre>order.addProduct(&quot;Pizza&quot;, 299);</pre><p>Instead, it’s receiving an entire <strong>Product object</strong>.</p><p>That means the Order doesn&#39;t need to know how a product stores its data internally. It simply says,</p><blockquote>“Give me a Product, and I’ll add it to the order.”</blockquote><p>The Product object remains responsible for knowing its own name and price, while the Order object remains responsible for managing the customer&#39;s order.</p><p>Neither object is trying to do the other’s job.</p><p>They’re simply collaborating.</p><p>And if that reminds you of our previous blog, that’s not a coincidence. We said that good software is built from independent things with clear responsibilities that work together. This small line of code is our first real example of that idea coming to life.</p><p><em>That’s it. Thank you so much for reading!</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=899976a0ceb1" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[02. The OOP Lens: A Perspective, Not a Theory]]></title>
            <link>https://hiimvikash.medium.com/02-the-oop-lens-a-perspective-not-a-theory-ea980099d298?source=rss-6530c2ff5590------2</link>
            <guid isPermaLink="false">https://medium.com/p/ea980099d298</guid>
            <category><![CDATA[oops-concepts]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[oop]]></category>
            <dc:creator><![CDATA[Vikash Gupta]]></dc:creator>
            <pubDate>Sat, 20 Jun 2026 06:19:10 GMT</pubDate>
            <atom:updated>2026-07-21T03:12:22.292Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xPZkXZPf_biR75hUIcVLtg.png" /></figure><p>If you’ve been following along from the last blog, we ended up somewhere around this thought:</p><blockquote>“Okay… system design isn’t actually this scary, I had imagined.”</blockquote><p>We broke things down. We took baby steps. We zoomed in and zoomed out. And eventually we reached Low Level Design.</p><p>Which sounds exciting…until you open any LLD resource and the first thing people tell you is:</p><blockquote>“Before LLD, make sure your OOP concepts are strong.”</blockquote><p>And if you’re anything like me, writing API endpoints in Express. Building React components. Connecting databases. Shipping features. Things were getting done. your immediate reaction might be:</p><p><strong>“…why though?” </strong>I remember thinking this quite a lot. I wasn’t writing Java every day, except while solving leetcode.</p><p><strong>I know what a class is. I knew an object is an instance of a class.</strong></p><p><strong>I have probably answered interview questions like: </strong><em>“Encapsulation means…”, “Inheritance means…”, “Polymorphism means…”</em></p><p>But none of that answered the actual question in my head:</p><blockquote><strong>“How has knowing OOP actually helped you build software?”</strong></blockquote><p>And honestly, the first version of almost every project feels amazing. Everything makes sense. The entire codebase lives comfortably inside your head. You know exactly where things are. You have a few APIs.</p><ul><li>Create order.</li><li>Cancel order.</li><li>Update inventory.</li><li>Send notification</li></ul><p>Life is good. You put some functions here. A few utility files there. Everything works. Then, slowly, reality starts happening.</p><p>PM asks:</p><ul><li>“Can we add refunds?”</li><li>“Can we support payments from razorpay, paytm, upi, cards, stripe?”</li><li>“Can sellers have different permissions than customers?”</li><li>“What if notifications go through email, whatsapp, SMS, and push?”</li><li>“What if inventory shouldn’t reduce until payment succeeds?”</li><li>then discount coupons, then reward points, then premium membership and so on…</li></ul><p>None of these requests sound unreasonable. In fact, they sound completely normal.</p><p>But somehow, after a few months, opening the same codebase starts feeling different.</p><p>You find yourself jumping between files trying to answer questions like:</p><blockquote>“Wait…where does this logic live?”</blockquote><blockquote>“Why is this function changing three unrelated things?”</blockquote><blockquote>“If I change this piece of code, what else am I accidentally breaking?”</blockquote><blockquote>”Who is responsible for changing the order status?”</blockquote><blockquote>“Why does this payment code know so much about order?”</blockquote><blockquote>“Who thought this was a good idea?”</blockquote><p>And somewhere around this point, OOP started making a little more sense to me.</p><p>Instead of treating the entire application as one big pile of functions, OOP asks us to think a little differently.</p><p>It says: <strong><em>“What are the actual things that exist in this system?”</em></strong></p><p>In an e-commerce application, maybe there is an <strong>Order</strong>. Maybe there is a <strong>Payment</strong>. Maybe there is an <strong>Inventory</strong>. Maybe there is a <strong>Notification, Products.</strong></p><p>And each of these things should be responsible for its own work.</p><ul><li><strong>A Product</strong> should know its own details like name, price, description, category, and availability.</li><li><strong>An Order</strong> should manage the order itself — what products were ordered, its current status, total amount, orderId and whether it can be cancelled or returned.</li><li><strong>An Order</strong> can perform actions like : <em>generateInvoice(), cancelOrder(), applyCoupon(String cpn), calcTotalAmount()</em></li><li><strong>A Payment</strong> should process payments, verify transactions, handle refunds, and keep track of payment status.</li><li><strong>An Inventory</strong> should know what products are available, reserve items when an order is placed, and update stock levels.</li><li><strong>A Notification</strong> should inform users through email, SMS, WhatsApp, or push notifications whenever something important happens.</li><li>An Order shouldn’t know how to send emails.</li><li>A Notification shouldn’t decide whether inventory should decrease.</li><li>A Payment shouldn’t randomly change order statuses.</li></ul><p>Everyone should mind their own business.</p><p>Now you may say :-</p><blockquote>“Okay…but if everyone is independent, how does an application actually work?”</blockquote><p>And that’s a very fair question. Because OOP isn’t asking us to isolate everything and pretend the other pieces don’t exist.</p><p>For example, imagine a customer placing an order:</p><pre>Customer places an order<br>        ↓<br>Order asks Payment to process the amount<br>        ↓<br>Payment confirms success<br>        ↓<br>Order asks Inventory to reserve the items<br>        ↓<br>Inventory updates stock<br>        ↓<br>Notification informs the customer</pre><p>If you look at this flow carefully, something interesting is happening.</p><p>Each object only knows what it needs to know.</p><ul><li>A <strong>Customer </strong>knows<strong> about himself </strong><em>[name, phone, email, username, my orders list] &amp; </em>it’s<strong> responsibility </strong><em>[changeEmail(), changePhone(), changeUsername()]</em></li><li><strong>An Order</strong> knows about itself <strong>[orderId, products, quantity, totalAmount, orderStatus, orderDate]</strong> and is responsible for <strong>[calculateTotal(), cancel(), markAsPaid(), markAsShipped()]</strong>.</li><li><strong>A PaymentService</strong> knows only the information required to process a payment <strong>[amount, currency, paymentMethod]</strong> and is responsible for <strong>[processPayment(), verifyPayment(), refund()]</strong>.</li><li><strong>An Inventory</strong> knows about the available products and their stock <strong>[productId, availableQuantity]</strong> and is responsible for <strong>[reserveItems(), reduceStock(), restoreStock()]</strong>.</li><li><strong>A NotificationService</strong> knows only the information required to notify the customer <strong>[recipient, channel, message]</strong> and is responsible for <strong>[sendEmail(), sendSMS(), sendPushNotification()]</strong>.</li><li>An <strong>Order</strong> doesn’t know how Razorpay, Stripe, or UPI work. It simply asks the <strong>PaymentService</strong> to process a payment by providing the amount and currency.</li><li>The <strong>PaymentService</strong> doesn’t know who the customer is or what products were ordered. It only needs the payment details required to process the transaction.</li><li>Similarly, <strong>Inventory</strong> doesn’t care whether the payment came from a card or UPI. It only needs to know which products to reserve.</li><li>And <strong>Notification</strong> doesn’t need the entire Order or Payment object. It only needs enough information to tell the customer what happened.</li></ul><p>And maybe that’s the real beauty of OOP. OOP is really teaching us a way of thinking:</p><blockquote>Break your software into independent pieces with clear responsibilities, and then build meaningful relationships between those pieces and make them collaborate without creating chaos.</blockquote><p>And if you think about it…isn’t that exactly what we’ve been doing since the first blog of this series?</p><ul><li>We took a huge system.</li><li>We broke it into components.</li><li>We gave each component a responsibility.</li><li>And then we thought about how they communicate.</li></ul><p>OOP simply brings that same thinking one level closer to the code.</p><p>That’s why, before we jump into design patterns and LLD, we need to build one important lens.</p><blockquote>The OOP lens.</blockquote><p>All the examples we imagined today — the Orders, Payments, Inventory, Notifications — they weren’t just examples.</p><p>They were a glimpse into the way OOP encourages us to think about software.</p><p>Today, we didn’t learn <strong>Encapsulation</strong>.<br>We didn’t learn <strong>Inheritance</strong>.<br>We didn’t learn <strong>Polymorphism</strong>.<br>We didn’t even write a single class.<br>And that was intentional.</p><p>Everything we discussed today was really about the <strong>why</strong> behind OOP.<br><strong>Why</strong> responsibilities matter.<br><strong>Why</strong> boundaries matter.<br><strong>Why</strong> collaboration matters.<br>But eventually, this way of thinking has to move from our heads into our code. <strong><em>The core concepts of OOP</em></strong> are what make that possible.</p><p><em>And that’s where our journey continues in the next blog.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ea980099d298" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[5. Deep dive into diffing & reconciliation]]></title>
            <link>https://hiimvikash.medium.com/5-deep-dive-into-diffing-reconciliation-e5a4cd030496?source=rss-6530c2ff5590------2</link>
            <guid isPermaLink="false">https://medium.com/p/e5a4cd030496</guid>
            <category><![CDATA[react]]></category>
            <category><![CDATA[reconciliation]]></category>
            <category><![CDATA[reactjs]]></category>
            <category><![CDATA[components]]></category>
            <category><![CDATA[diffing-algorithm]]></category>
            <dc:creator><![CDATA[Vikash Gupta]]></dc:creator>
            <pubDate>Tue, 10 Feb 2026 08:30:21 GMT</pubDate>
            <atom:updated>2026-02-11T14:56:23.516Z</atom:updated>
            <content:encoded><![CDATA[<p>In previous <a href="https://hiimvikash.medium.com/2-stop-re-rendering-the-universe-why-react-renders-the-way-it-does-ee7321c9c0e5">blog</a>, we talked about the basics of how React handles re-rendering. By now, we already know that when we write JSX like &lt;Child /&gt;, It <em>looks</em> like HTML, but React doesn’t see HTML. React sees <strong>objects</strong>. That line is secretly this: React.createElement(Child, null, null), And that call produces an object that looks roughly like this:{Child, props:{}}. Return statement inside a component function produces an object like this. React builds its entire understanding of the UI from these objects.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wQRcMyjPxuAQi0iiANWqHQ.png" /></figure><p>If the reference to any of these element objects does <strong>not</strong> change between renders, React skips further work for that element. But if the reference <strong>does</strong> change, React continues rendering and moves down the tree.</p><p>This is why, in the earlier blog, we reasoned that <em>“when a parent re-renders, all its children re-render.”</em> Writing JSX like &lt;Child /&gt; inside a component means a <strong>new object is created on every render of that component</strong>. Since the reference changes, React treats it as something new and continues the rendering process.</p><blockquote>If this part doesn’t feel fully clear yet, that’s okay. I’d really recommend reading the previous post on <a href="https://hiimvikash.medium.com/2-stop-re-rendering-the-universe-why-react-renders-the-way-it-does-ee7321c9c0e5"><em>why React renders the way it does</em></a> before continuing. It makes this discussion much easier to follow.</blockquote><p>So in the last blog, the focus was on understanding how React moves through the tree during an update. We saw that when a parent component re-renders, React doesn’t automatically re-render everything below it. Instead, React compares the references of the element objects created(from React.createElement) during the current render with those from the previous render, and then decides whether it should stop or continue rendering down the tree.</p><p>In other words, We were essentially learning how to toggle re-rendering On/Off for parts of the tree. <em>That was the focus of the previous chapter.</em></p><p>In this blog, we’re going one level deeper.</p><p>Here, we’re not talking about <em>how to avoid re-renders</em>. We’re talking about <strong>what actually happens when a re-render does occur</strong>.</p><p>Because a re-render is not React blindly repainting the screen. A re-render is React asking a very specific question:</p><blockquote>Can I reuse what’s already on the screen, possibly with some updated data<br> or do I need to completely remove this and mount something new?</blockquote><p>That decision — <strong>reuse vs remove and remount </strong>— is at the core of React. This is where <strong>reconciliation</strong> comes in.</p><p>And once we understand this part, a lot of React’s behaviour stops feeling magical and starts feeling very obvious.</p><p>In this blog, we’ll investigate a few very curious bugs, dive very deep into how things work under the hood, and in the process of doing so, we will learn:</p><ul><li>How React’s Diffing and Reconciliation algorithm works.</li><li>What happens when a state update is triggered and React needs to re-render components.</li><li>Why we shouldn’t create components inside other components.</li><li>How to solve the bug of two different components sharing the same state.</li><li>How React renders arrays and how we can influence that.</li><li>What is the purpose of the “key” attribute.</li><li>How to write the most performant lists possible.</li><li>Why we would use the “key” attribute outside of dynamic lists.</li></ul><h3>The mysterious bug</h3><p>Let’s start with a little mystery to keep things interesting.</p><p>Imagine you’re rendering a component conditionally. Very normal stuff.<br>“If this thing is true, show this. Otherwise, show that.”</p><p>Say I’m building a signup form. One of the questions is whether the user is signing up as a company or just a regular human being (for some very boring tax reasons). If they say they’re a company, I want to show an input for a <strong>Company Tax ID</strong>. If they’re not, I’ll just show a friendly message like:<br><em>“You don’t need to give us a tax ID. Lucky human.”</em></p><p>The code ends up looking roughly like this:</p><pre>const Form = () =&gt; {<br>  const [isCompany, setIsCompany] = useState(false);<br><br>  return (<br>    &lt;&gt;<br>      {/* checkbox somewhere here */}<br>      {isCompany ? (<br>        &lt;Input id=&quot;company-tax-id-number&quot; placeholder=&quot;Enter your company Tax ID&quot; /&gt;<br>      ) : (<br>        &lt;TextPlaceholder /&gt;<br>      )}<br>    &lt;/&gt;<br>  );<br>};</pre><p>Now pause for a second and think about what should happen herec when the user checks the box and isCompany changes from false to true?</p><p>Nothing surprising.</p><p>The Form component re-renders.<br>The TextPlaceholder component is unmounted.<br>The Input component is mounted.</p><p>If I flip the checkbox back, the Input is unmounted and the TextPlaceholder is mounted again.</p><p>From a behavioural point of view, this also means that if I type something into the input, flip the checkbox, and then flip it back, whatever I typed is lost. The input has its own internal state, which gets destroyed when it unmounts and re-created when it mounts again.</p><p>So far, everything makes sense.</p><p>Now let’s tweak the requirement slightly.</p><p>What if I <em>also</em> need to collect a tax ID from regular people?<br>The field should look and behave exactly the same, but it’ll have a different id, a different placeholder, maybe a different onChange.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fcodesandbox.io%2Fembed%2Fbugy-input-5x6kv7&amp;display_name=CodeSandbox&amp;url=https%3A%2F%2Fcodesandbox.io%2Fp%2Fsandbox%2Fbugy-input-5x6kv7&amp;image=https%3A%2F%2Fcodesandbox.io%2Fapi%2Fv1%2Fsandboxes%2F5x6kv7%2Fscreenshot.png&amp;type=text%2Fhtml&amp;schema=codesandbox" width="1000" height="500" frameborder="0" scrolling="no"><a href="https://medium.com/media/92c1ffa17de4acf593cc1f0d0eb83c06/href">https://medium.com/media/92c1ffa17de4acf593cc1f0d0eb83c06/href</a></iframe><p>Now… what do you think happens? Here’s where things get interesting.</p><p>The input <strong>doesn’t unmount anymore</strong>.</p><p>If I type something, flip the checkbox, and flip it back — the text is still there. React treats both of these inputs as the <em>same thing</em>. Instead of unmounting one and mounting the other, it just re-renders the existing input with new props.</p><p>If this behaviour feels completely obvious to you and you immediately thought, “Yeah, of course — that’s because of <em>that reason</em>” then honestly… respect. Can I get your autograph?</p><p>For the rest of us — the ones who felt a tiny eye twitch and a mild headache reading this — it’s time to slow down &amp; dive into React’s reconciliation process to get the answer.</p><h3><strong>What’s Really Going On Between React and the DOM</strong></h3><p>Everything here starts with the DOM — or more accurately, with the fact that <em>when we write React, we don’t work with the DOM directly</em> at all.</p><p>Normally, without React, if we wanted to update something on the screen, we’d have to do stuff like:</p><ul><li>find an element</li><li>compare old values</li><li>manually update attributes</li><li>append or remove nodes</li></ul><p>Something like:</p><pre>const input = document.getElementById(&#39;input-id&#39;);<br>input.placeholder = &#39;new data&#39;;</pre><p>That works, but it’s tedious, easy to mess up, and doesn’t scale well. React saves us from all of this.<br>We just write <strong>components</strong>, and React takes responsibility for syncing things with the DOM.</p><h4>What we expect React to do</h4><p>Take a simple component:</p><pre>const Input = ({ placeholder }) =&gt; {<br>  return (<br>    &lt;input<br>      type=&quot;text&quot;<br>      id=&quot;input-id&quot;<br>      placeholder={placeholder}<br>    /&gt;<br>  );<br>};</pre><p>And then somewhere else:</p><pre>&lt;Input placeholder=&quot;Input something here&quot; /&gt;</pre><p>What do we expect?</p><ul><li>An &lt;input /&gt; should appear in the DOM</li><li>The placeholder should be set correctly</li><li>If placeholder changes later, the DOM should update And ideally… instantly.</li></ul><p>But here’s the important part 👇<br>React <strong>cannot</strong> just remove the old input and add a new one every time something changes.<br>That would be <em>terribly slow</em>. So instead, React needs a way to say:</p><blockquote><em>“Oh, this input already exists. I’ll just update its attributes.”</em></blockquote><p>That’s where the whole <strong>diffing + reconciliation</strong> story begins.</p><h4>The “Virtual DOM” (not magical, just objects)</h4><p>React does something clever.</p><p>Instead of touching the real DOM directly, it creates a <strong>representation</strong> of what the UI should look like.</p><p>People call this the <em>Virtual DOM</em>, but honestly, it’s just:</p><ul><li>a big JavaScript object</li><li>shaped like a tree</li><li>describing elements, props, and children</li></ul><p>For our Input component, React internally thinks in terms of something like:</p><pre>{<br>  type: &quot;input&quot;,<br>  props: {<br>    id: &quot;input-id&quot;,<br>    placeholder: &quot;Input something here&quot;<br>  },<br>  // plus some internal stuff<br>}<br><br><br><br>const Input = ({ label }) =&gt; {<br>  return (<br>    &lt;&gt;<br>      &lt;label htmlFor=&quot;input-id&quot;&gt;{label}&lt;/label&gt;<br>      &lt;input type=&quot;text&quot; id=&quot;input-id&quot; /&gt;<br>    &lt;/&gt;<br>  );<br>};<br><br>From React’s point of view, this is just an array of objects:<br>[<br>  { type: &quot;label&quot;, ... },<br>  { type: &quot;input&quot;, ... }<br>]</pre><p>That’s it. DOM elements like div, input, label have their type as <strong>strings</strong>, so React knows:</p><blockquote><em>“Okay, I need to create real DOM elements for these.”</em></blockquote><p><strong>Now here’s where things get interesting. If we write:</strong></p><pre>const Component = () =&gt; {<br>  return &lt;Input /&gt;;<br>};<br><br>OR <br><br>const Component = () =&gt; {<br>  return (<br>    &lt;div&gt;<br>      &lt;Input placeholder=&quot;Text1&quot; id=&quot;1&quot; /&gt;<br>      &lt;Input placeholder=&quot;Text2&quot; id=&quot;2&quot; /&gt;<br>    &lt;/div&gt;<br>  );<br>}; </pre><p>Input is <strong>not</strong> a DOM element. It’s just a JavaScript function. So React stores it like this:</p><pre>{<br>  type: Input, // the actual function reference<br>  props: { ... }<br>}<br>// Instead of a string, the type is the function itself.<br><br>OR<br><br>{<br>  type: &quot;div&quot;,<br>  props: {<br>    children: [<br>      {<br>        type: Input,<br>        props: { id: &quot;1&quot;, placeholder: &quot;Text1&quot; }<br>      },<br>      {<br>        type: Input,<br>        props: { id: &quot;2&quot;, placeholder: &quot;Text2&quot; }<br>      }<br>    ]<br>  }<br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wQRcMyjPxuAQi0iiANWqHQ.png" /></figure><h4>What happens during the initial render?</h4><p>When React mounts the app for the first time, it walks this tree step by step:</p><ul><li>If type is a <strong>string</strong> → create a DOM element</li><li>If type is a <strong>function</strong> → call that function</li><li>Take whatever it returns</li><li>Repeat the process</li></ul><p>It keeps doing this until it ends up with a full tree of real DOM nodes.</p><h4>And finally… the real DOM</h4><p>Once React has resolved everything:</p><ul><li>all components are called</li><li>all objects are converted</li><li>all DOM nodes are ready</li></ul><p>Only then does React touch the real DOM.</p><p>At that point, it simply appends the nodes using something like JavaScript’s appendChild.</p><p>So instead of us micromanaging the DOM, React does all the heavy lifting — and later, when something changes, it can <strong>compare the old tree with the new one</strong> and update <em>only what’s necessary</em>.</p><p>That comparison process is what we call <strong>diffing</strong>.<br>The update process is <strong>reconciliation</strong>.</p><p>And honestly, once you see React as: <em>“Just functions returning objects that eventually become DOM”</em>…a lot of things suddenly start clicking.</p><h3>Reconciliation and state updates</h3><p>Up to this point, we’ve been talking about how React builds a tree of objects and turns that into real DOM nodes.<br>Now comes the interesting part — <strong>what happens when state changes</strong>.</p><p>Imagine one of the components in that tree updates its state. A re-render is triggered.<br>React now needs to:</p><ul><li>update existing elements with new data, or</li><li>add or remove elements altogether</li></ul><p>So React starts another walk through the tree.</p><p>But it doesn’t randomly walk the entire tree from the top.<br>It starts <strong>from the component where the state update happened</strong> and continues downward.</p><p><strong>Starting with a very simple</strong> <strong>case</strong></p><pre>const Component = () =&gt; {<br>  return &lt;Input /&gt;;<br>};</pre><p>From React’s point of view, this component returns an object like this:</p><pre>{<br>  type: Input,<br>  // other internal stuff<br>}</pre><p>Now assume a state update happens and a re-render cycle begins.</p><p>React compares:</p><ul><li>the object from <strong>before</strong> the update</li><li>the object from <strong>after</strong> the update</li></ul><p>The very first thing it checks is the type.</p><p>In this case:</p><ul><li>before → type: Input</li><li>after → type: Input</li></ul><p>Same function reference. Nothing changed here.</p><p>So React says:</p><blockquote><em>“Cool, same component. I don’t need to throw this away.”</em></blockquote><p>Instead:</p><ul><li>Input is marked as <strong>needing update</strong></li><li>React <strong>re-runs the Input function</strong></li><li>reconciliation continues inside it</li></ul><p>This is a normal re-render. No unmounting. No DOM destruction.</p><h4>Now let’s change just one thing: conditional rendering</h4><pre>const Component = () =&gt; {<br>  const [isCompany, setIsCompany] = useState(true);<br>  if (isCompany) return &lt;Input /&gt;;<br>  return &lt;TextPlaceholder /&gt;;<br>};</pre><p>Assume:</p><ul><li>earlier → isCompany === true</li><li>later → isCompany === false</li></ul><p>Now look at what React compares.</p><pre>// Before update<br>{<br>  type: Input,<br>}<br><br>// After update<br>{<br>  type: TextPlaceholder,<br>}</pre><p>At this point, React doesn’t care about props, state, or anything else. It sees this 👇</p><blockquote><em>“Oh. The type changed.”</em></blockquote><p>When type changes, React <strong>cannot reuse</strong> the previous component.</p><p>So it:</p><ol><li><strong>unmounts</strong> the old component (Input)</li><li>removes everything related to it from the DOM</li><li>destroys its state</li><li>removes focus, event listeners, everything</li><li><strong>mounts</strong> the new component (TextPlaceholder) from scratch</li></ol><p>This means:</p><ul><li>whatever you typed in the input → gone</li><li>internal state → gone</li><li>focus → gone</li></ul><p>This is not a re-render.<br>This is a <strong>full teardown + rebuild</strong>.</p><p>And this behaviour is not a bug — it’s intentional.</p><h4>This explains a very important rule</h4><blockquote><strong><em>Same type → update [</em></strong><em>Mark</em><strong><em> </em></strong><em>to</em><strong><em> reuse </em></strong><em>with</em><strong><em> </em></strong><em>updated</em><strong><em> </em></strong><em>data</em><strong><em>]</em></strong><em><br></em><strong><em>Different type → destroy and recreate</em></strong></blockquote><p>Once you really internalize this, a lot of React “mysteries” stop being mysterious.</p><h3><strong>What Really Goes Wrong When Components Are Defined Inside Components</strong></h3><p>Let’s look at an example that <em>looks harmless</em>:</p><pre>const Component = () =&gt; {<br>  const Input = () =&gt; &lt;input /&gt;;<br>  return &lt;Input /&gt;;<br>};</pre><p>At first glance, this feels totally fine. It works. No errors. No warnings.</p><p>But now let’s apply the same reconciliation logic we just discussed.</p><h4>What React actually sees here</h4><p>Every time Component renders a <strong>new </strong><strong>Input function is created, </strong>it’s local to that render</p><pre>// So on the first render, React sees:<br>{<br>  type: Input_v1,<br>}<br><br>// After a state update, React sees:<br>{<br>  type: Input_v2,<br>}</pre><p>These two functions <strong>look identical</strong>, but in JavaScript they are <strong>not the same reference</strong>.</p><pre>const a = () =&gt; {};<br>const b = () =&gt; {};<br>a === b; // always false</pre><p>So from React’s perspective:</p><blockquote><em>“The type changed again.”</em></blockquote><h4>And now you can predict the result</h4><p>Since the type changed:</p><ul><li>React unmounts the previous Input</li><li>mounts a brand new one</li><li>DOM nodes are recreated</li><li>state is lost</li><li>focus is lost</li></ul><p>And this happens <strong>on every re-render</strong>. This is what we call <strong>re-mounting</strong>.</p><h4>Why this is actually bad (not just theoretically)</h4><p>Re-mounting is expensive:</p><ul><li>it takes <strong>at least twice as long</strong> as a normal re-render</li><li>heavy components may visibly disappear and reappear, you may notice flickering</li></ul><p>But the worse part is the bugs.</p><p>If that inner component:</p><ul><li>holds state</li><li>manages focus</li><li>tracks hover, active, open, selected</li></ul><p>All of that will reset on every parent update. Which leads to those awful bugs where:</p><blockquote><em>“I type something and it suddenly disappears”<br>“Why does this lose focus every time?”<br>“Why does this component forget its state?”</em></blockquote><p>And the root cause is often that react sees <strong>different references in “type” between render.</strong></p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fcodesandbox.io%2Fembed%2F3gj369%3Fview%3Deditor%2B%252B%2Bpreview%26module%3D%252FApp.tsx&amp;display_name=CodeSandbox&amp;url=https%3A%2F%2Fcodesandbox.io%2Fs%2F3gj369&amp;image=https%3A%2F%2Fcodesandbox.io%2Fapi%2Fv1%2Fsandboxes%2F3gj369%2Fscreenshot.png&amp;type=text%2Fhtml&amp;schema=codesandbox" width="1000" height="500" frameborder="0" scrolling="no"><a href="https://medium.com/media/b3c03ab69e5751b12e8c0bde7aa37988/href">https://medium.com/media/b3c03ab69e5751b12e8c0bde7aa37988/href</a></iframe><h4>Walkthrough: where this breaks</h4><ol><li><strong>Click the “highlight” button </strong>The block becomes active.<br> ComponentWithState updates its own isActive state — everything works.</li><li><strong>Now type anything in the input </strong>Typing updates text, which causes the App component to re-render.</li><li><strong>During this re-render </strong>ComponentWithState is re-created because it’s defined inside App.</li><li><strong>React compares before vs after </strong>The component’s type is now a different function reference.</li><li><strong>Type changed → React re-mounts </strong>The previous ComponentWithState is unmounted, a new one is mounted.</li><li><strong>Result </strong>isActive resets to false, so the highlight disappears.</li></ol><p>Nothing is “resetting” the state. The component is being <strong>destroyed and recreated</strong> on every input change. That’s the entire bug.</p><h3>Solving the mystery</h3><p>Let’s go back to that slightly confusing piece of code from the beginning and finally understand <strong>why it behaves the way it does</strong>.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fcodesandbox.io%2Fembed%2Fbugy-input-5x6kv7%3Ffrom-embed%3D&amp;display_name=CodeSandbox&amp;url=https%3A%2F%2Fcodesandbox.io%2Fp%2Fsandbox%2Fbugy-input-5x6kv7%3Ffrom-embed%3D&amp;image=https%3A%2F%2Fcodesandbox.io%2Fapi%2Fv1%2Fsandboxes%2F5x6kv7%2Fscreenshot.png&amp;type=text%2Fhtml&amp;schema=codesandbox" width="1000" height="500" frameborder="0" scrolling="no"><a href="https://medium.com/media/693eab13163b0527aefefaf7a22f5c9f/href">https://medium.com/media/693eab13163b0527aefefaf7a22f5c9f/href</a></iframe><p>The behavior we saw was this:</p><ul><li>type something in the input</li><li>toggle the checkbox</li><li>the text <strong>does not disappear</strong></li></ul><p>At first, this feels surprising. Aren’t these two different inputs?</p><h4>Let’s look at what React is actually comparing.</h4><p><strong>Assume </strong><strong>isCompany changes from </strong><strong>true to </strong><strong>false.</strong></p><p><strong>Before the update </strong>(isCompany === true) React sees this object:</p><pre>{<br>  type: Input,<br>  props: {<br>    id: &quot;company-tax-id-number&quot;,<br>    placeholder: &quot;Enter your company Tax ID&quot;<br>  }<br>}</pre><p><strong>After the update</strong> (isCompany === false) React sees this object:</p><pre>{<br>  type: Input,<br>  props: {<br>    id: &quot;person-tax-id-number&quot;,<br>    placeholder: &quot;Enter your personal Tax ID&quot;<br>  }<br>}</pre><p>Now pause here — this is the key moment.</p><p>From <strong>our</strong> perspective:</p><ul><li>these represent different inputs</li><li>they mean different things in the business logic</li></ul><p>But from <strong>React’s</strong> perspective:</p><ul><li>the type is the same</li><li>both point to the exact same Input function</li></ul><p>So React thinks:</p><blockquote>“This is the same component. Only the props changed.”</blockquote><p>At the end<strong> </strong>of the day<strong>, </strong>our entire code reduces to this from React’s<strong><em> </em></strong>perspective<strong><em>:</em></strong></p><pre>&lt;Input<br>  id={isCompany ? &quot;company-tax-id-number&quot; : &quot;person-tax-id-number&quot;}<br>  placeholder={<br>    isCompany<br>      ? &quot;Enter your company Tax ID&quot;<br>      : &quot;Enter your personal Tax ID&quot;<br>  }<br>/&gt;</pre><h4>What React does next (and why the text stays)</h4><p>Since the type didn’t change, React does exactly what it was designed to do:</p><ul><li>it <strong>reuses</strong> the existing Input component</li><li>it updates the props (id, placeholder, etc.)</li><li>it re-renders the component</li><li>it keeps the same DOM node</li><li>it keeps the same internal state</li></ul><p>Nothing is destroyed. Nothing is remounted.</p><p>That’s why: you type something, flip the checkbox and the text is still there. React isn’t being clever or buggy here — it’s being <strong>consistent</strong>.</p><h4>Is this behaviour wrong?</h4><p>Not necessarily.</p><p>There <em>are</em> situations where this is exactly what you want:</p><ul><li>same component</li><li>same identity</li><li>new data</li></ul><p>In those cases, re-rendering instead of re-mounting is a feature, not a problem.</p><p>But in this specific case, from a <strong>business logic</strong> point of view:</p><ul><li>“company tax ID” and “personal tax ID” are different entities</li><li>reusing the same input doesn’t really make sense</li><li>we probably want a fresh input every time</li></ul><p>In other words, <strong>we don’t want reuse here</strong>.</p><h4>What we actually want</h4><p>when isCompany flips</p><ul><li>the old input is removed</li><li>a new input is mounted</li><li>the value is reset</li></ul><p>To make that happen, we need to tell React:</p><blockquote>“These two inputs are not the same thing.”</blockquote><p>And React gives us a couple of simple ways to do that.</p><h4>How we fix this (high level)</h4><p>There are at least two easy ways:</p><ul><li>[a] — rendering them as different entries in an array</li><li>[b] — using key to force identity separation</li></ul><p>Both approaches change how React matches elements during reconciliation.</p><p>And now that we understand <strong>why the bug exists</strong>, the fixes stop feeling like hacks and will start feeling like clear signals to React.</p><h3>[a] — Rendering them as different entries in an array</h3><p>Till now, we mostly talked about reconciliation assuming that a component returns <strong>one element</strong>.</p><p>But in real life… that almost never happens.</p><p>We need to talk about arrays of elements and how they behave during re-renders in more detail now.</p><p>Even our simple Form actually has an array:</p><pre>const Form = () =&gt; {<br>  const [isCompany, setIsCompany] = useState(false);<br><br>  return (<br>    &lt;&gt;<br>      &lt;Checkbox onChange={() =&gt; setIsCompany(!isCompany)} /&gt;<br>      {isCompany ? (<br>        &lt;Input id=&quot;company-tax-id-number&quot; /&gt;<br>      ) : (<br>        &lt;Input id=&quot;person-tax-id-number&quot; /&gt;<br>      )}<br>    &lt;/&gt;<br>  );<br>};</pre><p>But internally, React sees something closer to this:</p><pre>{<br>  type: React.Fragment, // special type<br>  props: {<br>    children: [<br>      {<br>        type: Checkbox,<br>        props: {<br>          onChange: () =&gt; setIsCompany(!isCompany)<br>        },<br>        key: null,<br>        ref: null<br>      },<br>      {<br>        type: Input,<br>        props: {<br>          id: &quot;person-tax-id-number&quot;<br>        },<br>        key: null,<br>        ref: null<br>      }<br>    ]<br>  },<br>  key: null,<br>  ref: null<br>}</pre><p><strong>Focus on children[]</strong> only for now, That fragment (&lt;&gt;...&lt;/&gt;) is just a <strong>container for an array of children</strong>.</p><pre>[<br>  { type: Checkbox },<br>  { type: Input },<br>]</pre><h4>How React compares arrays during re-render</h4><p>When state changes (isCompany flips), React does <strong>not</strong> randomly re-render everything.</p><p>It does this:</p><ol><li>Take the <strong>previous array of children</strong><br> (still virtual, nothing related to the DOM)</li><li>Take the <strong>new array of children</strong><br> (also virtual, nothing related to the DOM)</li><li>Compare the two arrays <strong>item by item, by position</strong></li></ol><p>For each position, React checks:</p><ul><li>Is the type the same?</li><li>If yes → <strong>reuse</strong> the existing component</li><li>If no → <strong>unmount</strong> the previous component at that position<br> and <strong>mount</strong> the new one at the same position</li></ul><p>So React’s mental model is basically:</p><blockquote><em>“First child with first child.<br> Second child with second child.<br> Third with third…”</em></blockquote><h4>Conditional rendering still creates array slots</h4><p>Now here’s something subtle but important 👇</p><p>Even this:</p><pre>{isCompany ? &lt;Input /&gt; : null}</pre><p>still occupies <strong>a position in the array</strong>.</p><p>So if we rewrite the form like this:</p><pre>&lt;&gt;<br>  &lt;Checkbox /&gt;<br>  {isCompany ? &lt;Input id=&quot;company-tax-id-number&quot; /&gt; : null}<br>  {!isCompany ? &lt;Input id=&quot;person-tax-id-number&quot; /&gt; : null}<br>&lt;/&gt;</pre><p>React always sees <strong>three positions</strong>:</p><pre>[<br>  { type: Checkbox },<br>  Input OR null,<br>  Input OR null<br>]</pre><p>The <em>number of slots stays stable</em> — only the values change.</p><h4>What actually happens<strong> when the Form is rewritten this way</strong></h4><p>Let’s walk through it like React does.</p><p>Before (isCompany = false):</p><pre>[<br>  { type: Checkbox },<br>  null,<br>  { type: Input }<br>]</pre><p>After (isCompany = true):</p><pre>[<br>  { type: Checkbox },<br>  { type: Input },<br>  null<br>]</pre><p>Now React compares <strong>position by position</strong>:</p><ol><li><strong>First item</strong><br> Checkbox → Checkbox<br> ✅ Same type → re-render Checkbox</li><li><strong>Second item</strong><br> null → Input<br> ❌ Different → mount Input</li><li><strong>Third item</strong><br> Input → null<br> ❌ Different → unmount Input</li></ol><p>And just like that ✨<br><strong>the correct input appears, and the old one disappears cleanly.</strong></p><h4>Why changing position fixed the bug</h4><p>This part feels like magic at first.</p><p>We didn’t change:</p><ul><li>state logic</li><li>event handlers</li><li>components themselves</li></ul><p>We only changed <strong>where the elements appear in the array</strong>.</p><p>But because React compares by <strong>position + type</strong>, that change completely altered how React matched elements.</p><p><em>And just like that, by changing only the position of the inputs in the render output — without touching any of the logic — the bug disappears, and the inputs start behaving exactly as expected.</em></p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fcodesandbox.io%2Fembed%2Ftwn74r%3Fview%3Deditor%2B%252B%2Bpreview%26module%3D%252Fsrc%252FApp.js&amp;display_name=CodeSandbox&amp;url=https%3A%2F%2Fcodesandbox.io%2Fs%2Ftwn74r&amp;image=https%3A%2F%2Fcodesandbox.io%2Fapi%2Fv1%2Fsandboxes%2Ftwn74r%2Fscreenshot.png&amp;type=text%2Fhtml&amp;schema=codesandbox" width="1000" height="500" frameborder="0" scrolling="no"><a href="https://medium.com/media/57a3e33d14192da9053823f941e26922/href">https://medium.com/media/57a3e33d14192da9053823f941e26922/href</a></iframe><h3>[b] — Using key to force identity separation</h3><p>There is another way to fix the same issue we just saw — by using the key attribute.</p><p>The “key” should be familiar to anyone who has written any lists in React. React forces us to add it when we iterate over arrays of data:</p><pre>const data = [&#39;1&#39;, &#39;2&#39;];<br><br>const Component = () =&gt; {<br>  return data.map((value) =&gt; &lt;Input key={value} /&gt;);<br>};</pre><p>At render time, React sees this as an array of elements:</p><pre>[<br>  { type: Input }, // &quot;1&quot; data item<br>  { type: Input }  // &quot;2&quot; data item<br>]</pre><p>So far, everything looks simple.</p><h4>The real problem: lists are dynamic</h4><p>The issue starts when the list changes.</p><p>In real applications, lists are rarely static. We:</p><ul><li>reorder items</li><li>insert new ones</li><li>remove existing ones</li></ul><p>Now imagine the order changes. From the data point of view, it’s now: [2, 1]</p><blockquote>Try here ! When we type something in the first input and then reorder the list. The typed text stays in the <strong>first position</strong>, not with the data it logically belongs to.</blockquote><iframe src="https://cdn.embedly.com/widgets/media.html?url=https%3A%2F%2Fcodesandbox.io%2Fs%2Fppqztw&amp;type=text%2Fhtml&amp;schema=codesandbox&amp;display_name=CodeSandbox&amp;src=https%3A%2F%2Fcodesandbox.io%2Fembed%2Fppqztw%3Fview%3Deditor%2B%252B%2Bpreview%26module%3D%252FApp.tsx" width="1000" height="500" frameborder="0" scrolling="no"><a href="https://medium.com/media/7f78ed626d7fee77fb8d236543f02654/href">https://medium.com/media/7f78ed626d7fee77fb8d236543f02654/href</a></iframe><h4>What React thinks is happening</h4><p>From our point of view, this is what we expect:</p><blockquote>The second input should move to the first position,<br>and the first input should move to the second position.</blockquote><p>In other words, we expect the inputs themselves to swap places — along with their state.</p><p>But React doesn’t see it that way.</p><p>From React’s point of view, before and after the reorder, the virtual output looks exactly like this:</p><pre>[<br>  { type: Input }, // now showing &quot;2&quot;, but React doesn&#39;t know that<br>  { type: Input }  // now showing &quot;1&quot;, but React doesn&#39;t know that<br>]</pre><p>From React’s point of view:</p><ul><li>the array length is the same</li><li>the element at index 0 is still Input</li><li>the element at index 1 is still Input</li></ul><p>There is <strong>no signal</strong> here that anything moved.</p><h4>Why React reuses the “wrong” input</h4><p>When we map over an array and render &lt;Input /&gt; components, React does <strong>not</strong> see the array as “data that owns components”.</p><p>React only sees the <strong>final render output</strong> — which is just an array of elements.</p><p>That array is simply being used as a loop to produce multiple Input components.<br> There is <strong>no bond or linkage</strong> between:</p><ul><li>an individual item in the data array, and</li><li>a specific Input component that gets rendered from it.</li></ul><p>From React’s point of view, the situation looks like this:</p><blockquote><em>“I was given </em>n<em> elements of type </em><em>Input. That’s it.”</em></blockquote><p>So when the data array changes order, React has no context to understand that:</p><ul><li>this Input used to belong to item &quot;1&quot;, and</li><li>that Input used to belong to item &quot;2&quot;.</li></ul><p>As far as React is concerned, nothing meaningful changed.<br>It’s still the same number of Input elements, in the same positions, with the same type.</p><h4>The rule React applies next</h4><p>Because there is no explicit identity connecting a particular Input to a particular data item, React falls back to its core reconciliation rule:</p><blockquote><strong><em>“If the type is the same at the same position, reuse it.”</em></strong></blockquote><p>So React reasons like this:</p><ul><li>First position was an Input → still an Input</li><li>Second position was an Input → still an Input</li></ul><p>As a result:</p><ul><li>both component instances are reused</li><li>React does not create new inputs</li><li>React does not move existing ones</li></ul><p>It simply updates the <strong>props</strong> of the inputs that were already there<br>(which is why labels or placeholders update, since they come from the data).</p><blockquote>Now why typed text stayed at same position ?</blockquote><p>The typed text stayed where it was because <strong>state was tied to the same </strong><strong>Input component instance</strong>.</p><p>Since React reused that same component during the re-render, the state stayed exactly where it was — only the props changed.</p><p><em>This is not a bug in React — it’s a consequence of the information React has available.</em></p><h4>How &quot;key” fills this missing gap ?</h4><p>Let’s look at what happens <strong>after we add </strong><strong>key</strong> and the data gets reordered.</p><pre>{inputs.map((val) =&gt; (<br>     &lt;Input<br>        label={`Input ${val}`}<br>        placeholder={`Enter value for Input ${val}`}<br>        onChange={() =&gt; {}}<br>        id=&quot;company-tax-id&quot;<br>        key={val}<br>      /&gt;<br>))}</pre><p><strong>Before re-ordering, React sees this:</strong></p><pre>[<br>  { type: Input, key: &#39;1&#39; },<br>  { type: Input, key: &#39;2&#39; }<br>]</pre><p>At this point, React creates two component instances:</p><ul><li>an Input with key 1</li><li>an Input with key 2</li></ul><p>Each instance has its own state and its own DOM node.</p><p><strong>After re-ordering, the render output becomes:</strong></p><pre>[<br>  { type: Input, key: &#39;2&#39; },<br>  { type: Input, key: &#39;1&#39; }<br>]</pre><p>This is where things change completely compared to the no-key case.</p><h4>How React compares elements now</h4><p>React no longer starts by looking at <strong>position</strong>.</p><p>Instead, React looks at each element and asks:</p><blockquote><em>“Do I already have an element with this </em><strong><em>type</em></strong><em> and this </em><strong><em>key</em></strong><em>?”</em></blockquote><p>So React’s thinking goes something like this:</p><ul><li>“Here is Input with key 2<br> Let me check the previous render…<br> Yes, I already created an Input with key 2.<br> I’ll reuse that one.”</li><li>“Next is Input with key 1<br> Let me check the previous render…<br> Yes, I already created an Input with key 1.<br> I’ll reuse that one too.”</li></ul><p>At no point does React need to care about <strong>positions</strong>. Since React finds matching elements by <strong>type and key</strong>: it reuses the correct component instances.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fcodesandbox.io%2Fembed%2Flvj8cp%3Fview%3Deditor%2B%252B%2Bpreview%26module%3D%252FApp.tsx&amp;display_name=CodeSandbox&amp;url=https%3A%2F%2Fcodesandbox.io%2Fs%2Flvj8cp&amp;image=https%3A%2F%2Fcodesandbox.io%2Fapi%2Fv1%2Fsandboxes%2Flvj8cp%2Fscreenshot.png&amp;type=text%2Fhtml&amp;schema=codesandbox" width="1000" height="500" frameborder="0" scrolling="no"><a href="https://medium.com/media/b59eb13cd2911c7aa3f5a6e112f61551/href">https://medium.com/media/b59eb13cd2911c7aa3f5a6e112f61551/href</a></iframe><h4>Why this fixes the bug</h4><p>This is why key exists.</p><p>A key is React’s way of uniquely identifying an element <strong>within a children array</strong> across renders.</p><p>When both <strong>type</strong> and <strong>key</strong> match between renders, React knows it is the same element — regardless of where it appears in the array.</p><p>So the comparison changes from:</p><pre> type + position</pre><p>to:</p><pre>type + key</pre><p>And that one change is enough to fix the entire issue.</p><h4>State reset technique (and why this matters for our Form)</h4><p>So far, we’ve spent a lot of time understanding how key helps React correctly <strong>reuse</strong> components when lists change.</p><p>But here’s the interesting part — we can also use the same mechanism to do the <em>opposite</em>.</p><p>We can use key to <strong>force React to NOT reuse a component at all</strong>.</p><p>And this is exactly what fixes the original bug in our Form.</p><h4>Coming back to our original Form bug</h4><p>Let’s revisit the component we started with:</p><pre>const Form = () =&gt; {<br>  const [isCompany, setIsCompany] = useState(false);<br>  return (<br>      &lt;&gt;<br>        &lt;Checkbox onChange={() =&gt; setIsCompany(!isCompany)} /&gt;<br>        {isCompany ? (<br>          &lt;Input id=&quot;company-tax-id-number&quot; /&gt;<br>        ) : (<br>          &lt;Input id=&quot;person-tax-id-number&quot; /&gt;<br>        )}<br>      &lt;/&gt;<br>    );<br>  };</pre><p>From React’s point of view, this component always returns <strong>an array of children</strong>:</p><pre>[<br>  { type: Checkbox },<br>  { type: Input } // React thinks this is the same input every time<br>]</pre><p>Even though <em>we</em> think we’re switching between two different inputs, React only sees:</p><ul><li>the same type</li><li>the same position</li><li>no key</li></ul><p>So React reuses the same Input component between re-renders — and that’s why the input state sticks around.</p><h4>What we actually want React to do</h4><p>In this case, we <strong>don’t</strong> want reuse.</p><p>We want React to understand:</p><blockquote><em>“These are not the same input.<br> When this changes, throw the old one away and create a new one.”</em></blockquote><p>And that’s where key comes in again — but this time, with a different goal.</p><h4>Fixing the bug using key</h4><p>If we add a key to each input:</p><pre>{isCompany ? (<br>  &lt;Input<br>    id=&quot;company-tax-id-number&quot;<br>    key=&quot;company-tax-id-number&quot;<br>  /&gt;<br>) : (<br>  &lt;Input<br>    id=&quot;person-tax-id-number&quot;<br>    key=&quot;person-tax-id-number&quot;<br>  /&gt;<br>)}</pre><p>Now the children array looks like this.</p><p>Before (isCompany = false):</p><pre>[<br>  { type: Checkbox },<br>  { type: Input, key: &#39;person-tax-id-number&#39; }<br>]</pre><p>After (isCompany = true):</p><pre>[<br>  { type: Checkbox },<br>  { type: Input, key: &#39;company-tax-id-number&#39; }<br>]</pre><p>The important thing to notice is that <strong>the key is different</strong>.</p><h4>What React does now</h4><p>During reconciliation, React compares:</p><ul><li>old Input → key: &#39;person-tax-id-number&#39;</li><li>new Input → key: &#39;company-tax-id-number&#39;</li></ul><p>Same type, but <strong>different key</strong>.</p><p>So React concludes:</p><blockquote><em>“This is not the same component anymore.”</em></blockquote><p>Because of that:</p><ul><li>the old Input is <strong>unmounted</strong></li><li>a brand new Input is <strong>mounted from scratch</strong></li></ul><p>As a result, the input state is reset.</p><p>And just like that, the original bug disappears.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fcodesandbox.io%2Fembed%2Flsqx5y%3Fview%3Deditor%2B%252B%2Bpreview%26module%3D%252Fsrc%252FApp.js&amp;display_name=CodeSandbox&amp;url=https%3A%2F%2Fcodesandbox.io%2Fs%2Flsqx5y&amp;image=https%3A%2F%2Fcodesandbox.io%2Fapi%2Fv1%2Fsandboxes%2Flsqx5y%2Fscreenshot.png&amp;type=text%2Fhtml&amp;schema=codesandbox" width="1000" height="500" frameborder="0" scrolling="no"><a href="https://medium.com/media/4bbea110a6b4c30f9b7bd56ac037c12b/href">https://medium.com/media/4bbea110a6b4c30f9b7bd56ac037c12b/href</a></iframe><h4>This pattern is called “state reset”</h4><p>This technique is commonly known as <strong>state reset</strong>.</p><p>Despite the name, it’s not really about state itself.</p><p>What we’re actually doing is:</p><ul><li>forcing React to destroy a component</li><li>and create a new one</li></ul><p>The state reset is just a <strong>side effect</strong> of that full remount.</p><h4>We don’t need multiple components for this</h4><p>Another useful detail: We don’t even need two different components to use this pattern.</p><p>Any value that changes the key will force React to remount the component.</p><p>For example, if we want to reset an input when the URL changes:</p><pre>const Component = () =&gt; {<br>  const { url } = useRouter();<br>  return &lt;Input id=&quot;some-id&quot; key={url} /&gt;;<br>};</pre><p>Every time the URL changes:</p><ul><li>the key changes</li><li>React unmounts the old input</li><li>React mounts a fresh one</li></ul><p>State reset achieved.</p><h4>A small but important warning</h4><p>This technique is powerful — but it’s also destructive.</p><p>When we change a key, we force React to:</p><ul><li>unmount the component completely</li><li>clean up effects</li><li>destroy DOM</li><li>mount everything again from scratch</li></ul><p>For large or complex components, this can cause performance issues.</p><p>So we should use this pattern <strong>intentionally</strong>, not casually.</p><p>The state reset is not magic — it’s simply a by-product of a full remount.</p><h4>Final takeaway</h4><p>At this point, the picture should be clear:</p><ul><li>we can use key to help React <strong>reuse the right component</strong></li><li>we can also use key to tell React <strong>not to reuse a component</strong></li><li>both behaviours come from the same reconciliation rule</li></ul><p>Once we understand how React compares <strong>type + key</strong>, everything else becomes predictable.</p><p>Internally, React:</p><ul><li>builds a <strong>map of old children by key</strong></li><li>then tries to match new children against it</li></ul><p>But <strong>after finding by key</strong>, it <strong>still validates the type</strong>.</p><p>So internally it’s more like:</p><pre>Find by key → verify type → reuse</pre><p>Never:</p><pre>Find by key → reuse blindly</pre><p>So you can think of React’s internal priority like this:</p><ul><li><strong>Find by key → verify type → reuse</strong></li><li><strong>If key is missing → match by position + type</strong></li></ul><p>Anything that fails these checks results in React unmounting the old component and mounting a new one.</p><h3>Bad Keys — let’s list them down</h3><p>Let’s not think in terms of rules yet.<br>Let’s just ask one simple question every time:</p><p><strong>“Does this key truly represent <em>who this item is</em>?”</strong></p><p>If the answer is no — it’s probably a bad key.</p><ol><li><strong>Using array index as key</strong></li></ol><ul><li>items.map((item, index) =&gt; &lt;Item key={index} /&gt;)</li><li>This one feels natural, right?<br>But here’s the problem: index only tells React <em>where</em> the item is, not <em>what</em> it is.</li><li>If an item is added or removed or even from the middle, all the indexes after it change.<br>React now starts matching the wrong items with the wrong previous ones.</li></ul><p><strong>2. Keys that change every render</strong></p><ul><li>&lt;Item key={Math.random()} /&gt;</li><li>At this point, we’re basically telling React:<br>“Nothing is the same as before.”</li><li>React has no choice but to throw everything away and rebuild it again — losing state, focus, everything.</li></ul><p><strong>3. Non-unique keys</strong></p><ul><li>&lt;Item key={item.type} /&gt;</li><li>If two items share the same key, React can’t tell them apart.<br>It’s like calling two people by the same name and expecting no confusion.</li></ul><p><strong>4. Keys from values that can change</strong></p><ul><li>&lt;Item key={item.name} /&gt;</li><li>This works… until name changes.</li><li>The moment it does, React thinks:<br>“Oh, this is a brand-new element.”</li><li>And suddenly state resets, inputs lose focus, and bugs appear out of nowhere.</li></ul><blockquote>A good key answers <em>“</em>who is this item?<em>”</em> in a way that survives re-renders — even when items are reordered, added, or removed.</blockquote><h3>Why keys are only required inside arrays</h3><p>Let’s have a bit more fun with reconciliation, now that the mystery is solved and the algorithm is more or less clear. There are still a few mini-questions and mysteries there. For example, have you noticed that React never forced you to add keys to anything unless you’re iterating over an array?</p><p>The object definition of this:</p><pre>&lt;&gt;<br>  {data.map((value) =&gt; (<br>    &lt;Input key={value} /&gt;<br>  ))}<br>&lt;/&gt;</pre><p>and this :</p><pre>&lt;&gt;<br> &lt;Input /&gt;<br> &lt;Input /&gt;<br>&lt;/&gt;</pre><p>will be exactly the same, just a fragment with two inputs as a children array:</p><pre>[<br>  { type: Input },<br>  { type: Input }<br>]</pre><p>Why does React scream in the first case but stay silent in the second?</p><h4>The real difference: dynamic vs static children</h4><p>Here’s where React’s thinking changes.</p><h4>Case 1: Explicit JSX children (static)</h4><pre>&lt;&gt;<br>  &lt;Input /&gt;<br>  &lt;Input /&gt;<br>&lt;/&gt;</pre><p>From React’s POV:</p><ul><li>These elements are <strong>statically defined</strong></li><li>Their <strong>order is fixed</strong></li><li>React can safely assume:</li><li>First Input stays first</li><li>Second Input stays second</li></ul><p>Even across re-renders, React expects this structure to remain stable unless <em>you explicitly change the JSX</em>.</p><p>So React says:</p><blockquote><em>“Cool. I can match these by position. No extra identity needed.”</em></blockquote><p>No keys required.</p><h4>Case 2: map() over an array (dynamic)</h4><pre>{data.map((value) =&gt; (<br>  &lt;Input key={value} /&gt;<br>))}</pre><p>Now React pauses and thinks:</p><blockquote><em>“Hmm… this is coming from data.”</em></blockquote><p>And that changes everything.</p><p>React <strong>does not know</strong> what you’ll do to this array on the next render:</p><ul><li>You might add an item</li><li>Remove one</li><li>Reorder them</li><li>Or leave them as-is</li></ul><p>From React’s POV, this array is <strong>unstable by nature</strong>.</p><p>So React says:</p><blockquote><em>“I can’t rely on position anymore.<br> If things move around, I need a way to know </em>which element is which<em>.”</em></blockquote><p>That’s why React <strong>forces</strong> you to provide a key.<br>It’s a <strong>precautionary measure</strong>. Keys are React’s way of saying:</p><blockquote><em>“If this list changes, tell me how to track identity across renders.”</em></blockquote><h3>Now comes the fun part 🧠</h3><p>Let’s try something weird.</p><p>What if we <strong>don’t use an array</strong>, but still mess with keys?</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fcodesandbox.io%2Fembed%2F765zq8%3Fview%3Deditor%2B%252B%2Bpreview%26module%3D%252FApp.tsx&amp;display_name=CodeSandbox&amp;url=https%3A%2F%2Fcodesandbox.io%2Fs%2F765zq8&amp;image=https%3A%2F%2Fcodesandbox.io%2Fapi%2Fv1%2Fsandboxes%2F765zq8%2Fscreenshot.png&amp;type=text%2Fhtml&amp;schema=codesandbox" width="1000" height="500" frameborder="0" scrolling="no"><a href="https://medium.com/media/8cdb4b67dabe60d3db257b284720ee85/href">https://medium.com/media/8cdb4b67dabe60d3db257b284720ee85/href</a></iframe><p>Notice a few important things:</p><ul><li>These inputs are <strong>not rendered via an array</strong></li><li>React does <strong>not warn</strong> about keys</li><li>But we’re <strong>conditionally assigning the same key</strong></li></ul><p>Let’s simulate what React sees.</p><p>Initial render (isReverse = false)</p><pre><br>[<br>  { type: Input, key: null},<br>  { type: Input, key: &#39;some-key&#39; }<br>]</pre><p>Toggle isReverse = true</p><pre>[<br>  { type: Input, key: &#39;some-key&#39; }<br>  { type: Input, key: null},<br>]</pre><p>React notices:</p><ul><li>&quot;some-key&quot; existed before &amp; &quot;some-key&quot; still exists now But it <strong>moved to a different position, LET’S REUSE.</strong></li><li>At the second position, React is now left with an unkeyed &lt;Input /&gt;.<br>Since unkeyed elements are matched purely by position, React unmounts the previous unkeyed input and mounts a new one.</li></ul><h4>What happens to the input values?</h4><p>If you type something into one input and toggle the boolean:</p><ul><li>The <strong>text jumps to the other input</strong></li><li>The DOM nodes appear to swap identities</li><li>State follows the <strong>key</strong>, not the position</li></ul><p>This feels surprising only because:</p><ul><li>There’s no array</li><li>React didn’t warn you</li><li>But reconciliation rules still apply</li></ul><h4>The takeaway mental model</h4><ul><li><strong>Keys are about identity, not arrays</strong></li><li>Arrays are just the place where identity problems are most common</li><li>React enforces keys in arrays because: Order can change implicitly</li><li>Outside arrays: React assumes stability</li><li>But <strong>you can still break that assumption</strong></li></ul><p>So the rule is not:</p><blockquote><em>“Keys are only for arrays”</em></blockquote><p>The real rule is:</p><blockquote><em>“Keys are needed whenever element identity must survive re-renders despite reordering, adding, or removing.”</em></blockquote><h3>Dynamic arrays mixed with normal elements</h3><p>If you’ve been reading this chapter carefully, there’s a good chance you had a tiny heart attack at this point.<br> I definitely did when I was digging into this.</p><p>Because suddenly, a very scary thought appears.</p><h4>The scary realization</h4><p>We already learned two things:</p><ol><li><strong>Dynamic lists (</strong><strong>map) become arrays of children</strong></li><li><strong>Normal JSX elements next to each other also become arrays of children</strong></li></ol><p>So the brain goes:</p><blockquote><em>“If everything becomes an array anyway…<br> and if dynamic items are no different from normal elements…<br> what happens when I mix them?”</em></blockquote><p>Now look at this code:</p><pre>const data = [&#39;1&#39;, &#39;2&#39;];<br>const Component = () =&gt; {<br>  return (<br>    &lt;&gt;<br>      {data.map((i) =&gt; (<br>        &lt;Input key={i} id={i} /&gt;<br>      ))}<br>      {/* will this input re-mount if I add a new item above? */}<br>      &lt;Input id=&quot;3&quot; /&gt;<br>    &lt;/&gt;<br>  );<br>};</pre><p>This looks innocent. But once reconciliation clicks, a <strong>fearful question</strong> shows up:</p><blockquote><em>“If I add or remove items from </em><em>data,<br>does this </em><em>Input id=&quot;3&quot; keep re-mounting?”</em></blockquote><blockquote><em>this is because on every change in data[] length, position will be changed for </em><em>Input id=&quot;3&quot;</em></blockquote><p>And if that’s true…</p><p>👉 this would be a <strong>silent performance disaster</strong><br> 👉 inputs would lose state<br> 👉effects would re-run<br> 👉 DOM nodes would be destroyed and recreated</p><p>All just because an array changed above them 😨</p><h4>But… phew 😮‍💨 — This is NOT what React does</h4><p>React is smarter than that. Here’s the key realization:</p><blockquote><strong>React does NOT flatten dynamic and static elements into one single list.</strong></blockquote><p>Instead, React treats <strong>dynamic arrays as a single unit</strong>.</p><p>When React sees:</p><pre>&lt;&gt;<br>  {data.map(...)}<br>  &lt;Input id=&quot;3&quot; /&gt;<br>&lt;/&gt;</pre><p>React does <strong>not</strong> think:</p><blockquote><em>“Ah, three Inputs in a row.”</em></blockquote><p>React thinks:</p><blockquote><em>“First child: a dynamic array<br> Second child: a static element”</em></blockquote><p>So the internal structure becomes:</p><pre>[<br>  // first child is the entire dynamic array<br>  [<br>    { type: Input, key: 1 },<br>    { type: Input, key: 2 },<br>  ],<br>  // second child is the manual Input<br>  { type: Input }<br>]</pre><h4>What happens when the array changes?</h4><p>Let’s say data becomes [&#39;1&#39;, &#39;2&#39;, &#39;3&#39;].</p><p>React compares:</p><h4>First child (the array)</h4><ul><li>Reconciled <strong>inside itself</strong></li><li>Uses keys (1, 2, 3)</li><li>Adds one new Input</li><li>No confusion</li></ul><h4>Second child (manual Input)</h4><ul><li>Still at index 1</li><li>Same position</li><li>Same element</li><li>Same instance</li></ul><p>React’s conclusion:</p><blockquote>“Nothing changed here. Keep it.”</blockquote><p>✅ No re-mount<br>✅ No lost state<br>✅ No performance disaster</p><p>So React adds one more rule internally:</p><blockquote>Dynamic arrays are grouped and reconciled separately.</blockquote><blockquote>Thanks for reading — a part of <a href="https://hiimvikash.medium.com/list/fundamentals-of-react-4ea34381c101"><em>Fundamentals of React</em></a></blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e5a4cd030496" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[01. The First Time System Design Made Sense to Me]]></title>
            <link>https://hiimvikash.medium.com/01-the-first-time-system-design-made-sense-to-me-1d10fd357c99?source=rss-6530c2ff5590------2</link>
            <guid isPermaLink="false">https://medium.com/p/1d10fd357c99</guid>
            <category><![CDATA[system-design-interview]]></category>
            <category><![CDATA[system-design-concepts]]></category>
            <category><![CDATA[high-level-design]]></category>
            <category><![CDATA[low-level-design]]></category>
            <category><![CDATA[systems-thinking]]></category>
            <dc:creator><![CDATA[Vikash Gupta]]></dc:creator>
            <pubDate>Sun, 01 Feb 2026 17:48:27 GMT</pubDate>
            <atom:updated>2026-02-01T17:48:27.265Z</atom:updated>
            <content:encoded><![CDATA[<p>Let me be very honest from the start.</p><p>When I first heard the term <em>system design</em>, I assumed it was this big, scary thing — <br>the kind of stuff only senior engineers deal with,<br>the kind of topic you’re supposed to stay away from until you’re “experienced enough.”</p><p><em>So I chose to park it for a while and focus on other fundamentals first.</em></p><p>But when I finally sat down and tried to understand it slowly, without pressure, something clicked.</p><p>System design isn’t actually complicated. It just <em>sounds</em> complicated.</p><p>So in this blog, I’m not going to “teach” you system design. I’m just going to talk to you about how I’m understanding it.</p><ol><li>What system design actually means</li><li>How to approach any system design problem without feeling overwhelmed</li><li>How to judge whether a system you designed is actually <em>good</em></li></ol><p>I’ll explain this the same way I’d explain it to a teammate sitting next to me.</p><h3>So First… What Is System Design?</h3><p>Let’s begin with the most basic question.</p><p><strong>What is system design?</strong></p><p>In the simplest possible terms:</p><blockquote><em>System design is about taking a set of requirements and building a real product out of it.</em></blockquote><p>That’s it.</p><h4>What Does “Design a System” Actually Mean?</h4><p>For a long time, this phrase confused me. Someone would say:</p><blockquote><em>“Design a system”</em></blockquote><p>And I’d be like…okay, but <strong>what am I supposed to do first?</strong></p><p>Write code?<br>Draw diagrams?<br>Choose a database?</p><p>It felt very vague.</p><h4>Here’s what I slowly realized</h4><p>When people say <strong><em>design a system</em></strong>, they usually <strong>don’t mean code</strong>.</p><p>They’re not asking you to open an editor.<br>They’re not asking you to write classes.</p><p>What they really mean is:</p><blockquote><em>“Let’s first think about what all things are needed to make this work.”</em></blockquote><p>That’s it.</p><h4>How I Personally Break System Design in My Head</h4><p><em>(This is not some official definition — this is just how it makes sense to me)</em></p><p>Whenever I hear a big system design problem, my first reaction used to be confusion.</p><p>Too many things.<br>Too many moving parts.<br>Too many decisions.</p><p>So instead of trying to hold everything in my head at once, I started asking myself a very simple question:</p><blockquote>What is the smallest way I can think about this problem without freezing?</blockquote><p>So the way I put it now is this: I tell myself to<em> take baby steps, no matter what.</em><br>No matter what problem you have in front of you, just go really small.<br>One tiny step at a time.</p><p>You don’t need to figure out everything at once.<br>You don’t need all the answers upfront.</p><p>You just take one small decision, then the next, then the next.</p><p>And eventually, without even realizing it, you’ll cover everything.<br>That’s how you end up building a really good system.</p><p>So let’s do this the same way — slowly and without pressure.<br>We’ll start small and walk through building a URL shortener from first principles.</p><h3>Applying 3-Layer System Design Thinking to a URL Shortener</h3><p>Let’s say someone comes to us and says:</p><blockquote><em>“Design a URL shortener.”</em></blockquote><h3>Layer 1: Architecture — <strong>“What is the overall thing I’m building?”</strong></h3><p>This is the <strong>top-most level</strong>.<br>The highest zoom-out possible.</p><p>At this stage, I’m not thinking about code.<br>I’m not thinking about databases.<br>I’m not thinking about APIs.</p><p>I’m just asking one very basic question:</p><blockquote><em>What is the overall system?</em></blockquote><h4>URL Shortener — Big Picture</h4><p>So I tell myself:</p><blockquote><em>A URL shortener is a system where<br>a user gives a long URL<br>and gets a short URL,<br>and later, when someone opens the short URL,<br>they are redirected to the original long URL.</em></blockquote><p>That’s it. That sentence itself already defines the system.</p><p>From this, two <strong>very obvious flows</strong> come out:</p><ol><li><strong>Create short URL</strong></li></ol><ul><li>user gives long URL</li><li>system returns short URL</li></ul><p><strong>2. Redirect</strong></p><ul><li>user opens short URL</li><li>system redirects to long URL</li></ul><p>At architecture level, I’m done.</p><p>I’m not thinking how.<br>I’m just clear <strong>what this system is</strong>.</p><p>If I can’t explain the system in one or two simple sentences, that’s a signal that I don’t actually understand the problem yet. So I stay here for a bit.</p><h3>Layer 2: Components — “Okay, this is too big to think as one thing”</h3><p>Now I move one level down.</p><p>I say:</p><blockquote><em>“Fine, I know what a URL shortener is.<br> But I can’t build everything at once.<br> Let me break it.”</em></blockquote><p>So I ask:</p><blockquote><em>What are the major parts of this system?</em></blockquote><h4>Breaking URL Shortener into Components</h4><p>Very naturally, a few things come to mind.</p><p>For example:</p><ol><li><strong>URL Creation Component — </strong>Handles requests like: “Here is a long URL, give me a short one”</li><li><strong>Redirect Component — </strong>Handles requests like: “Someone opened short URL, where should I send them?”</li></ol><p>That’s already enough.</p><p>Two components. Clean &amp; Clear.</p><p>Notice something important:</p><ul><li>I didn’t force this</li><li>I didn’t overthink</li><li>These components came naturally from the problem</li></ul><p>That’s how components should feel.</p><h4>Why This Step Matters So Much</h4><p>Earlier, the problem was:</p><blockquote><em>“Design a URL shortener”</em></blockquote><p>Now the problem is:</p><ul><li>“Design URL creation”</li><li>“Design redirect”</li></ul><p>That’s <strong>much easier</strong>. And also very realistic. In real systems, these <em>are</em> often separate services.</p><h3>Layer 3: Modules — “Now let me go inside ONE component”</h3><p>Now I pick <strong>one component</strong>. Let’s start with <strong>URL Creation</strong>.</p><p>I completely ignore redirect for now.</p><p>This is very important: 👉 <strong>one thing at a time</strong></p><h4>Going Inside URL Creation Component</h4><p>Now I ask very boring, very basic questions.</p><p><strong>Question 1: How does a request even come in?</strong></p><p>User will probably call some API like:</p><pre>POST /shorten<br>{<br>  longUrl: &quot;https://example.com/some/very/long/url&quot;<br>}</pre><p>So immediately I realize: 👉 I need a <strong>web server.</strong></p><p>That’s one module.</p><p><strong>Question 2: Where do I store the mapping?</strong></p><p>Once I generate a short URL, I need to remember:</p><pre>short123  -&gt;  https://example.com/long</pre><p>Otherwise, redirect will never work.</p><p>So I need: 👉 a <strong>database.</strong></p><p>That’s another module.</p><p><strong>Question 3: How do I generate the short URL?</strong></p><p>Some logic must:</p><ul><li>generate a unique key</li><li>make sure it doesn’t clash</li><li>maybe encode it</li></ul><p>This logic could live:</p><ul><li>inside the web server</li><li>or as a separate service</li></ul><p>But logically, it’s another <strong>responsibility</strong>.</p><p>So I note: 👉 a <strong>short-code generator</strong></p><p>That’s another module.</p><p><strong>So Inside URL Creation, I Have:</strong></p><ul><li>Web server (handles request)</li><li>Short code generator (creates short string)</li><li>Database (stores mapping)</li></ul><p>That’s it.</p><h4>Pause — Notice What Just Happened</h4><p>We started with:</p><blockquote><em>“Design a URL shortener”</em></blockquote><p>And without stress, without jumping, we reached:</p><ul><li>concrete pieces</li><li>real responsibilities</li><li>implementable things</li></ul><p>This is <strong>exactly</strong> what system design is.</p><h4>Now Let’s Do the Redirect Component (Same Thinking)</h4><p>Now we switch components.</p><p>Forget URL creation.<br>Only think about <strong>redirect</strong>.</p><h4>What Does Redirect Need to Do?</h4><p>Very simple:</p><ol><li>User opens: <a href="https://hiimvikash.dev/writeups">short.ly/abc123</a></li><li>System should:</li></ol><ul><li>find the long URL</li><li>redirect the user</li></ul><p>That’s it.</p><h4>Modules Inside Redirect Component</h4><p>Again, ask boring questions.</p><ol><li>How does request come in? — Web server</li><li>How do I find long URL? — Database lookup</li><li>Should this be fast? — Yes Very fast, so maybe Cache (optional, but makes sense)</li></ol><p><strong>Now redirect component has:</strong></p><ul><li>Web server</li><li>Cache</li><li>Database</li></ul><p>Same database as before or different — we’ll decide later.<br>For now, clarity matters more than perfection.</p><h4>Putting the Layers Together</h4><p>Now step back and look.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*EjWpGuFwacgDTQXs9mVhPQ.png" /></figure><p>And now comes the real system design thinking:</p><blockquote><em>How do these talk to each other?<br>How do they scale?<br>What happens if something fails?</em></blockquote><p>But notice — we <strong>earned the right</strong> to think about those things.</p><p>We didn’t jump there blindly.</p><h3>Without realizing it, we already covered High Level Design</h3><p>Think about it.</p><p>When we were talking about:</p><ul><li>what a URL shortener is</li><li>what problem it solves</li><li>what the major parts are (URL creation, redirect)</li></ul><p>We never discussed code.<br>We never discussed implementation details.</p><p>We were only shaping the system:</p><ul><li>defining its boundaries</li><li>deciding responsibilities</li><li>splitting the problem into big, meaningful pieces</li></ul><p>This way of thinking — <br>where you stay at the big picture and organize the system — <br>is what people usually call <strong>High Level Design (HLD)</strong>.</p><p>Not as a term to memorize. Just as a name for this kind of thinking.</p><h3>And the moment we went inside a component, we crossed into Low Level Design</h3><p>Now notice what happened next.</p><p>The moment we said:</p><blockquote><em>“Okay, let’s go inside URL creation…”</em></blockquote><p>The questions changed.</p><p>We started asking:</p><ul><li>how does the request come in?</li><li>where do we store data?</li><li>what modules do we need?</li><li>how do these parts work together?</li></ul><p>We were no longer shaping the system. We were filling in the details.</p><p>This level of thinking — <br>where you talk about modules, flow, and internal structure — <br>is what’s usually called <strong>Low Level Design (LLD)</strong>.</p><p>Again, not as a definition.Just as a natural zoom-in.</p><h4><strong>A very simple way to remember it</strong></h4><p>If you ever need a mental shortcut:</p><blockquote><strong><em>HLD</em></strong><em> is about shaping the system<br></em><strong><em>LLD</em></strong><em> is about filling in the details</em></blockquote><p>Or even simpler:</p><blockquote><em>HLD answers </em>“what exists and why”<em><br>LLD answers </em>“how it works inside”</blockquote><p>That’s enough. No more theory needed.</p><h3>The Four Technical Decisions for Every Component</h3><p>Once components are clear, you go into technical details. For <strong>every component</strong>, think about these four things:</p><h4>1. Database and Caching</h4><ul><li>What data are we storing?</li><li>Which database should we use?</li><li>Do we need caching to make things faster?</li></ul><h4>2. Scaling and Fault Tolerance</h4><ul><li>How will this component scale?</li><li>What happens if one server crashes?</li></ul><h4>3. Asynchronous Processing</h4><ul><li>Does this need to happen immediately?</li><li>Can this be done in the background?</li></ul><p>For example:</p><ul><li>Feed generation in fb or instagram shouldn’t happen when you open the app; it should already be done in the background so the feed is ready instantly.</li></ul><p>That’s asynchronous processing.</p><h4>4. Communication</h4><ul><li>How do components talk to each other?</li><li>HTTP? gRPC? WebSockets?</li></ul><p>These details make the system real.</p><h3>This Is the Real Shift</h3><p>System design isn’t about having perfect answers.</p><p>It’s about <strong>thinking in the right order</strong>, together.</p><p>If we can:</p><ul><li>Explain what the system is in simple words</li><li>Break it into natural components</li><li>Go inside one component and find real modules</li><li>reason about data</li><li>think ahead about growth and failures</li><li>separate critical work from background work</li><li>stay mindful of communication</li></ul><p>Even if:</p><ul><li>some choices change later</li><li>some assumptions turn out wrong</li></ul><p>That’s okay. Design evolves.</p><p>Those things improve with time. This <strong>thinking process</strong> is the foundation.</p><p>For most of us, in our current roles, the majority of our time isn’t spent drawing architectures on a whiteboard.<br>It’s spent <strong>implementing things</strong>.</p><p>We’re writing code.<br>We’re building features.<br>We’re fixing bugs.<br>We’re working inside existing systems and existing constraints.</p><p>So it makes sense to start from a place that directly maps to what we do every day.</p><p>That’s why, in this upcoming blog series, we’ll start with <strong>Low Level Design (LLD) — </strong>focusing on how real components are structured, how responsibilities are split, and how design patterns show up in actual code.</p><p>But this isn’t where things stop.</p><p>As we grow in our careers, we don’t stop implementing — <br>we still write code.</p><p>But slowly, more time starts going into <strong>thinking before implementing</strong>.</p><p>We start spending more energy on:</p><ul><li>deciding architecture</li><li>making trade-offs</li><li>thinking about scale, cost, and failure cases</li></ul><p>This is where higher-level system design naturally comes into play.</p><p>So this series is intentionally structured in the same way growth usually happens.</p><p>We’ll start <strong>from the inside</strong>:</p><ul><li>with Low Level Design</li><li>with design patterns</li><li>with decisions that live close to code</li></ul><p>And then, step by step, we’ll <strong>zoom out</strong>:</p><ul><li>connecting those decisions to bigger architectural choices</li><li>understanding trade-offs at scale</li><li>and seeing how systems evolve as requirements grow</li></ul><blockquote>If this way of thinking about system design resonated with you,<br>I’ll be continuing this as a <strong>blog series on Medium — </strong><a href="https://hiimvikash.medium.com/list/engineering-from-first-principles-b2585b15af5a"><strong>Engineering from First Principle.</strong></a></blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1d10fd357c99" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[0. Engineering from First Principles: Why I’m Starting This Series]]></title>
            <link>https://hiimvikash.medium.com/0-engineering-from-first-principles-why-im-starting-this-series-a6f0dc132443?source=rss-6530c2ff5590------2</link>
            <guid isPermaLink="false">https://medium.com/p/a6f0dc132443</guid>
            <category><![CDATA[backend-engineering]]></category>
            <category><![CDATA[design-systems]]></category>
            <category><![CDATA[system-design-interview]]></category>
            <category><![CDATA[systems-thinking]]></category>
            <category><![CDATA[system-design-concepts]]></category>
            <dc:creator><![CDATA[Vikash Gupta]]></dc:creator>
            <pubDate>Thu, 15 Jan 2026 11:47:46 GMT</pubDate>
            <atom:updated>2026-02-11T14:47:17.207Z</atom:updated>
            <content:encoded><![CDATA[<h3>0. Engineering from First Principles: Why I’m Starting This</h3><p>Most of us start our engineering journey the same way.</p><p>We learn a frontend framework, a backend framework, connect them together, deploy an application, and make it work. And that’s a real achievement. That’s how almost everyone enters the industry — including me. And honestly, that’s perfectly fine.</p><p>But at some point, a quiet question shows up:</p><blockquote>“Is this engineering… or am I just assembling things that already exist?”</blockquote><h3>Why I’m Starting This Series</h3><p>Backend engineering has no shortage of content.</p><p>There are countless tutorials, courses, and blog posts that teach you how to build APIs, connect databases, deploy services, and make systems work. If you want to learn a framework, you’ll find hundreds of resources for it.</p><p>That part is not the problem.</p><p>While learning, I keep running into questions like:</p><ul><li>How does Hotstar handle massive traffic during India vs Pakistan matches?</li><li>How does Uber find the nearest driver in real time when millions of users are booking rides after office hours?</li><li>How does Flipkart handle an insane number of concurrent requests during Big Billion Days?</li></ul><p>These aren’t just “system design interview” questions.</p><p>They force you to think about:</p><ul><li>databases</li><li>networking</li><li>concurrency</li><li>trade-offs</li><li>real constraints</li></ul><p>And you can’t answer them properly unless you understand fundamentals.</p><p>Then deeper questions begin to surface:</p><ul><li>Where does the backend end, and where does the network begin?</li><li>What actually happens between a request leaving the client and hitting your service?</li><li>Which problems belong to the application, and which ones belong to the network?</li></ul><p>Most of the time, backend engineering and networking are taught as separate worlds. As a result, there’s a blurry edge between them that many of us never fully explore. Things work, but the boundary remains unclear.</p><p>One of my goals with this series is to <strong>bridge that gap — to slowly connect backend concepts with networking fundamentals</strong> and observe what happens between them. To understand systems not as isolated layers, but as parts of the same flow.</p><p>There’s another reason as well.</p><p>I want to be able to participate in system discussions with ease — by actually understanding what’s being discussed, what trade-offs are being made, and why certain decisions make sense in a given context.</p><p>This series is my way of fixing that.</p><p>I’ll be learning deliberately, step by step, and documenting what I understand along the way — partly to help others, but mainly to keep myself honest, consistent, and moving forward.</p><h3>What “First Principles” Means Here</h3><p>By <em>first principles</em>, I don’t mean reinventing everything or rejecting existing tools.</p><p>I mean understanding <strong>why things exist before accepting how they’re usually done</strong>.</p><ul><li>Why does object-oriented design exist beyond syntax?</li><li>Why do some systems scale gracefully while others collapse?</li><li>Why does one SQL query fly and another crawl?</li><li>Why does concurrency break things that look perfectly correct?</li></ul><p>This series is about slowing down and reasoning.</p><p>It’s not a tutorial series.<br>It’s not a claim of expertise.<br>It’s a documented thinking process.</p><h3>Who This Series Is Really For</h3><p>This series is designed for engineers who have <strong>already built backend applications</strong>.</p><p>If you’re a full-stack engineer, you’ve been everywhere — frontend, backend, APIs, databases — and now you want to deeply understand backend communication and system behavior.</p><p>If you’re a frontend engineer who has built backend services but still feels more confident on the UI side — this series will help bridge that gap.</p><p>If you’ve <strong>never built a backend system</strong>, this might feel heavy. And that’s okay. This is an intermediate-to-advanced journey, built on real confusions.</p><h3>The Path We’ll Follow and References :-</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UnuDXmbxKkKvt8NVMVRnVw.png" /></figure><p>It’s about <strong>understanding enough to feel confident</strong> when systems grow, traffic spikes, or things break.</p><p>If you’ve ever felt that discomfort — you’ll feel at home here.</p><p>This is <a href="https://hiimvikash.medium.com/list/engineering-from-first-principles-b2585b15af5a"><strong>Engineering from First Principles</strong></a><strong>.</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a6f0dc132443" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>