<?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 Ashish Kumar Sahoo on Medium]]></title>
        <description><![CDATA[Stories by Ashish Kumar Sahoo on Medium]]></description>
        <link>https://medium.com/@ashishksahoo?source=rss-95f47ff57945------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*qwUuE5SK183p_bPDw04Drw.png</url>
            <title>Stories by Ashish Kumar Sahoo on Medium</title>
            <link>https://medium.com/@ashishksahoo?source=rss-95f47ff57945------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 05 Dec 2026 19:26:53 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@ashishksahoo/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[Distributed Systems Explained: 14 Essential Concepts Every Backend Engineer Must Know (With…]]></title>
            <link>https://ashishksahoo.medium.com/distributed-systems-explained-14-essential-concepts-every-backend-engineer-must-know-with-3073dbebc10c?source=rss-95f47ff57945------2</link>
            <guid isPermaLink="false">https://medium.com/p/3073dbebc10c</guid>
            <category><![CDATA[system-design-interview]]></category>
            <category><![CDATA[system-design-concepts]]></category>
            <category><![CDATA[design-systems]]></category>
            <category><![CDATA[distributed-systems]]></category>
            <category><![CDATA[backend-development]]></category>
            <dc:creator><![CDATA[Ashish Kumar Sahoo]]></dc:creator>
            <pubDate>Tue, 03 Nov 2026 16:09:37 GMT</pubDate>
            <atom:updated>2026-11-03T16:09:37.920Z</atom:updated>
            <content:encoded><![CDATA[<h3>Distributed Systems Explained: 14 Essential Concepts Every Backend Engineer Must Know (With Real-World Examples)</h3><p><strong>A practical guide to Distributed Systems, Race Conditions, Distributed Locks, Leader Election, CAP Theorem, Idempotency, Eventual Consistency, Retries, and Fault Tolerance — with interview questions and answers.</strong></p><p>Distributed systems are among the most important topics for backend engineers, particularly those working with microservices, cloud infrastructure, databases, payment systems, background workers, and high-throughput applications.</p><p>But understanding distributed systems isn’t about memorizing 50 definitions.</p><p>It’s about understanding one fundamental problem:</p><p><strong>What happens when multiple independent processes work together, communicate over a network, share resources, and fail independently?</strong></p><p>Imagine building a job scheduling platform that executes 100,000 jobs using 10 independent worker processes.</p><p>What happens if:</p><ul><li>Two workers pick the same job?</li><li>A worker crashes halfway through execution?</li><li>A network request succeeds, but its response gets lost?</li><li>A worker’s lock expires while it is still processing?</li><li>The database becomes unavailable?</li><li>All workers retry failed requests simultaneously?</li></ul><p>These are not theoretical problems. They are everyday engineering challenges in distributed systems.</p><p>In this article, we’ll understand 14 essential distributed systems concepts using real-world scenarios, implementation approaches, and interview-ready explanations.</p><h3>1. Distributed Systems Fundamentals</h3><h3>What is a Distributed System?</h3><p>A distributed system is a collection of independent computers or processes that communicate over a network and coordinate to accomplish a common objective.</p><p>Consider a simple backend application.</p><p>A client sends a request to a FastAPI server, which communicates with PostgreSQL.</p><p>Now imagine your application grows.</p><p>Instead of one server, you introduce multiple API instances, background workers, and database replicas.</p><p>Your architecture becomes:</p><pre>                 Clients<br>                    |<br>                    v<br>               Load Balancer<br>                    |<br>          +---------+---------+<br>          |         |         |<br>          v         v         v<br>       API-1      API-2      API-3<br>          |         |         |<br>          +---------+---------+<br>                    |<br>                    v<br>                PostgreSQL<br>                    |<br>          +---------+---------+<br>          |         |         |<br>          v         v         v<br>       Worker-1  Worker-2  Worker-3</pre><p>Now multiple independent processes are executing simultaneously.</p><p>This is a distributed system.</p><h3>Why are distributed systems difficult?</h3><p>Unlike a single-process application, distributed systems introduce several challenges:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/816/1*2jGZPCp8etfmZfxoshiptA.png" /></figure><h3>Important principle</h3><p>In distributed systems, never assume another process is alive, available, responsive, or aware of what has happened.</p><h3>Interview answer</h3><p><strong>Q: What makes distributed systems difficult compared to monolithic applications?</strong></p><p>A distributed system consists of independent processes communicating over a network. Components can fail independently, network communication is unreliable, and multiple processes may modify shared state concurrently. Therefore, we need coordination, consistency guarantees, fault tolerance, retries, and idempotency mechanisms.</p><h3>2. Race Conditions</h3><h3>What is a Race Condition?</h3><p>A race condition occurs when multiple processes or threads access shared data concurrently, and the final result depends on the order in which their operations execute.</p><p>Let’s understand with a banking example.</p><p>Suppose an account has ₹1,000.</p><p>Two transactions simultaneously withdraw ₹500.</p><p>Expected result:</p><pre>Initial Balance = ₹1,000<br><br>Transaction A = -₹500<br>Transaction B = -₹500<br><br>Expected Final Balance = ₹0</pre><p>But internally:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/710/1*4_U8w1vgGifaSSNJfNjcBg.png" /></figure><p>Final balance: ₹500.</p><p>One withdrawal has effectively been lost.</p><p>This is called a <strong>lost update</strong>, a type of race condition.</p><h3>Race Conditions in Background Workers</h3><p>Imagine a job scheduler containing:</p><pre>job_id = 101<br>status = PENDING</pre><p>Two workers execute:</p><pre>job = get_pending_job()<br><br>if job:<br>    execute(job)</pre><p>Both workers might read the same pending job before either updates its status.</p><p>Consequently, both execute it.</p><h3>How do we prevent Race Conditions?</h3><p>There are four common approaches.</p><p><strong>1. Database transactions</strong></p><p>Ensure related database operations execute atomically.</p><p><strong>2. Pessimistic locking</strong></p><p>Use PostgreSQL row-level locks:</p><pre>SELECT *<br>FROM jobs<br>WHERE status = &#39;PENDING&#39;<br>FOR UPDATE;</pre><p><strong>3. Atomic operations</strong></p><p>Instead of reading and updating separately:</p><pre>UPDATE accounts<br>SET balance = balance - 500<br>WHERE id = 1<br>AND balance &gt;= 500;</pre><p>Check the affected row count to determine whether the operation succeeded.</p><p><strong>4. Optimistic concurrency control</strong></p><p>Use version numbers:</p><pre>UPDATE jobs<br>SET status = &#39;PROCESSING&#39;,<br>    version = version + 1<br>WHERE id = 101<br>AND version = 1;</pre><p>Only one competing transaction can successfully update the expected version.</p><h3>Interview answer</h3><p>A race condition occurs when concurrent operations access shared state and produce an outcome dependent on execution timing. I prevent it using atomic database operations, transactions, row-level locking, unique constraints, or optimistic concurrency control, depending on the use case.</p><h3>3. Distributed Locks</h3><h3>What is a Distributed Lock?</h3><p>A distributed lock is a coordination mechanism that ensures only one process can hold a particular lock at a time across multiple independent processes or machines.</p><p>Imagine five workers trying to generate the same monthly financial report.</p><p>Only one should execute the operation.</p><p>A distributed lock helps coordinate this.</p><h3>How does it work?</h3><p>Redis provides a common way to implement distributed locks.</p><pre>SET report_lock worker_1 NX EX 30</pre><p>Meaning:</p><ul><li>report_lock: Lock identifier.</li><li>worker_1: Lock owner.</li><li>NX: Create only if the key does not exist.</li><li>EX 30: Expire after 30 seconds.</li></ul><p>If Worker 1 successfully acquires the lock, Worker 2 cannot acquire the same lock while it remains valid.</p><pre>             Redis<br>               |<br>          report_lock<br>               |<br>          Worker 1<br>           LOCKED<br><br>          Worker 2<br>           WAITING</pre><h3>Important: Lock Ownership</h3><p>Never release a distributed lock using an unconditional delete.</p><p>Consider:</p><ol><li>Worker 1 acquires a lock.</li><li>Its lock expires.</li><li>Worker 2 acquires the same lock.</li><li>Worker 1 resumes and deletes the lock.</li></ol><p>Worker 1 has now deleted Worker 2’s lock.</p><p>The solution is to associate a unique ownership token with each lock and release it only if the stored token matches.</p><p>Use an atomic compare-and-delete operation, such as a Redis Lua script.</p><h3>Where are Distributed Locks Used?</h3><ul><li>Preventing concurrent execution of critical operations.</li><li>Coordinating background workers.</li><li>Preventing duplicate scheduled operations.</li><li>Coordinating distributed maintenance tasks.</li><li>Managing access to shared resources.</li></ul><h3>Interview answer</h3><p>A distributed lock coordinates access to shared resources across multiple processes. It can be implemented using Redis, a database, or coordination services. A production implementation must consider expiration, ownership verification, stale lock holders, and fencing tokens.</p><h3>4. Leader Election</h3><h3>What is Leader Election?</h3><p>Leader election is the process of selecting one process among multiple distributed processes to act as the coordinator or leader.</p><p>Imagine you have 10 worker processes.</p><p>All can execute jobs, but only one should perform cluster-wide maintenance.</p><p>You need a leader.</p><pre>       Worker 1<br>       Worker 2<br>       Worker 3<br>       Worker 4<br>       Worker 5<br><br>             |<br>             v<br><br>         Leader Election<br><br>             |<br>             v<br><br>          Worker 2<br>            LEADER<br><br>       Remaining workers<br>          FOLLOWERS<br><br></pre><p>If Worker 2 crashes, the system elects another leader.</p><h3>How is Leader Election Implemented?</h3><p>Common approaches include:</p><p><strong>Raft and Paxos:</strong> Consensus algorithms that help distributed nodes agree on decisions.</p><p><strong>etcd and ZooKeeper:</strong> Coordination systems that support distributed coordination and leader election.</p><p><strong>Database-based leadership:</strong> Maintain an ownership record with an expiration time, acquired through atomic database operations.</p><h3>What is Split-Brain?</h3><p>Split-brain occurs when multiple nodes independently believe they are the leader.</p><p>For example, a network partition prevents Worker 2 from communicating with Worker 1.</p><p>Worker 2 assumes Worker 1 has failed and becomes leader.</p><p>But Worker 1 is still running.</p><p>Now both workers believe they are leaders.</p><p>This can cause conflicting writes and duplicate operations.</p><p>Consensus protocols and fencing mechanisms help prevent stale leaders from performing conflicting operations.</p><h3>Interview answer</h3><p>Leader election selects one process as the coordinator of a distributed system. It is useful for cluster-wide scheduling, maintenance, and coordination. Systems such as etcd and ZooKeeper support coordination, while consensus algorithms such as Raft provide a foundation for safe leader selection.</p><h3>5. Leases and Heartbeats</h3><p>These two concepts are closely related.</p><h3>What is a Lease?</h3><p>A lease is a time-limited permission granted to a process to hold a resource or perform an operation.</p><p>Example:</p><pre>Worker 1 acquires lease.<br><br>Lease Duration = 30 seconds.</pre><p>If Worker 1 crashes, its lease eventually expires, allowing another worker to acquire the resource.</p><h3>What is a Heartbeat?</h3><p>A heartbeat is a periodic signal sent by a process to indicate that it is still alive or making progress.</p><p>Example:</p><pre>Worker 1 ---- Heartbeat ----&gt; Database<br><br>Worker 1 ---- Heartbeat ----&gt; Database<br><br>Worker 1 ---- Heartbeat ----&gt; Database</pre><p>The system tracks:</p><pre>last_heartbeat_at = current_timestamp</pre><p>If no heartbeat arrives within the configured timeout, the worker may be considered unhealthy.</p><h3>How do They Work Together?</h3><p>Suppose:</p><pre>Lease Duration: 30 seconds<br>Heartbeat Interval: 10 seconds</pre><p>TimeEvent00sWorker acquires lease10sSends heartbeat20sSends heartbeat30sRenews lease40sSends heartbeat</p><p>If the worker crashes, the lease eventually expires.</p><p>Another worker can acquire the resource.</p><h3>Where are They Used?</h3><ul><li>Distributed job schedulers.</li><li>Kubernetes node health monitoring.</li><li>Worker coordination.</li><li>Distributed locks.</li><li>Cluster management.</li></ul><h3>Interview answer</h3><p>A lease provides time-limited ownership of a resource, while a heartbeat periodically communicates that a process is alive or making progress. Together, they help detect failed workers and recover abandoned tasks.</p><h3>6. Fencing Tokens</h3><p>This is one of the most important senior-level distributed systems concepts.</p><h3>The Problem with Leases</h3><p>Imagine:</p><ol><li>Worker 1 acquires a lock.</li><li>Its lease expires after 30 seconds.</li><li>Worker 1 pauses due to CPU starvation.</li><li>Worker 2 acquires the same lock.</li><li>Worker 2 starts processing.</li><li>Worker 1 resumes.</li></ol><p>Now both workers might execute the operation.</p><p>Worker 1 is a stale lock holder.</p><p>A lease alone cannot guarantee that the previous owner stops executing when its expiration time passes.</p><h3>What is a Fencing Token?</h3><p>A fencing token is a monotonically increasing number assigned to each new owner of a resource.</p><p>Example:</p><pre>Worker 1 acquires lock -&gt; Token 101<br><br>Worker 2 acquires lock -&gt; Token 102<br><br>Worker 3 acquires lock -&gt; Token 103</pre><p>Every new owner receives a higher token.</p><p>The protected resource rejects operations carrying an older token.</p><p>Example:</p><pre>UPDATE resources<br>SET value = &#39;Updated&#39;,<br>    fencing_token = 102<br>WHERE id = 1<br>AND fencing_token &lt; 102;</pre><p>When Worker 1 resumes and tries to write using token 101, the database rejects the stale update.</p><p>The important point is that the resource itself must enforce the fencing token.</p><h3>Where are Fencing Tokens Used?</h3><ul><li>Distributed storage.</li><li>Database coordination.</li><li>Distributed locking.</li><li>Resource ownership.</li><li>Preventing stale workers from overwriting newer data.</li></ul><h3>Interview answer</h3><p>A lease provides temporary ownership, but an old owner can continue running after its lease expires. Fencing tokens solve this by assigning monotonically increasing ownership numbers. The protected resource rejects writes with stale tokens, preventing older owners from overwriting newer work.</p><h3>7. At-Most-Once vs At-Least-Once Delivery</h3><p>Imagine a background job:</p><pre>Send payment confirmation email.</pre><p>How many times should it execute?</p><p>Ideally, once.</p><p>But failures make this difficult.</p><h3>At-Most-Once Delivery</h3><p>A message is delivered zero or one time.</p><pre>Producer<br>   |<br>   v<br>Message System<br>   |<br>   v<br>Consumer</pre><p>If the message is lost or the consumer fails before processing, it is not delivered again.</p><p><strong>Guarantee: No redelivery, but messages can be lost.</strong></p><h3>At-Least-Once Delivery</h3><p>A message is delivered one or more times.</p><p>Consider:</p><ol><li>Consumer receives a message.</li><li>Consumer processes it successfully.</li><li>Consumer crashes before acknowledging completion.</li><li>The system assumes processing failed.</li><li>The message is delivered again.</li></ol><p>Now the same job might execute twice.</p><p><strong>Guarantee: Messages are retried, but duplicates are possible.</strong></p><h3>Comparison</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/740/1*-nLHJLxg3sJ_jK_s3KV1EQ.png" /></figure><p>For payment processing and critical background jobs, at-least-once delivery combined with idempotent processing is usually preferable.</p><h3>Interview answer</h3><p>At-most-once delivery prevents redelivery but may lose messages. At-least-once delivery retries until acknowledgement but can create duplicates. For critical operations, I generally prefer at-least-once delivery with idempotent consumers.</p><h3>8. Exactly-Once Processing and Its Limitations</h3><p>Exactly-once processing is one of the most misunderstood concepts in distributed systems.</p><h3>What Does Exactly-Once Mean?</h3><p>Exactly-once processing means a logical operation produces its intended effect only once, even when messages are delivered multiple times or components fail.</p><p>Consider a payment system.</p><pre>Customer pays ₹1,000.</pre><p>Your backend needs to:</p><ol><li>Receive the payment request.</li><li>Process the payment.</li><li>Update the database.</li><li>Send confirmation.</li></ol><p>Now imagine the payment succeeds, but your backend crashes before returning the response.</p><p>The client retries.</p><p>Without protection, the customer could be charged twice.</p><h3>Why is Exactly-Once Difficult?</h3><p>Distributed systems cannot always distinguish between:</p><ul><li>An operation that failed.</li><li>An operation that succeeded but whose response was lost.</li></ul><p>This creates uncertainty.</p><h3>How do We Achieve Effectively-Once Business Effects?</h3><p>Combine:</p><ol><li>Idempotency keys.</li><li>Database transactions.</li><li>Unique constraints.</li><li>Deduplication.</li><li>Transactional outbox patterns.</li><li>Idempotent external APIs, where supported.</li></ol><p>For example:</p><pre>idempotency_key = order_123_payment</pre><p>Before processing, check whether the operation has already been completed.</p><p>If it has, return the stored result.</p><p>Otherwise, process it safely and persist the result.</p><p><strong>Important distinction:</strong> Exactly-once guarantees can be provided within bounded system boundaries. For example, Kafka supports transactional processing within its supported Kafka boundaries. This does not automatically guarantee exactly-once effects in an external payment gateway or arbitrary third-party service.</p><h3>Interview answer</h3><p>Exactly-once delivery and exactly-once business processing are different. Most distributed applications use at-least-once delivery combined with idempotent consumers and transactional state updates to achieve effectively-once business effects. End-to-end guarantees require coordination across every relevant system boundary.</p><h3>9. Idempotency</h3><p>Idempotency is one of the most important concepts for backend engineers.</p><h3>What is Idempotency?</h3><p>An operation is idempotent if executing it multiple times produces the same intended final effect as executing it once.</p><p>Mathematically:</p><pre>f(f(x)) = f(x)</pre><h3>Example 1: Idempotent Operation</h3><pre>PUT /users/101</pre><p>Request:</p><pre>{<br>  &quot;name&quot;: &quot;Ashish&quot;<br>}</pre><p>Executing this request once or five times results in the same user representation.</p><h3>Example 2: Non-Idempotent Operation</h3><pre>POST /accounts/101/deposit</pre><p>Request:</p><pre>{<br>  &quot;amount&quot;: 1000<br>}</pre><p>If executed five times, the account receives ₹5,000.</p><p>This is not idempotent.</p><h3>How do We Make an API Idempotent?</h3><p>Introduce an idempotency key.</p><p>Client sends:</p><pre>POST /payments<br>Idempotency-Key: payment-123</pre><p>The backend:</p><ol><li>Checks whether the key already exists.</li><li>Returns the previous result if the operation has completed.</li><li>Otherwise, processes the operation.</li><li>Stores the result against the key.</li></ol><p>Example database table:</p><pre>CREATE TABLE idempotency_records (<br>    id BIGSERIAL PRIMARY KEY,<br>    idempotency_key TEXT UNIQUE NOT NULL,<br>    status TEXT NOT NULL,<br>    response JSONB<br>);</pre><p>A production implementation must also handle concurrent requests using the same key, in-progress requests, payload mismatches, retention, and external side effects.</p><h3>Where is Idempotency Used?</h3><ul><li>Payment APIs.</li><li>Order creation.</li><li>Background job processing.</li><li>Webhooks.</li><li>Message consumers.</li><li>Retryable HTTP requests.</li></ul><h3>Interview answer</h3><p>Idempotency ensures repeated execution of an operation produces the same intended business effect as a single execution. I implement it using unique idempotency keys, database constraints, and transactional state updates to prevent duplicate processing.</p><h3>10. Eventual Consistency</h3><p>Imagine a social media application.</p><p>A user updates their profile name.</p><p>Your architecture contains a primary database and two read replicas.</p><pre>Primary Database<br>                    |<br>               Replication<br>                /       \<br>               v         v<br>          Replica 1   Replica 2</pre><p>The primary database updates immediately.</p><p>But replication takes time.</p><p>For a short period:</p><pre>Primary DB: Ashish<br>Replica 1:  Ashish<br>Replica 2:  Old Name</pre><p>Eventually, replication catches up.</p><p>All replicas show the updated value.</p><p>This is eventual consistency.</p><h3>Definition</h3><p>Eventual consistency means that if no new updates occur, distributed replicas will eventually converge to the same value.</p><h3>Strong Consistency vs Eventual Consistency</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/847/1*PPfGNr5ks17nvKNrqvhYkQ.png" /></figure><h3>Where is Eventual Consistency Used?</h3><ul><li>Social media like counts.</li><li>Product recommendation systems.</li><li>Search indexes.</li><li>Distributed caches.</li><li>Database replicas.</li><li>Analytics dashboards.</li></ul><h3>How do We Handle Stale Reads?</h3><p>Depending on business requirements:</p><ul><li>Read from the primary database.</li><li>Invalidate caches after updates.</li><li>Use version numbers.</li><li>Implement read-your-writes consistency.</li><li>Use replication-aware routing.</li></ul><h3>Interview answer</h3><p>Eventual consistency means replicas may temporarily return stale data, but they converge if no new updates occur. It is commonly used in distributed databases, caches, search indexes, and read-heavy systems.</p><h3>11. CAP Theorem</h3><p>CAP theorem is one of the most frequently asked distributed systems interview topics.</p><p>CAP stands for:</p><ul><li>Consistency.</li><li>Availability.</li><li>Partition Tolerance.</li></ul><h3>Understanding the Three Properties</h3><p><strong>Consistency (C)</strong></p><p>Every successful read returns the latest committed value, according to the consistency model used in CAP discussions: linearizability.</p><p><strong>Availability (A)</strong></p><p>Every request received by a non-failing node receives a non-error response, even if the returned value might be stale.</p><p><strong>Partition Tolerance (P)</strong></p><p>The system continues operating despite network communication failures between nodes.</p><h3>Imagine a Distributed Database</h3><pre>Node A<br>          |<br>          |<br>     Network Failure<br>          X<br>          |<br>       Node B</pre><p>Node A and Node B cannot communicate.</p><p>A client sends a request to Node A.</p><p>What should the system do?</p><p>Option 1: Reject or delay the request because it cannot guarantee consistency.</p><p>Option 2: Accept the request and respond, even though Node B might have conflicting or stale information.</p><p>This creates the CAP trade-off.</p><h3>CP Systems</h3><p>Prioritize consistency over availability during a network partition.</p><p>The system may reject or delay requests rather than risk returning inconsistent data.</p><h3>AP Systems</h3><p>Prioritize availability during a network partition.</p><p>Different nodes may accept updates independently, requiring conflict resolution later.</p><h3>Important Clarification</h3><p>CAP does not mean a system permanently chooses only two properties.</p><p>It describes a trade-off during a network partition.</p><p>When there is no partition, a system can provide both consistency and availability under appropriate conditions.</p><h3>Interview answer</h3><p>CAP theorem states that during a network partition, a distributed data system cannot simultaneously guarantee both linearizable consistency and availability. It must choose whether to reject or delay some operations to preserve consistency or continue responding while potentially returning stale or conflicting data.</p><h3>12. Retry Mechanisms</h3><p>Failures are inevitable in distributed systems.</p><p>Imagine your backend is processing 10,000 jobs.</p><p>Suddenly:</p><ul><li>PostgreSQL becomes unavailable.</li><li>An external API times out.</li><li>A network request fails.</li><li>A worker crashes.</li></ul><p>How should your application recover?</p><p>A retry mechanism attempts an operation again when a temporary failure occurs.</p><p>Example:</p><pre>async def call_external_api():<br>    try:<br>        return await external_api.request()<br>    except TemporaryError:<br>        return await external_api.request()</pre><p>This is a basic retry.</p><p>But blindly retrying is dangerous.</p><h3>What is a Retry Storm?</h3><p>Imagine 1,000 workers retrying a failed database request every second.</p><pre>1000 workers<br>     |<br>     v<br>1000 requests/second<br>     |<br>     v<br>Database already overloaded<br>     |<br>     v<br>More failures<br>     |<br>     v<br>More retries</pre><p>The retry mechanism makes the outage worse.</p><p>This is called a retry storm.</p><h3>Retryable vs Non-Retryable Errors</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/1*XXDTvMf3QAwdiFjDAvJnnw.png" /></figure><p>Retries must also be bounded and designed around operation idempotency.</p><h3>Interview answer</h3><p>Retries improve resilience by recovering from temporary failures. However, they must use retry limits, timeouts, backoff, jitter, and error classification. Non-idempotent operations must be protected against duplicate side effects.</p><h3>13. Exponential Backoff and Jitter</h3><h3>What is Exponential Backoff?</h3><p>Instead of retrying after a fixed interval, increase the delay after every failed attempt.</p><p>Example:</p><pre>Attempt 1 -&gt; Wait 1 second<br>Attempt 2 -&gt; Wait 2 seconds<br>Attempt 3 -&gt; Wait 4 seconds<br>Attempt 4 -&gt; Wait 8 seconds<br>Attempt 5 -&gt; Wait 16 seconds</pre><p>Formula:</p><pre>delay = min(max_delay, base_delay × 2^attempt)</pre><p>Python implementation:</p><pre>delay = min(<br>    30,<br>    1 * (2 ** attempt)<br>)</pre><h3>What is Jitter?</h3><p>Jitter introduces randomness into the retry delay.</p><p>Why?</p><p>Imagine 1,000 workers fail simultaneously.</p><p>Without jitter, all workers retry after the same interval.</p><p>With jitter:</p><pre>Worker 1 -&gt; 1.4 seconds<br>Worker 2 -&gt; 2.1 seconds<br>Worker 3 -&gt; 1.8 seconds<br>Worker 4 -&gt; 2.7 seconds</pre><p>Requests become distributed over time.</p><h3>Full Jitter Implementation</h3><pre>import random<br>def get_retry_delay(attempt):<br>    base_delay = 1<br>    max_delay = 30<br>    exponential_delay = min(<br>        max_delay,<br>        base_delay * (2 ** attempt)<br>    )<br>    return random.uniform(0, exponential_delay)</pre><p>This is called full jitter.</p><h3>Where is it Used?</h3><ul><li>AWS SDKs.</li><li>HTTP clients.</li><li>Database connection retries.</li><li>Distributed workers.</li><li>Message consumers.</li><li>Microservice communication.</li></ul><h3>Interview answer</h3><p>Exponential backoff increases the delay between retries exponentially. Jitter adds randomness to those delays, preventing many clients from retrying simultaneously and overwhelming an already unhealthy service.</p><h3>14. Failure Detection</h3><p>How do you know whether a worker is actually dead?</p><p>Imagine:</p><pre>Worker 1<br>   |<br>   X<br>Network unavailable</pre><p>Your monitoring system stops receiving heartbeats.</p><p>Is Worker 1 dead?</p><p>Not necessarily.</p><p>It might be:</p><ul><li>Temporarily disconnected.</li><li>CPU overloaded.</li><li>Experiencing a long garbage collection pause.</li><li>Running slowly.</li><li>Completely crashed.</li></ul><p>This is why failure detection is difficult.</p><h3>Common Failure Detection Mechanisms</h3><p><strong>1. Heartbeats</strong></p><p>Workers periodically communicate their health.</p><p><strong>2. Timeouts</strong></p><p>If a response doesn’t arrive within the expected duration, the operation is considered timed out.</p><p><strong>3. Health checks</strong></p><p>Applications expose endpoints:</p><pre>GET /health</pre><p><strong>4. Monitoring</strong></p><p>Track:</p><ul><li>CPU usage.</li><li>Memory.</li><li>Request latency.</li><li>Error rates.</li><li>Worker status.</li><li>Database connectivity.</li></ul><h3>Important Distinction</h3><p>A timeout does not prove that a process has crashed.</p><p>It only tells you that the expected response did not arrive within the configured time.</p><h3>Interview answer</h3><p>I would detect failed workers using periodic heartbeats, lease expiration, and health monitoring. If a worker fails to renew its lease within the expected period, its jobs can be recovered. However, I would use ownership verification and fencing tokens to prevent stale workers from modifying shared state.</p><h3>15. Graceful Shutdown</h3><p>Graceful shutdown is essential for production backend applications.</p><p>Imagine your worker is processing a job.</p><pre>Worker 1<br>   |<br>   v<br>Processing Job 101</pre><p>Suddenly, Kubernetes restarts the container.</p><p>If the process immediately terminates:</p><ul><li>The job might remain unfinished.</li><li>Database transactions might be interrupted.</li><li>External API calls might complete without the result being recorded.</li><li>The job might execute again.</li></ul><p>We need graceful shutdown.</p><h3>What is Graceful Shutdown?</h3><p>Graceful shutdown is the process of stopping an application in a controlled manner while allowing ongoing operations to complete or safely release their resources.</p><h3>Correct Shutdown Sequence</h3><pre>Shutdown Signal<br>                 |<br>                 v<br>       Stop accepting new jobs<br>                 |<br>                 v<br>       Finish ongoing operations<br>                 |<br>                 v<br>       Commit database changes<br>                 |<br>                 v<br>       Release resources/locks<br>                 |<br>                 v<br>       Close database connections<br>                 |<br>                 v<br>          Process exits</pre><h3>Python Example</h3><pre>import asyncio<br>import signal<br>shutdown_event = asyncio.Event()<br>def handle_shutdown():<br>    shutdown_event.set()<br>async def worker():<br>    while not shutdown_event.is_set():<br>        job = await fetch_next_job()<br>        if job:<br>            await process_job(job)<br>    print(&quot;Worker shutting down safely&quot;)<br>async def main():<br>    loop = asyncio.get_running_loop()<br>    loop.add_signal_handler(<br>        signal.SIGTERM,<br>        handle_shutdown<br>    )<br>    loop.add_signal_handler(<br>        signal.SIGINT,<br>        handle_shutdown<br>    )<br>    await worker()<br>asyncio.run(main())</pre><p>This is a simplified illustration. Production implementations also need bounded shutdown timeouts, cancellation handling, cleanup in finally blocks, and safe recovery of unfinished jobs.</p><h3>SIGTERM vs SIGKILL</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/570/1*M-UpXIdZ759x7z2Q-vDwIw.png" /></figure><p>Kubernetes typically sends SIGTERM and, after its configured grace period, forcefully terminates the container.</p><h3>Interview answer</h3><p>Graceful shutdown allows a service to stop accepting new work, finish or safely release in-flight operations, commit required state changes, release resources, and close connections before exiting.</p><h3>Putting Everything Together: Design a Reliable Distributed Job Scheduler</h3><p>Now let’s connect all 14 concepts.</p><p>Imagine you are designing a job scheduling platform with:</p><ul><li>100,000 scheduled jobs.</li><li>10 independent worker processes.</li><li>Multiple organizations.</li><li>No duplicate business execution.</li><li>Worker crash recovery.</li><li>Reliable job processing.</li></ul><p>Architecture:</p><pre>API Layer<br>                      |<br>                      v<br>                 PostgreSQL<br>                      |<br>                      v<br>              Atomic Job Claiming<br>                      |<br>          +-----------+-----------+<br>          |           |           |<br>          v           v           v<br>       Worker 1    Worker 2    Worker 3<br>          |           |           |<br>          +-----------+-----------+<br>                      |<br>                      v<br>                Job Processing<br>                      |<br>                      v<br>               External Services</pre><h3>How Each Concept Solves a Real Problem</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/851/1*rezfXRSNegeoUQ5vc9wS0A.png" /></figure><h3>The Complete Job Execution Lifecycle</h3><p>A production-grade worker might follow this sequence:</p><p><strong>Step 1: Claim a job</strong></p><p>Atomically claim a pending job using PostgreSQL transactions and row locking.</p><p><strong>Step 2: Establish ownership</strong></p><p>Record the worker identity, lease expiration, and ownership generation or fencing token.</p><p><strong>Step 3: Process the job</strong></p><p>Execute the business operation while periodically renewing the lease.</p><p><strong>Step 4: Protect against duplicates</strong></p><p>Use an idempotency key so that retries cannot repeat the same business effect.</p><p><strong>Step 5: Handle failures</strong></p><p>Retry temporary errors using bounded exponential backoff and jitter.</p><p><strong>Step 6: Recover abandoned jobs</strong></p><p>If a worker stops renewing its lease, make its expired job eligible for recovery.</p><p><strong>Step 7: Protect against stale workers</strong></p><p>Reject stale ownership tokens when updating protected resources.</p><p><strong>Step 8: Complete transactionally</strong></p><p>Update the job state and persist related database changes in an appropriate transaction.</p><p><strong>Step 9: Shut down safely</strong></p><p>Stop accepting new jobs, finish or safely release in-flight work, and close connections.</p><p>This is how distributed systems concepts translate into real production engineering.</p><h3>25 Frequently Asked Distributed Systems Interview Questions</h3><p>Use these to test whether you genuinely understand the concepts.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1007/1*GUx2-q9ssv5QYo-KECwiRA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kPmlvpKiBq0gud1qtD__VA.png" /></figure><h3>The Ultimate Distributed Systems Cheat Sheet</h3><p>This is the section to revisit before interviews.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/687/1*mALFBvquR2wk6yGuxM0Uxw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/851/1*rezfXRSNegeoUQ5vc9wS0A.png" /></figure><h3>Five Golden Principles to Remember</h3><p>If you remember only five things from this article, remember these:</p><p><strong>1. Never trust distributed communication.</strong></p><p>A timeout does not mean the remote operation failed. It may have succeeded while the response was lost.</p><p><strong>2. Never assume a worker executes a job only once.</strong></p><p>Design consumers and business operations to be idempotent.</p><p><strong>3. Never assume a lock guarantees correctness forever.</strong></p><p>Leases can expire, and stale processes can resume. Use fencing tokens when stale writes must be prevented.</p><p><strong>4. Never retry without a strategy.</strong></p><p>Use bounded retries, exponential backoff, jitter, timeouts, and error classification.</p><p><strong>5. Always design for failure.</strong></p><p>Workers crash, databases become unavailable, networks disconnect, and containers restart. Recovery must be part of the architecture, not an afterthought.</p><h3>Final Thoughts</h3><p>Distributed systems engineering is fundamentally about coordination, reliability, consistency, and failure management.</p><p>A junior developer might ask:</p><p>“How do I execute this job?”</p><p>A senior backend engineer asks:</p><ul><li>What if two workers run it at the same time?</li><li>What if the worker crashes after completing the external operation?</li><li>What if the database update fails?</li><li>What if the lock expires while the worker is still processing?</li><li>What if the network response is lost?</li><li>What if all workers retry simultaneously?</li><li>How will the system recover without duplicating business effects?</li></ul><p>That difference in thinking is what separates someone who can write backend code from someone who can design reliable backend infrastructure.</p><p><strong>The most important lesson: Distributed systems are not designed around the assumption that everything works. They are designed around the assumption that something will eventually fail.</strong></p><p>Master these concepts, understand their interactions, and you’ll have a strong foundation for backend engineering interviews at product-based companies and infrastructure-focused startups.</p><p><em>Suggested next reading: Database Internals, PostgreSQL Concurrency Control, System Design, Message Queues, Kafka, and Fault-Tolerant Microservices.</em></p><p>If you find this article helpful, <a href="https://ashishksahoo.medium.com/">follow me</a> for more practical insights on Backend Engineering, System Design, Distributed Systems, Python, and Software Architecture.</p><p>Let’s learn, build, and grow together! 🚀</p><p>Your support means a lot. ❤️</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3073dbebc10c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[PostgreSQL & Backend System Design: From Database Fundamentals to Building Scalable Systems]]></title>
            <link>https://ashishksahoo.medium.com/postgresql-backend-system-design-from-database-fundamentals-to-building-scalable-systems-861678c72b8b?source=rss-95f47ff57945------2</link>
            <guid isPermaLink="false">https://medium.com/p/861678c72b8b</guid>
            <category><![CDATA[system-design-concepts]]></category>
            <category><![CDATA[postgresql]]></category>
            <category><![CDATA[database]]></category>
            <category><![CDATA[backend-architecture]]></category>
            <category><![CDATA[software-architecture]]></category>
            <dc:creator><![CDATA[Ashish Kumar Sahoo]]></dc:creator>
            <pubDate>Mon, 02 Nov 2026 17:46:46 GMT</pubDate>
            <atom:updated>2026-11-02T17:46:46.135Z</atom:updated>
            <content:encoded><![CDATA[<p><em>Understanding transactions, concurrency, indexing, query optimization, caching, distributed architecture, and production scalability through real-world examples.</em></p><h3>Introduction</h3><p>Building a backend application is relatively straightforward when the traffic is low, the database is small, and only a few users interact with the system.</p><p>The real engineering challenges begin when:</p><ul><li>Multiple requests try to update the same database record.</li><li>Thousands of users access the application at the same time.</li><li>Database queries become increasingly slow.</li><li>Multiple application instances need to coordinate.</li><li>Workers crash while processing background jobs.</li><li>A database becomes a bottleneck.</li><li>The system needs to remain available during deployments and failures.</li></ul><p>These problems require more than knowing how to write APIs or SQL queries. They require an understanding of database internals, concurrency, performance optimization, distributed systems, and architectural trade-offs.</p><p>In this article, we&#39;ll build that understanding progressively through four phases:</p><ol><li><strong>Database Fundamentals:</strong> How databases maintain correctness under concurrent operations.</li><li><strong>Database Indexing:</strong> How databases retrieve information efficiently.</li><li><strong>Performance Optimization:</strong> How to identify and eliminate bottlenecks.</li><li><strong>System Scaling:</strong> How to evolve an application to handle increasing traffic.</li></ol><p>We’ll use two practical systems throughout the article:</p><ul><li>A URL Shortener that creates short links, redirects users, and records analytics.</li><li>A Database-Backed Job Scheduler that allows multiple workers to execute scheduled jobs without claiming the same job concurrently.</li></ul><h3>Phase 1: Database Fundamentals</h3><p>Before discussing scalability, we need to understand how a database handles data, transactions, and concurrent operations.</p><h3>1. ACID Properties</h3><p>ACID represents four properties that help databases maintain transaction correctness.</p><h3>Atomicity</h3><p>A transaction is treated as one logical unit.</p><p>Either all operations succeed, or none are committed.</p><p>Consider a banking transfer:</p><ul><li>Account A has ₹10,000.</li><li>Account B has ₹5,000.</li><li>We transfer ₹2,000 from A to B.</li></ul><p>Two operations are required:</p><ol><li>Deduct ₹2,000 from A.</li><li>Add ₹2,000 to B.</li></ol><p>If the first operation succeeds but the second fails, the database must not leave the accounts in an inconsistent state.</p><pre>BEGIN;<br>UPDATE accounts<br>SET balance = balance - 2000<br>WHERE id = 1;<br>UPDATE accounts<br>SET balance = balance + 2000<br>WHERE id = 2;<br>COMMIT;</pre><p>If an operation fails, the transaction can be rolled back.</p><h3>Consistency</h3><p>Every committed transaction must preserve the database’s defined constraints and invariants.</p><p>For example:</p><ul><li>Account balance must not be negative.</li><li>Email addresses must be unique.</li><li>A job must reference a valid organization.</li><li>A URL short code must be unique.</li></ul><p>These rules should be enforced using database constraints wherever possible.</p><pre>CREATE TABLE accounts (<br>    id BIGINT PRIMARY KEY,<br>    balance NUMERIC(12, 2)<br>        CHECK (balance &gt;= 0)<br>);</pre><p>Consistency does not mean PostgreSQL automatically understands every business rule. Developers must encode the required constraints.</p><h3>Isolation</h3><p>Isolation controls how concurrent transactions interact.</p><p>Imagine two users trying to purchase the last available product.</p><p>Both requests read:</p><pre>Available stock = 1</pre><p>Both attempt to purchase it.</p><p>Without suitable concurrency control, the application may oversell the product.</p><p>Isolation levels and locking mechanisms help prevent these problems.</p><h3>Durability</h3><p>Once a transaction is successfully committed, its changes should survive a database crash according to the configured durability guarantees.</p><p>PostgreSQL uses Write-Ahead Logging (WAL).</p><p>Instead of relying only on modifying database pages directly, PostgreSQL records changes in its WAL. During recovery, it can replay the necessary log records.</p><p>Durability depends on configuration and storage guarantees. For example, synchronous_commit affects when PostgreSQL acknowledges a commit relative to WAL flushing.</p><p><strong>Interview takeaway:</strong> ACID provides the foundation for reliable database transactions, but developers still need to design appropriate constraints, isolation levels, and concurrency controls.</p><h3>2. Database Transactions</h3><p>A transaction groups multiple database operations into a single logical unit.</p><p>The basic structure is:</p><pre>BEGIN;<br>-- Perform database operations<br>COMMIT;</pre><p>If something goes wrong:</p><pre>ROLLBACK;</pre><h3>Transactions in Node.js</h3><p>When using PostgreSQL with Node.js and the pg library, all operations in a transaction must use the same checked-out database connection.</p><pre>const client = await pool.connect();<br>try {<br>  await client.query(&#39;BEGIN&#39;);<br>  await client.query(<br>    &#39;UPDATE accounts SET balance = balance - $1 WHERE id = $2&#39;,<br>    [2000, 1]<br>  );<br>  await client.query(<br>    &#39;UPDATE accounts SET balance = balance + $1 WHERE id = $2&#39;,<br>    [2000, 2]<br>  );<br>  await client.query(&#39;COMMIT&#39;);<br>} catch (error) {<br>  await client.query(&#39;ROLLBACK&#39;);<br>  throw error;<br>} finally {<br>  client.release();<br></pre><p>A common mistake is using separate pool.query() calls for different statements in the same transaction. They may execute on different connections, which means they won&#39;t belong to the same transaction.</p><h3>Production considerations</h3><p>Transactions should generally be short.</p><p>Avoid performing these operations while holding a transaction open:</p><ul><li>Calling external APIs.</li><li>Sending emails.</li><li>Performing lengthy computations.</li><li>Waiting for user input.</li><li>Running unnecessary queries.</li></ul><p>Long-running transactions hold resources and can increase lock contention.</p><p>Another important scenario is an ambiguous commit outcome: the database may commit successfully, but the application loses the response. The application cannot safely assume the transaction failed. Idempotency and reconciliation mechanisms help handle this situation.</p><h3>3. Database Isolation Levels</h3><p>Isolation levels determine what one transaction can observe while other transactions are executing.</p><p>The four SQL-standard isolation levels are:</p><p>Isolation LevelGeneral behaviorRead UncommittedAllows dirty reads in systems that support themRead CommittedReads committed data at each statementRepeatable ReadMaintains a stable transaction snapshot Serializable Ensures successful transactions behave as if executed serially</p><p>PostgreSQL has some important implementation-specific behavior.</p><h3>Read Committed</h3><p>This is PostgreSQL’s default isolation level.</p><p>Each SQL statement gets a new snapshot of committed data.</p><p>Example:</p><pre>Transaction A:<br>SELECT balance FROM accounts WHERE id = 1;<br>-- Returns 1000<br>Transaction B:<br>UPDATE accounts SET balance = 2000 WHERE id = 1;<br>COMMIT;<br>Transaction A:<br>SELECT balance FROM accounts WHERE id = 1;<br>-- Returns 2000</pre><p>The same query can return different values within one transaction.</p><h3>Repeatable Read</h3><p>PostgreSQL maintains a stable snapshot for the transaction.</p><p>A transaction continues seeing the same committed snapshot, even when other transactions commit new changes.</p><p>PostgreSQL’s Repeatable Read also prevents phantom reads, but it does not prevent every serialization anomaly.</p><h3>Serializable</h3><p>Serializable provides the strongest isolation guarantee.</p><p>PostgreSQL uses Serializable Snapshot Isolation (SSI) to detect dangerous concurrent dependency patterns. It can abort a transaction when necessary to preserve serializable behavior.</p><p>Applications must be prepared to retry transactions that fail with serialization errors.</p><h3>Write Skew Example</h3><p>Imagine two doctors are on duty.</p><p>Business rule: At least one doctor must remain on duty.</p><p>Initially:</p><pre>Doctor A = ON<br>Doctor B = ON</pre><p>Two transactions execute concurrently:</p><pre>Transaction A:<br>Read both doctors.<br>See Doctor B is ON.<br>Set Doctor A = OFF.<br><br>Transaction B:<br>Read both doctors.<br>See Doctor A is ON.<br>Set Doctor B = OFF.</pre><p>Under Repeatable Read, both transactions can commit because they modify different rows.</p><p>The final state becomes:</p><pre>Doctor A = OFF<br>Doctor B = OFF</pre><p>The business invariant is violated.</p><p>Serializable can detect this anomaly and abort one transaction.</p><p><strong>Interview takeaway:</strong> Choose isolation levels based on business correctness requirements, not simply because a stronger isolation level sounds safer.</p><h3>4. Concurrency Anomalies</h3><p>Understanding these anomalies is essential for designing reliable backend systems.</p><p>AnomalyMeaningDirty ReadReading uncommitted changesNon-repeatable ReadReading the same row twice and getting different valuesPhantom ReadRepeating a predicate query and seeing a changed result setLost UpdateOne update overwrites anotherWrite SkewConcurrent transactions jointly violate an invariant</p><p>PostgreSQL prevents dirty reads even when Read Uncommitted is requested; it behaves like Read Committed.</p><p>A useful distinction:</p><ul><li>Non-repeatable reads concern changes to an existing row.</li><li>Phantom reads concern changes to the set of rows matching a predicate.</li><li>Write skew concerns a business invariant across multiple records.</li></ul><h3>5. Optimistic vs Pessimistic Locking</h3><p>These are two common approaches to handling concurrent updates.</p><h3>Optimistic Locking</h3><p>Optimistic locking assumes conflicts are relatively uncommon.</p><p>The application reads a record and its version number.</p><p>When updating, it checks whether the version is still unchanged.</p><pre>UPDATE products<br>SET stock = stock - 1,<br>    version = version + 1<br>WHERE id = 101<br>  AND version = 5;</pre><p>If zero rows are updated, another transaction changed the record first.</p><p>The application can retry or return a conflict response.</p><p>Useful when:</p><ul><li>Conflicts are relatively rare.</li><li>Reads are frequent.</li><li>Locking records for long periods would be expensive.</li></ul><h3>Pessimistic Locking</h3><p>Pessimistic locking assumes conflicts may occur and locks the record before modifying it.</p><pre>BEGIN;<br>SELECT *<br>FROM accounts<br>WHERE id = 101<br>FOR UPDATE;<br>UPDATE accounts<br>SET balance = balance - 500<br>WHERE id = 101;<br>COMMIT;</pre><p>Another transaction attempting a conflicting update must wait.</p><p>Useful for:</p><ul><li>Inventory reservations.</li><li>Wallet operations.</li><li>Booking systems.</li><li>Database-backed job claiming.</li></ul><h3>Atomic Updates: An Important Alternative</h3><p>For simple operations, an atomic conditional SQL statement may be better than reading and then updating.</p><pre>UPDATE accounts<br>SET balance = balance - 500<br>WHERE id = 101<br>  AND balance &gt;= 500<br>RETURNING balance;</pre><p>If no row is returned, the withdrawal did not succeed.</p><p>This reduces the application-level read-modify-write race.</p><h3>6. Row-Level Locks and SELECT FOR UPDATE</h3><p>PostgreSQL supports several row-level lock modes:</p><ul><li>FOR UPDATE</li><li>FOR NO KEY UPDATE</li><li>FOR SHARE</li><li>FOR KEY SHARE</li></ul><p>The most commonly used is:</p><pre>SELECT *<br>FROM jobs<br>WHERE id = 101<br>FOR UPDATE;</pre><p>This locks the selected row against conflicting modifications until the transaction ends.</p><p>A normal SELECT generally does not acquire a row-level lock that blocks concurrent updates.</p><p>Importantly, SELECT FOR UPDATE locks records, not the entire table, although PostgreSQL also acquires appropriate table-level locks.</p><p>Use row-level locking when multiple transactions may attempt to modify the same logical record.</p><h3>7. SKIP LOCKED: Multiple Workers and Job Scheduling</h3><p>This is one of the most practical PostgreSQL features for building database-backed job schedulers.</p><p>Imagine a system with:</p><ul><li>Thousands of scheduled jobs.</li><li>Multiple worker processes.</li><li>Several organizations.</li><li>A requirement that two workers must not concurrently claim the same job.</li></ul><p>A naive implementation might look like this:</p><pre>SELECT *<br>FROM jobs<br>WHERE status = &#39;PENDING&#39;<br>ORDER BY scheduled_at<br>LIMIT 10;</pre><p>The problem is that multiple workers can retrieve the same rows before either updates their status.</p><h3>Solution: FOR UPDATE SKIP LOCKED</h3><pre>BEGIN;<br>WITH selected_jobs AS (<br>    SELECT id<br>    FROM jobs<br>    WHERE status = &#39;PENDING&#39;<br>      AND scheduled_at &lt;= NOW()<br>    ORDER BY scheduled_at, id<br>    LIMIT 10<br>    FOR UPDATE SKIP LOCKED<br>)<br>UPDATE jobs<br>SET status = &#39;PROCESSING&#39;,<br>    started_at = NOW(),<br>    attempts = attempts + 1<br>WHERE id IN (<br>    SELECT id FROM selected_jobs<br>)<br>RETURNING *;<br>COMMIT;</pre><p>How it works:</p><ol><li>Worker A starts a transaction.</li><li>Worker A selects and locks eligible jobs.</li><li>Worker B executes the same query.</li><li>Worker B skips rows locked by Worker A.</li><li>Worker A marks the selected jobs as PROCESSING.</li><li>Both workers commit and execute different jobs.</li></ol><p>The status update is important because row locks disappear when the transaction commits.</p><h3>Does SKIP LOCKED guarantee exactly-once execution?</h3><p>No.</p><p>It prevents competing workers from claiming the same locked rows through this mechanism, but it does not guarantee exactly-once execution.</p><p>Consider:</p><pre>Worker claims job<br>      |<br>      v<br>Job marked PROCESSING<br>      |<br>      v<br>Worker crashes<br>      |<br>      v<br>Job remains PROCESSING</pre><p>A production scheduler needs additional mechanisms:</p><ul><li>Lease expiration.</li><li>Heartbeats.</li><li>Stale-job recovery.</li><li>Retry policies.</li><li>Attempt counters.</li><li>Idempotent job handlers.</li><li>Appropriate ownership or fencing mechanisms for external side effects.</li></ul><p>For multi-tenant fairness, simply ordering by scheduled_at may not be sufficient. One organization with a huge backlog could dominate the workers. Fair scheduling may require tenant-aware quotas, weighted scheduling, or separate claim policies.</p><p><strong>Important distinction:</strong> SKIP LOCKED is a concurrency primitive, not a complete job scheduling architecture.</p><h3>8. Deadlocks</h3><p>A deadlock occurs when transactions wait for each other in a circular dependency.</p><p>Example:</p><pre>Transaction A:<br>Locks Account 1<br>Wants Account 2<br><br>Transaction B:<br>Locks Account 2<br>Wants Account 1</pre><p>Neither can proceed.</p><p>PostgreSQL detects deadlocks and aborts one transaction.</p><h3>How to prevent deadlocks</h3><ol><li>Always acquire locks in a consistent order.</li><li>Keep transactions short.</li><li>Avoid external API calls while holding locks.</li><li>Use appropriate indexes.</li><li>Retry aborted transactions safely.</li></ol><p>For example, always lock account IDs in ascending order.</p><p>Deadlock errors can be identified using SQLSTATE 40P01.</p><h3>9. MVCC: Multi-Version Concurrency Control</h3><p>MVCC is a fundamental part of PostgreSQL’s concurrency model.</p><p>Instead of simply overwriting a row during every update, PostgreSQL maintains different row versions.</p><p>Imagine:</p><pre>Account balance = 1000</pre><p>Transaction A updates the balance:</p><pre>UPDATE accounts<br>SET balance = 2000<br>WHERE id = 1;</pre><p>PostgreSQL creates a new row version.</p><p>Different transactions may see different versions depending on their snapshots.</p><p>This helps readers and writers operate concurrently without requiring every normal read to block writes.</p><h3>Important MVCC concepts</h3><p><strong>xmin:</strong> Transaction ID associated with inserting a tuple version.</p><p><strong>xmax:</strong> Transaction ID associated with deleting or otherwise invalidating a tuple version.</p><p>These values are useful for understanding tuple visibility, but visibility also depends on transaction status and the snapshot.</p><h3>What are dead tuples?</h3><p>When rows are updated or deleted, older row versions may remain physically present.</p><p>Once no active transaction needs those versions, they become eligible for cleanup.</p><p>PostgreSQL uses VACUUM to reclaim space for reuse and maintain visibility information.</p><h3>What is autovacuum?</h3><p>Autovacuum automatically performs maintenance tasks such as vacuuming and analyzing tables.</p><p>Long-running transactions can prevent cleanup of old row versions, contributing to table bloat and transaction ID wraparound concerns.</p><p><strong>Interview takeaway:</strong> MVCC improves concurrency, but it does not eliminate locks, and it makes vacuum maintenance important.</p><h3>Phase 2: Database Indexing</h3><p>Understanding transactions explains how PostgreSQL maintains correctness.</p><p>Indexing explains how PostgreSQL retrieves information efficiently.</p><h3>10. What is a Database Index?</h3><p>An index is a separate data structure that helps the database locate records without scanning the entire table.</p><p>Imagine a URL table containing 10 million records.</p><pre>SELECT *<br>FROM urls<br>WHERE short_code = &#39;abc123&#39;;</pre><p>Without a suitable index, PostgreSQL may perform a sequential scan.</p><p>It checks table rows to find matching records.</p><p>With an index:</p><pre>CREATE UNIQUE INDEX idx_urls_short_code<br>ON urls(short_code);</pre><p>PostgreSQL can use the index to locate the relevant record more efficiently.</p><p>Indexes improve reads, but they introduce costs:</p><ul><li>Additional storage.</li><li>More work during INSERT operations.</li><li>More work during DELETE operations.</li><li>Index maintenance during relevant UPDATE operations.</li></ul><p>Therefore, indexing every column is not a good strategy.</p><h3>11. How B-Tree Indexes Work</h3><p>B-Tree is PostgreSQL’s default index type.</p><p>It is a balanced, page-oriented tree structure.</p><p>A simplified representation:</p><pre>                Root<br>              /      \<br>          Internal  Internal<br>          /   \       /   \<br>        Leaf Leaf   Leaf Leaf</pre><p>Each page contains ordered keys and references to lower-level pages or table tuples.</p><p>To locate a value:</p><ol><li>PostgreSQL starts at the root.</li><li>Navigates through internal pages.</li><li>Reaches the appropriate leaf page.</li><li>Finds matching index entries.</li><li>Uses tuple identifiers to locate table rows when necessary.</li><li>Checks visibility under MVCC.</li></ol><p>B-Trees support:</p><ul><li>Equality searches.</li><li>Range queries.</li><li>Sorting.</li><li>Minimum and maximum lookups.</li></ul><p>The approximate search complexity is logarithmic in the number of indexed entries, although actual performance depends heavily on caching, I/O, selectivity, and the execution plan.</p><h3>12. Different PostgreSQL Index Types</h3><p>Not every index is suitable for every query.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/703/1*8_MxWe_8GBZggu51OHSQIg.png" /></figure><h3>B-Tree</h3><p>Best general-purpose choice.</p><pre>CREATE INDEX idx_users_email<br>ON users(email);</pre><h3>Hash</h3><p>Useful for equality lookups, but does not support range searches or ordering.</p><p>B-Tree is usually the more flexible default.</p><h3>GIN</h3><p>Useful for data containing multiple searchable elements.</p><p>For example, JSONB:</p><pre>CREATE INDEX idx_metadata<br>ON events<br>USING GIN(metadata);</pre><p>Query:</p><pre>SELECT *<br>FROM events<br>WHERE metadata @&gt; &#39;{&quot;type&quot;:&quot;payment&quot;}&#39;;</pre><p>GIN is commonly used for JSONB containment, arrays, and full-text search.</p><h3>GiST</h3><p>A generalized search tree used for specialized data types and operators.</p><p>Common examples include geospatial searches through PostGIS and range-related queries.</p><h3>BRIN</h3><p>BRIN stores summaries of values across physical block ranges.</p><p>It is particularly useful for very large tables where the physical order of records correlates with the indexed value.</p><p>For example, a time-series table where records are mostly inserted chronologically.</p><p>BRIN indexes are small but lossy, so PostgreSQL may need to recheck matching rows.</p><h3>13. Single-Column Indexes</h3><p>A single-column index covers one column.</p><pre>CREATE INDEX idx_orders_user_id<br>ON orders(user_id);</pre><p>Useful for:</p><pre>SELECT *<br>FROM orders<br>WHERE user_id = 101;</pre><p>Index selection should be based on actual query patterns, not assumptions.</p><h3>14. Composite Indexes</h3><p>A composite index covers multiple columns.</p><pre>CREATE INDEX idx_orders_user_status<br>ON orders(user_id, status);</pre><p>It is useful for:</p><pre>SELECT *<br>FROM orders<br>WHERE user_id = 101<br>  AND status = &#39;PAID&#39;;</pre><h3>Leftmost Prefix Principle</h3><p>A B-Tree composite index is ordered lexicographically.</p><p>For:</p><pre>(user_id, status, created_at)</pre><p>The leading user_id column is important for navigating the index.</p><p>Queries filtering on user_id, or on user_id plus status, can use the leading index structure effectively.</p><p>A query filtering only on status generally cannot use the index as efficiently as one using its leading column.</p><p>Some PostgreSQL versions can use B-tree skip scans in certain circumstances, but this is cost-dependent and should not replace good index design.</p><h3>Column Ordering</h3><p>Consider:</p><pre>SELECT *<br>FROM orders<br>WHERE user_id = 101<br>  AND created_at &gt;= &#39;2026-01-01&#39;<br>ORDER BY created_at DESC;</pre><p>A useful index is:</p><pre>CREATE INDEX idx_orders_user_created<br>ON orders(user_id, created_at DESC);</pre><p>A common heuristic is to put equality-filtered columns before range-filtered columns, but the final choice must match the actual workload and query plan.</p><p>PostgreSQL can also combine multiple indexes using bitmap operations, so composite indexes are not always automatically better than separate indexes.</p><h3>15. Unique Indexes</h3><p>Unique indexes enforce uniqueness.</p><pre>CREATE UNIQUE INDEX idx_users_email<br>ON users(email);</pre><p>They are useful for:</p><ul><li>Email addresses.</li><li>Short codes.</li><li>Idempotency keys.</li><li>External identifiers.</li></ul><p>A primary key automatically creates a unique B-Tree index.</p><p>A UNIQUE constraint also creates a unique index.</p><p>One PostgreSQL detail: ordinary unique indexes allow multiple NULL values because NULLs are considered distinct by default. UNIQUE NULLS NOT DISTINCT can change that behavior.</p><h3>16. Partial Indexes</h3><p>A partial index indexes only rows satisfying a condition.</p><p>Consider a job scheduler where most completed jobs do not need to be scanned when workers claim jobs.</p><pre>CREATE INDEX idx_pending_jobs<br>ON jobs(scheduled_at)<br>WHERE status = &#39;PENDING&#39;;</pre><p>This index contains only pending jobs.</p><p>Benefits:</p><ul><li>Smaller index.</li><li>Less unnecessary index maintenance.</li><li>Faster relevant lookups in suitable workloads.</li></ul><p>Partial indexes are particularly useful for:</p><ul><li>Pending jobs.</li><li>Active users.</li><li>Unpaid orders.</li><li>Unprocessed events.</li></ul><p>The query predicate must imply the partial-index predicate for PostgreSQL to use the index.</p><p>Index predicates also need immutable expressions. For example, using NOW() directly in a partial-index predicate is not allowed because it is not immutable.</p><h3>17. Covering Indexes and INCLUDE</h3><p>A covering index contains all the columns required by a query.</p><pre>CREATE INDEX idx_orders_user_covering<br>ON orders(user_id)<br>INCLUDE(status);</pre><p>The user_id column is an index key.</p><p>The status column is stored as a non-key included value.</p><p>This can help PostgreSQL perform an Index Only Scan.</p><p>However, an Index Only Scan does not always mean zero heap access. PostgreSQL uses the visibility map to determine whether heap visibility checks can be skipped. If the relevant pages are not marked all-visible, heap fetches may still happen.</p><p>Do not include every selected column automatically. Larger indexes increase storage and write costs.</p><h3>18. PostgreSQL Scan Types</h3><p>You should recognize these in execution plans.</p><h3>Sequential Scan</h3><p>Reads table pages directly.</p><p>Useful when:</p><ul><li>The table is small.</li><li>A large portion of the table is required.</li><li>An index would involve too many random heap accesses.</li></ul><h3>Index Scan</h3><p>Uses an index to find matching tuple identifiers and then visits the heap.</p><p>Useful for selective queries.</p><h3>Index Only Scan</h3><p>Returns required values from the index when visibility information allows it.</p><h3>Bitmap Index Scan and Bitmap Heap Scan</h3><p>PostgreSQL builds a bitmap of matching tuple locations and then visits relevant heap pages.</p><p>It can combine multiple indexes using BitmapAnd or BitmapOr.</p><p><strong>Important:</strong> Seeing a Sequential Scan does not automatically mean the query is poorly optimized. The planner chooses the estimated cheapest plan.</p><h3>19. Common Indexing Mistakes</h3><h3>Applying functions to indexed columns</h3><p>This query may not use a normal index on email efficiently:</p><pre>SELECT *<br>FROM users<br>WHERE LOWER(email) = &#39;test@example.com&#39;;</pre><p>An expression index can help:</p><pre>CREATE INDEX idx_users_lower_email<br>ON users(LOWER(email));</pre><h3>Leading wildcard searches</h3><p>A normal B-Tree is not suitable for:</p><pre>WHERE name LIKE &#39;%ashish%&#39;</pre><p>PostgreSQL’s pg_trgm extension can help with substring and similarity searches using GIN or GiST indexes.</p><h3>Filtering timestamps using DATE()</h3><p>Instead of:</p><pre>WHERE DATE(created_at) = &#39;2026-11-02&#39;;</pre><p>Prefer a range:</p><pre>WHERE created_at &gt;= &#39;2026-11-02 00:00:00&#39;<br>  AND created_at &lt;  &#39;2026-11-03 00:00:00&#39;;</pre><p>The range approach is generally more index-friendly when there is a suitable index on created_at.</p><h3>Too many indexes</h3><p>Every index adds maintenance cost.</p><p>Review index usage and query patterns before creating or removing indexes. A low index scan count alone does not prove an index is unnecessary; statistics may have been reset, or the index may serve occasional but important workloads.</p><h3>20. EXPLAIN and EXPLAIN ANALYZE</h3><p>One of the most important skills for a backend engineer is understanding why a query is slow.</p><p>Use:</p><pre>EXPLAIN<br>SELECT *<br>FROM urls<br>WHERE short_code = &#39;abc123&#39;;</pre><p>This displays the planned execution strategy.</p><p>For actual execution statistics:</p><pre>EXPLAIN (ANALYZE, BUFFERS)<br>SELECT *<br>FROM urls<br>WHERE short_code = &#39;abc123&#39;;</pre><p>Important fields:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/721/1*hQJMXhCus208O1RLQREZww.png" /></figure><p>Compare estimated rows with actual rows.</p><p>Large differences can indicate:</p><ul><li>Stale statistics.</li><li>Data skew.</li><li>Correlation between columns.</li><li>Planner estimation problems.</li></ul><p>Run:</p><pre>ANALYZE urls;</pre><p>Or:</p><pre>VACUUM ANALYZE urls;</pre><p>The latter also performs vacuum maintenance.</p><h3>pg_stat_statements</h3><p>This PostgreSQL extension helps identify expensive queries across the workload.</p><pre>CREATE EXTENSION IF NOT EXISTS pg_stat_statements;</pre><p>Example:</p><pre>SELECT<br>    query,<br>    calls,<br>    total_exec_time,<br>    mean_exec_time,<br>    rows<br>FROM pg_stat_statements<br>ORDER BY total_exec_time DESC<br>LIMIT 10;</pre><p>This is useful for identifying queries that consume significant database time.</p><h3>N+1 Query Problem</h3><p>Imagine fetching 100 users and then fetching each user’s orders separately.</p><pre>1 query: Fetch users<br>100 queries: Fetch orders for each user<br><br>Total = 101 queries</pre><p>Instead, use a JOIN or batch query.</p><pre>SELECT *<br>FROM orders<br>WHERE user_id = ANY($1);</pre><p>This reduces unnecessary database round trips.</p><p>In the next part, I will be sharing information about performance optimization and scaling the Architecture efficiently.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=861678c72b8b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Load Balancers Explained: L4 vs L7 and How Traffic Actually Gets Distributed]]></title>
            <link>https://ashishksahoo.medium.com/load-balancers-explained-l4-vs-l7-and-how-traffic-actually-gets-distributed-569fd832679d?source=rss-95f47ff57945------2</link>
            <guid isPermaLink="false">https://medium.com/p/569fd832679d</guid>
            <category><![CDATA[design-systems]]></category>
            <category><![CDATA[backend-development]]></category>
            <category><![CDATA[load-balancing]]></category>
            <category><![CDATA[networking]]></category>
            <dc:creator><![CDATA[Ashish Kumar Sahoo]]></dc:creator>
            <pubDate>Tue, 29 Sep 2026 17:30:35 GMT</pubDate>
            <atom:updated>2026-09-29T17:41:05.476Z</atom:updated>
            <content:encoded><![CDATA[<p>While learning networking and backend architecture, I came across a component that sits quietly in the middle of almost every scalable system:</p><p><strong>The Load Balancer.</strong></p><p>At first, I thought a load balancer simply meant:</p><blockquote><em>“Send requests to multiple servers.”</em></blockquote><p>That’s true — but incomplete.</p><p>The interesting part is <strong>how it decides which server should receive each request</strong>, and why there are different types of load balancers.</p><p>My notes helped me connect the concept through two important categories:</p><ul><li><strong>Layer 4 Load Balancer</strong></li><li><strong>Layer 7 Load Balancer</strong></li></ul><p>And then there are different algorithms that determine how traffic gets distributed.</p><h3>Why Do We Need a Load Balancer?</h3><p>Imagine we have a single application server:</p><pre>┌─────────────┐<br>Users ──────→│   Server    │<br>             └─────────────┘</pre><p>Initially, this might work perfectly.</p><p>But as traffic increases:</p><pre>100 users<br>   ↓<br>1,000 users<br>   ↓<br>10,000 users<br>   ↓<br>1,00,000 users</pre><p>One server eventually becomes a bottleneck.</p><p>So we add more servers:</p><pre>┌── Server 1<br>                 │<br>Users ───────────┼── Server 2<br>                 │<br>                 └── Server 3</pre><p>But now another question appears:</p><blockquote><strong><em>Who decides which server receives each incoming connection or request?</em></strong></blockquote><p>That’s the job of the <strong>load balancer</strong>.</p><h3>What Does a Load Balancer Actually Do?</h3><p>A load balancer acts as an intermediary between clients and backend servers.</p><p>Instead of users directly connecting to individual servers:</p><pre>Client → Server 1<br>Client → Server 2<br>Client → Server 3</pre><p>they connect to a common entry point:</p><pre>┌── Server 1<br>                  │<br>Client → Load Balancer ── Server 2<br>                  │<br>                  └── Server 3</pre><p>The load balancer receives incoming traffic and selects an appropriate backend.</p><p>The goal isn’t necessarily to make every server receive exactly the same number of requests.</p><p>The goal is to <strong>distribute traffic according to the selected balancing strategy and the system’s requirements</strong>.</p><h3>The Two Important Types</h3><p>When people talk about load balancers by OSI layer, two common categories are:</p><pre>Layer 4 → Network Load Balancer<br>Layer 7 → Application Load Balancer</pre><p>The fundamental difference is <strong>what information the load balancer uses to make routing decisions.</strong></p><h3>1. Layer 4 Load Balancer — Network Level</h3><p>Layer 4 operates at the <strong>transport layer</strong>.</p><p>It primarily works with information such as:</p><pre>Source IP<br>Destination IP<br>Source Port<br>Destination Port<br>Protocol<br>Connection information</pre><p>For example:</p><pre>Client<br>10.0.0.5:52341<br>      ↓<br>Load Balancer<br>      ↓<br>10.0.2.10:443</pre><p>The L4 load balancer doesn’t need to understand the actual HTTP request.</p><p>It can make its decision without inspecting application-level details such as:</p><pre>GET /users<br>POST /payments<br>/api/orders</pre><h3>Example</h3><p>Suppose we have:</p><pre>┌── Server A<br>                │<br>Client → L4 LB ─┼── Server B<br>                │<br>                └── Server C</pre><p>The load balancer can establish or forward the connection to one of these servers based on its configured algorithm.</p><h3>When is L4 useful?</h3><p>L4 load balancing is useful when you want:</p><ul><li>High-performance connection-level distribution</li><li>Protocol-agnostic TCP/UDP balancing</li><li>Low overhead</li><li>Applications where the load balancer doesn’t need HTTP awareness</li></ul><p>The important mental model:</p><blockquote><strong><em>L4 cares primarily about connections and transport/network information, not HTTP semantics.</em></strong></blockquote><h3>2. Layer 7 Load Balancer — Application Level</h3><p>Layer 7 operates at the <strong>application layer</strong>.</p><p>Now the load balancer can understand application-level information such as:</p><pre>HTTP method<br>URL/path<br>Host<br>Headers<br>Cookies<br>Other application-layer attributes</pre><p>For example:</p><pre>GET /users</pre><p>could be routed differently from:</p><pre>GET /products</pre><p>We could design a system like:</p><pre>┌── User Service<br>                         │<br>Client → L7 Load Balancer ── Product Service<br>                         │<br>                         └── Order Service</pre><p>Or:</p><pre>example.com/api/users<br>        ↓<br>     User Server<br><br>example.com/api/orders<br>        ↓<br>     Order Server</pre><p>This gives L7 load balancing much more context about the request.</p><h3>The mental model</h3><blockquote><strong><em>L4 asks: “Which connection should handle this?”</em></strong></blockquote><blockquote><strong><em>L7 can ask: “What is this HTTP request, and where should this request go?”</em></strong></blockquote><h3>L4 vs L7</h3><p>The difference becomes much easier to remember this way:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_LJR0e9Rjtd_ZI1Wp3Ph9w.png" /></figure><p>This doesn’t mean L7 is “better” than L4.</p><p>They solve different problems.</p><h3>How Does the Load Balancer Choose a Server?</h3><p>This is where things get interesting.</p><p>Having three servers doesn’t automatically tell the load balancer which one to choose.</p><p>It needs a <strong>load-balancing algorithm</strong>.</p><p>There are several common approaches.</p><h3>1. Round Robin</h3><p>This is probably the simplest approach.</p><p>Suppose we have:</p><pre>Server A<br>Server B<br>Server C</pre><p>Requests are distributed in sequence:</p><pre>Request 1 → A<br>Request 2 → B<br>Request 3 → C<br>Request 4 → A<br>Request 5 → B<br>Request 6 → C</pre><p>So the pattern looks like:</p><pre>A → B → C → A → B → C</pre><p>It’s simple and predictable.</p><h3>The problem?</h3><p>It assumes the servers can handle roughly similar workloads.</p><p>Imagine:</p><pre>Server A → powerful<br>Server B → medium<br>Server C → weak</pre><p>Sending the same number of requests to all three may not be ideal.</p><p>That’s where weighted algorithms come in.</p><h3>2. Weighted Round Robin</h3><p>Here, each server receives a <strong>weight</strong>.</p><p>For example:</p><pre>Server A → Weight 5<br>Server B → Weight 3<br>Server C → Weight 2</pre><p>The load balancer can distribute traffic approximately according to those weights.</p><p>Conceptually:</p><pre>A → A → A → A → A<br>B → B → B<br>C → C</pre><p>The exact scheduling behavior depends on the implementation.</p><p>The idea is simple:</p><blockquote><strong><em>More capable servers can receive a larger share of traffic.</em></strong></blockquote><p>The weight might be based on factors such as:</p><ul><li>Capacity</li><li>CPU</li><li>Memory</li><li>Instance size</li><li>Expected workload</li></ul><p>Although in production, weights are typically configured rather than automatically derived from current CPU/memory unless the load-balancing system explicitly supports dynamic weighting.</p><h3>3. Least Connections</h3><p>Instead of asking:</p><blockquote><em>“Which server comes next?”</em></blockquote><p>the load balancer asks:</p><blockquote><strong><em>“Which healthy server currently has the fewest active connections?”</em></strong></blockquote><p>Imagine:</p><pre>Server A → 20 connections<br>Server B → 12 connections<br>Server C → 35 connections</pre><p>A new connection may be sent to:</p><pre>Server B</pre><p>because it currently has the fewest connections.</p><p>This can be useful when connections have significantly different lifetimes.</p><p>For example:</p><pre>Server A<br>████████████████ 20 connections</pre><pre>Server B<br>████████ 8 connections</pre><pre>Server C<br>████████████████████ 25 connections</pre><p>A new connection would naturally be directed toward Server B.</p><h3>4. Weighted Least Connections</h3><p>Now combine the two ideas.</p><p>We consider:</p><pre>Number of connections<br>+<br>Server capacity/weight</pre><p>For example:</p><pre>Server A → Weight 10<br>Server B → Weight 5</pre><p>A powerful server can reasonably handle more connections than a smaller server.</p><p>So the load balancer doesn’t simply ask:</p><blockquote><em>“Who has the fewest connections?”</em></blockquote><p>It considers the server’s configured capacity as well.</p><p>This can make distribution more appropriate when backend servers have different capacities.</p><h3><strong>5. Least Response / Least Response Time</strong></h3><p>The basic idea is:</p><blockquote><strong><em>Send the new request to the healthy server that is currently responding fastest.</em></strong></blockquote><p>For example:</p><p>ServerCurrent response timeServer A120 msServer B45 msServer C80 ms</p><p>A <strong>least-response-time</strong> strategy would prefer:</p><pre>New Request<br>     ↓<br>Load Balancer<br>     ↓<br>Server B<br>     ↑<br>45 ms — fastest response</pre><p>The exact implementation varies. A load balancer may consider <strong>measured latency</strong>, <strong>response time</strong>, <strong>active connections</strong>, or a combination of these factors.</p><h3>Least Connections vs Least Response</h3><p>This distinction is important:</p><p><strong>Least Connections</strong></p><pre>A → 20 connections<br>B → 8 connections<br>C → 15 connections<br>New request → B</pre><p>It asks:</p><blockquote><strong><em>Which server has the fewest active connections?</em></strong></blockquote><p><strong>Least Response Time</strong></p><pre>A → 120 ms<br>B → 45 ms<br>C → 80 ms<br>New request → B</pre><p>It asks:</p><blockquote><strong><em>Which server is responding fastest?</em></strong></blockquote><h3>6. IP Hash</h3><p>Another approach is to use the client’s IP address as an input to a hashing function.</p><p>Conceptually:</p><pre>Client IP<br>   ↓<br>Hash function<br>   ↓<br>Server selection</pre><p>For example:</p><pre>Client A → Hash → Server 1<br>Client B → Hash → Server 3<br>Client C → Hash → Server 2</pre><p>The advantage is that the same client IP can tend to map to the same backend, assuming the server pool and hashing behavior remain stable.</p><p>This can be useful when some degree of <strong>session affinity</strong> is desired.</p><p>However, relying on client IP for affinity has limitations, especially when many users share the same public IP through NAT.</p><h3>7. Consistent Hashing</h3><p>This takes the hashing idea further.</p><p>A normal hash-based approach can cause a large number of mappings to change when servers are added or removed.</p><p>Consistent hashing is designed to minimize how much existing key-to-server mapping changes when the server set changes.</p><p>Imagine:</p><pre>Server A<br>           ↓<br>     ───────────────<br>    /       |        \<br>Server B   Client    Server C</pre><p>The actual implementation is more sophisticated, but the important idea is:</p><blockquote><strong><em>Keep existing assignments relatively stable even when the backend pool changes.</em></strong></blockquote><p>This is particularly useful in distributed systems and caching architectures.</p><h3>8. Power of Two Choices</h3><p>Another interesting strategy is:</p><blockquote><em>Randomly choose two servers and send the request to the less-loaded one.</em></blockquote><p>For example:</p><pre>Servers:<br>A → 20 connections<br>B → 8 connections<br>C → 15 connections<br>D → 5 connections</pre><p>Suppose the algorithm randomly selects:</p><pre>B and D</pre><p>Since D has fewer connections:</p><pre>Request → D</pre><p>Instead of checking every server, we only compare two candidates.</p><p>This simple idea can produce surprisingly effective load distribution in many systems.</p><h3>Health Checks Matter Too</h3><p>A load balancer shouldn’t blindly send traffic to every server.</p><p>Imagine:</p><pre>Server A → Healthy<br>Server B → Healthy<br>Server C → DOWN</pre><p>If Server C is still receiving requests:</p><pre>Client → Load Balancer → Server C<br>                         ❌</pre><p>we have a problem.</p><p>So load balancers commonly use <strong>health checks</strong>.</p><p>For an HTTP service, a health check might call:</p><pre>GET /health</pre><p>and expect a healthy response.</p><p>Conceptually:</p><pre>Load Balancer<br>              /     |     \<br>             ↓      ↓      ↓<br>           A ✓     B ✓     C ✗</pre><p>The load balancer can then stop sending new traffic to an unhealthy backend according to its configuration.</p><h3>What Happens When a Request Arrives?</h3><p>Let’s put everything together.</p><p>Imagine three backend servers:</p><pre>Server A<br>Server B<br>Server C</pre><p>A client sends a request:</p><pre>Client<br>   │<br>   │ Request<br>   ▼<br>Load Balancer</pre><p>The load balancer can then:</p><h3>Step 1 — Receive traffic</h3><pre>Client → Load Balancer</pre><h3>Step 2 — Determine the available backend pool</h3><pre>A ✓<br>B ✓<br>C ✗</pre><h3>Step 3 — Apply the configured algorithm</h3><p>For example:</p><pre>Least Connections</pre><h3>Step 4 — Select the backend</h3><pre>Server B</pre><h3>Step 5 — Forward the traffic</h3><pre>Client<br>   ↓<br>Load Balancer<br>   ↓<br>Server B</pre><h3>Step 6 — Return the response</h3><pre>Server B<br>   ↓<br>Load Balancer<br>   ↓<br>Client</pre><p>And the process repeats for incoming traffic.</p><h3>A Realistic Architecture</h3><p>A production architecture might look something like:</p><pre>Internet<br>                       │<br>                       ▼<br>                    Client<br>                       │<br>                       ▼<br>              ┌─────────────────┐<br>              │  Load Balancer  │<br>              └────────┬────────┘<br>                       │<br>             ┌─────────┼─────────┐<br>             ▼         ▼         ▼<br>          Server A  Server B  Server C<br>             │         │         │<br>             └─────────┼─────────┘<br>                       ▼<br>                    Database</pre><p>And the load balancer may be responsible for:</p><pre>✓ Traffic distribution<br>✓ Health checks<br>✓ Connection handling<br>✓ Routing<br>✓ Failover behavior<br>✓ TLS termination (depending on architecture)</pre><p>An L7 load balancer can additionally make routing decisions based on HTTP-level information.</p><h3>One Important Distinction</h3><p>Something I had to correct in my own understanding:</p><p><strong>L4/L7 are types of load balancing based on where the decision is made.</strong></p><p>But:</p><p><strong>Round Robin, Weighted Round Robin, Least Connections, Weighted Least Connections, IP Hash and Consistent Hashing are algorithms/strategies for selecting backends.</strong></p><p>So these aren’t competing categories.</p><p>You could conceptually have:</p><pre>L4 Load Balancer<br>      +<br>Load-balancing algorithm</pre><p>or:</p><pre>L7 Load Balancer<br>      +<br>Load-balancing algorithm</pre><p>The exact algorithms available depend on the implementation.</p><h3>My Mental Model</h3><p>I now think about a load balancer using three questions:</p><h3>1. What can it see?</h3><pre>L4 → Network/transport information<br>L7 → Application-level information</pre><h3>2. Which servers are healthy?</h3><pre>A ✓<br>B ✓<br>C ✗</pre><h3>3. Which healthy server should receive the traffic?</h3><pre>Round Robin<br>Weighted Round Robin<br>Least Connections<br>Weighted Least Connections<br>Hash-based strategies<br>Power of Two Choices</pre><p>That’s essentially the core idea.</p><h3>Final Thought</h3><p>A load balancer isn’t just a “traffic distributor.”</p><p>It’s a <strong>decision-making layer between clients and backend infrastructure</strong>.</p><p>When traffic arrives, it has to answer:</p><blockquote><strong><em>Can this server handle the traffic?</em></strong></blockquote><blockquote><strong><em>Is this server healthy?</em></strong></blockquote><blockquote><strong><em>Which backend should receive this connection/request?</em></strong></blockquote><blockquote><strong><em>Should routing depend on connection-level or application-level information?</em></strong></blockquote><p>And that’s why understanding load balancing is important before moving deeper into:</p><p><strong>System Design → Distributed Systems → Microservices → Cloud Architecture.</strong></p><p>The more servers we add, the more important the question becomes:</p><blockquote><strong><em>How do we make all those servers behave like one reliable service from the client’s perspective?</em></strong></blockquote><p>That’s the problem a load balancer helps us solve.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=569fd832679d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[20 Networking Concepts Every Backend Developer Must Learn]]></title>
            <link>https://ashishksahoo.medium.com/20-networking-concepts-every-backend-developer-must-learn-c6ddb958bb2c?source=rss-95f47ff57945------2</link>
            <guid isPermaLink="false">https://medium.com/p/c6ddb958bb2c</guid>
            <category><![CDATA[networking]]></category>
            <category><![CDATA[computer-networking]]></category>
            <category><![CDATA[backend-development]]></category>
            <category><![CDATA[system-design-concepts]]></category>
            <dc:creator><![CDATA[Ashish Kumar Sahoo]]></dc:creator>
            <pubDate>Tue, 29 Sep 2026 17:17:47 GMT</pubDate>
            <atom:updated>2026-09-29T17:17:47.851Z</atom:updated>
            <content:encoded><![CDATA[<p>When I started learning backend development, I realized something pretty quickly:</p><p><strong>You can write an API without really understanding what happens to the request after you hit “Send.”</strong></p><p>I knew things like HTTP, TCP, DNS, IP addresses, routers, ports, etc. But I knew them mostly as individual definitions.</p><p>So I started writing them down and, more importantly, connecting them.</p><p>The interesting part is that these aren’t 20 unrelated networking concepts.</p><p>They are pieces of the same journey:</p><pre>Client<br>  ↓<br>Network<br>  ↓<br>Router<br>  ↓<br>Internet<br>  ↓<br>Server<br>  ↓<br>Application</pre><p>Here are the 20 concepts I currently use as my networking mental model.</p><h3>1. Client–Server Model</h3><p>Almost everything starts with two sides:</p><pre>Client  ─────────→  Server<br>        Request</pre><pre>Client  ←─────────  Server<br>        Response</pre><p>The <strong>client</strong> initiates communication, while the <strong>server</strong> provides a service or resource.</p><p>For example:</p><pre>Browser → Web Server<br>Mobile App → API Server<br>Backend → Database</pre><p>This sounds simple, but understanding this relationship makes concepts like HTTP, WebSockets, proxies and load balancers much easier.</p><h3>2. OSI Model</h3><p>The OSI model gives us a conceptual way to understand how network communication is organized.</p><pre>7. Application<br>6. Presentation<br>5. Session<br>4. Transport<br>3. Network<br>2. Data Link<br>1. Physical</pre><p>I don’t think the goal should be to memorize these seven layers just for interviews.</p><p>The useful part is understanding <strong>responsibilities</strong>.</p><p>For example:</p><pre>HTTP       → Application<br>TCP        → Transport<br>IP         → Network<br>Ethernet   → Data Link</pre><p>The Internet’s actual protocol architecture doesn’t map perfectly onto the OSI model, but the model remains useful for reasoning about networking problems.</p><h3>3. Packets</h3><p>Applications don’t generally send one giant block of data across the Internet.</p><p>Data is processed and encapsulated as it moves through the networking stack.</p><p>A simplified view is:</p><pre>Application Data<br>       ↓<br>TCP Segment<br>       ↓<br>IP Packet<br>       ↓<br>Network Frame<br>       ↓<br>Bits</pre><p>Different layers add their own headers containing information needed for delivery.</p><p>This is one of the reasons networking can be modular.</p><h3>4. IP Address</h3><p>An IP address provides network-layer addressing.</p><p>For IPv4:</p><pre>192.168.1.10</pre><p>IPv4 addresses are <strong>32 bits</strong>.</p><p>IPv6 addresses are <strong>128 bits</strong>.</p><p>The important distinction for me is:</p><blockquote><em>An IP address helps identify where network-layer traffic should be delivered.</em></blockquote><p>For example:</p><pre>Client IP<br>    ↓<br>Router<br>    ↓<br>Destination IP</pre><p>But an IP address alone doesn’t tell us which application should receive the traffic.</p><p>That’s where ports come in.</p><h3>5. Routers</h3><p>A router connects different networks and forwards IP packets toward their destination.</p><p>A simplified path might look like:</p><pre>Laptop<br>   ↓<br>Home Router<br>   ↓<br>ISP Router<br>   ↓<br>Internet Routers<br>   ↓<br>Destination Network<br>   ↓<br>Server</pre><p>A router examines the destination information and its routing information to determine where to forward the packet next.</p><p>So my mental model is:</p><blockquote><strong><em>IP identifies the destination; routers help move the packet toward it.</em></strong></blockquote><h3>6. DNS — Domain Name System</h3><p>Humans prefer:</p><pre>google.com</pre><p>Machines communicate using network addresses such as IP addresses.</p><p>DNS provides the naming system that connects domain names to information such as IP addresses.</p><p>A simplified lookup might look like:</p><pre>Browser<br>   ↓<br>DNS Cache<br>   ↓<br>Recursive Resolver<br>   ↓<br>DNS hierarchy<br>   ↓<br>Authoritative DNS<br>   ↓<br>IP Address</pre><p>Caching means a resolver may already know the answer, so a complete lookup through every level isn’t required every time.</p><p>Without DNS, we’d have to remember IP addresses instead of domain names.</p><h3>7. Ports</h3><p>Suppose a server has one IP address:</p><pre>93.x.x.x</pre><p>But that machine is running:</p><pre>Web Server<br>SSH<br>Database<br>Other Services</pre><p>How does network traffic reach the appropriate service?</p><p>Ports help identify transport-layer endpoints.</p><p>For example:</p><pre>93.x.x.x:443</pre><p>Here:</p><pre>93.x.x.x → IP address<br>443      → Port</pre><p>Common conventions include:</p><pre>HTTP  → 80<br>HTTPS → 443<br>SSH   → 22</pre><p>A port doesn’t inherently guarantee which application is listening there; these numbers are conventions that services commonly use.</p><h3>8. NAT — Network Address Translation</h3><p>Your home network might contain:</p><pre>Laptop → 192.168.1.10<br>Phone  → 192.168.1.11<br>TV     → 192.168.1.12</pre><p>But your router may have only one public IPv4 address.</p><p>NAT allows the router to translate traffic between private and public addressing.</p><p>A simplified example:</p><pre>Laptop<br>192.168.1.10:5000<br>       ↓<br>     Router<br>       ↓<br>Public-IP:62001<br>       ↓<br>    Internet</pre><p>The router maintains translation state so returning traffic can be associated with the correct internal connection.</p><p>This is one reason multiple devices can share a public IPv4 address.</p><h3>9. Subnet</h3><p>A subnet divides a larger IP network into smaller logical networks.</p><p>Consider:</p><pre>192.168.1.0/24</pre><p>The /24 is CIDR notation.</p><p>For IPv4, that means:</p><pre>24 bits → network prefix<br>8 bits  → remaining address space</pre><p>Subnetting becomes especially important in:</p><ul><li>Enterprise networks</li><li>Cloud infrastructure</li><li>VPCs</li><li>Routing</li><li>Security boundaries</li></ul><p>Instead of thinking about one huge network, we can create smaller logical networks.</p><h3>10. DHCP</h3><p>So how does your laptop get an IP address when you connect to Wi-Fi?</p><p>You usually don’t manually configure everything.</p><p>That’s where <strong>DHCP — Dynamic Host Configuration Protocol</strong> — comes in.</p><p>A simplified DHCP exchange is:</p><pre>Client<br>  ↓ DHCP Discover<br>Server<br>  ↓ DHCP Offer<br>Client<br>  ↓ DHCP Request<br>Server<br>  ↓ DHCP ACK<br>Client</pre><p>DHCP can provide configuration such as:</p><pre>IP address<br>Subnet information<br>Default gateway<br>DNS server<br>Lease information</pre><p>So when your device joins a network, DHCP can automatically provide the information it needs.</p><h3>11. MAC Address</h3><p>IP addresses operate at the network layer.</p><p>But on a local network, devices also communicate using link-layer addressing.</p><p>For Ethernet, this commonly involves a <strong>MAC address</strong>.</p><p>Example:</p><pre>AA:BB:CC:DD:EE:FF</pre><p>A useful distinction is:</p><pre>IP address<br>→ Network-layer addressing</pre><pre>MAC address<br>→ Link-layer addressing</pre><p>So when communicating locally, both addressing concepts can become relevant.</p><h3>12. ARP — Address Resolution Protocol</h3><p>Now imagine my laptop knows:</p><pre>Gateway = 192.168.1.1</pre><p>But it needs the corresponding MAC address to send a local Ethernet frame.</p><p>For IPv4, ARP can solve this.</p><p>The machine can effectively ask:</p><pre>&quot;Who has 192.168.1.1?&quot;</pre><p>The device owning that IP responds with its MAC address.</p><p>Conceptually:</p><pre>Laptop<br>  │<br>  │ Who has 192.168.1.1?<br>  ↓<br>Router<br>  │<br>  │ 192.168.1.1 = AA:BB:CC:DD:EE:FF<br>  ↓<br>Laptop</pre><p>IPv6 uses Neighbor Discovery rather than ARP.</p><h3>13. TCP — Transmission Control Protocol</h3><p>TCP provides a reliable, ordered byte-stream abstraction between endpoints.</p><p>Before application data is exchanged, TCP commonly establishes a connection using the three-way handshake:</p><pre>Client                 Server</pre><pre>SYN  ─────────────────→</pre><pre>     ←──────────── SYN-ACK</pre><pre>ACK  ─────────────────→</pre><p>TCP then provides mechanisms such as:</p><ul><li>Sequencing</li><li>Acknowledgments</li><li>Retransmission</li><li>Flow control</li><li>Congestion control</li></ul><p>That’s why TCP is commonly used when reliable, ordered delivery is important.</p><p>For example:</p><pre>Web applications<br>File transfers<br>Email<br>Database connections</pre><h3>14. UDP — User Datagram Protocol</h3><p>UDP takes a much lighter approach.</p><p>It provides datagram transport without TCP’s connection establishment and reliability mechanisms.</p><p>It doesn’t guarantee:</p><pre>Delivery<br>Ordering<br>Retransmission</pre><p>This makes UDP useful when applications prefer low overhead or need to implement their own transport behavior.</p><p>Examples can include:</p><pre>Real-time communication<br>Online games<br>Streaming-related workloads<br>DNS queries</pre><p>The important thing isn’t:</p><blockquote><em>TCP is good and UDP is bad.</em></blockquote><p>It’s:</p><blockquote><strong><em>Different applications have different communication requirements.</em></strong></blockquote><h3>15. HTTP / HTTPS</h3><p>HTTP is the application-layer protocol used for communication between clients and servers on the Web.</p><p>A request can look conceptually like:</p><pre>GET /users HTTP/1.1<br>Host: example.com</pre><p>And the server may respond:</p><pre>HTTP/1.1 200 OK</pre><pre>{<br>  &quot;users&quot;: [...]<br>}</pre><p>Common HTTP methods include:</p><pre>GET<br>POST<br>PUT<br>PATCH<br>DELETE</pre><p>HTTP provides concepts such as:</p><ul><li>Methods</li><li>Headers</li><li>Status codes</li><li>Request/response semantics</li><li>Message content</li></ul><p>But plain HTTP doesn’t provide encryption.</p><p>That’s where HTTPS comes in.</p><h3>16. TLS — Transport Layer Security</h3><p>HTTPS can be thought of as:</p><pre>HTTP<br> +<br>TLS</pre><p>TLS provides cryptographic protection for communication.</p><p>It is designed to provide:</p><pre>Confidentiality<br>Integrity<br>Authentication</pre><p>During a TLS handshake, the client and server negotiate cryptographic parameters and establish keys for protecting the subsequent communication.</p><p>The server also presents a certificate that can be used as part of authenticating its identity.</p><p>So when I visit:</p><pre>https://example.com</pre><p>I’m not just using HTTP.</p><p>I’m using HTTP over a TLS-protected connection.</p><h3>17. Firewall</h3><p>A firewall controls network traffic according to configured security policies.</p><p>Rules can consider information such as:</p><pre>Source IP<br>Destination IP<br>Port<br>Protocol<br>Connection state</pre><p>For example:</p><pre>Allow → TCP 443<br>Block → unwanted traffic</pre><p>In a production architecture, firewalls can exist at multiple levels.</p><p>They aren’t necessarily just a single physical box sitting between a server and the Internet.</p><h3>18. VPN — Virtual Private Network</h3><p>A VPN can create a protected tunnel between a client and a VPN endpoint.</p><p>A simplified view:</p><pre>Client<br>   ↓<br>Encrypted Tunnel<br>   ↓<br>VPN Server<br>   ↓<br>Private Network / Internet</pre><p>VPNs are commonly used for:</p><ul><li>Remote access</li><li>Connecting private networks</li><li>Secure communication across untrusted networks</li></ul><p>But a VPN doesn’t magically make everything secure.</p><p>It protects traffic according to the VPN protocol and configuration. The security of the destination systems and applications still matters.</p><h3>19. Proxy &amp; Reverse Proxy</h3><p>These two are easy to confuse.</p><h3>Forward Proxy</h3><p>The proxy represents the <strong>client</strong>.</p><pre>Client<br>   ↓<br>Forward Proxy<br>   ↓<br>Internet<br>   ↓<br>Server</pre><h3>Reverse Proxy</h3><p>The proxy represents the <strong>server side</strong>.</p><pre>Client<br>   ↓<br>Reverse Proxy<br>   ↓<br>Backend Server</pre><p>A reverse proxy can handle responsibilities such as:</p><ul><li>Request routing</li><li>TLS termination</li><li>Caching</li><li>Access control</li><li>Hiding backend topology</li></ul><p>Tools such as Nginx are commonly used for reverse-proxy workloads.</p><h3>20. Load Balancer</h3><p>Now imagine an application receives millions of requests.</p><p>We probably don’t want:</p><pre>┌── Server 1<br>                 │<br>Client → Server<br>                 │<br>                 └── Server 2</pre><p>Instead, we can introduce a load balancer:</p><pre>┌── Server 1<br>                 │<br>Client → Load Balancer ── Server 2<br>                 │<br>                 └── Server 3</pre><p>The load balancer distributes incoming traffic among backend instances according to its configured algorithm and health information.</p><p>This allows us to build systems that can scale horizontally.</p><h3>Putting Everything Together</h3><p>This is where these concepts became much easier for me.</p><p>Imagine I type:</p><pre>https://example.com</pre><p>into my browser.</p><p>A simplified journey could look like:</p><pre>Browser<br>                    │<br>                    ▼<br>                   DNS<br>                    │<br>                    ▼<br>                IP Address<br>                    │<br>                    ▼<br>                 Port 443<br>                    │<br>                    ▼<br>              TCP Connection<br>                    │<br>                    ▼<br>                   TLS<br>                    │<br>                    ▼<br>                  HTTP<br>                    │<br>                    ▼<br>              Home Router<br>                    │<br>                    ▼<br>                   NAT<br>                    │<br>                    ▼<br>                Internet<br>                    │<br>                    ▼<br>                 Firewall<br>                    │<br>                    ▼<br>              Load Balancer<br>                    │<br>                    ▼<br>             Reverse Proxy<br>                    │<br>                    ▼<br>             Application Server<br>                    │<br>                    ▼<br>                Database</pre><p>And underneath the local-network communication, concepts such as:</p><pre>DHCP<br>ARP<br>MAC addresses<br>Subnetting</pre><p>are helping the devices communicate correctly.</p><h3>My Networking Mental Model</h3><p>Instead of memorizing 20 definitions, I now try to remember the <strong>questions each concept answers</strong>.</p><p><strong>OSI Model</strong></p><blockquote><em>What responsibilities exist at different networking layers?</em></blockquote><p><strong>Packet</strong></p><blockquote><em>How is data encapsulated for network transmission?</em></blockquote><p><strong>IP</strong></p><blockquote><em>Where should this network-layer traffic go?</em></blockquote><p><strong>Router</strong></p><blockquote><em>Which path should the packet take next?</em></blockquote><p><strong>DNS</strong></p><blockquote><em>What address/information corresponds to this domain name?</em></blockquote><p><strong>Port</strong></p><blockquote><em>Which transport-layer endpoint should receive this traffic?</em></blockquote><p><strong>NAT</strong></p><blockquote><em>How should private/public addressing be translated?</em></blockquote><p><strong>Subnet</strong></p><blockquote><em>Which logical network does this address belong to?</em></blockquote><p><strong>DHCP</strong></p><blockquote><em>How does my device automatically get network configuration?</em></blockquote><p><strong>MAC</strong></p><blockquote><em>What link-layer address is used for local delivery?</em></blockquote><p><strong>ARP</strong></p><blockquote><em>What MAC address corresponds to this local IPv4 address?</em></blockquote><p><strong>TCP</strong></p><blockquote><em>How do I get reliable, ordered byte-stream communication?</em></blockquote><p><strong>UDP</strong></p><blockquote><em>How do I send lightweight datagrams without TCP’s reliability machinery?</em></blockquote><p><strong>HTTP</strong></p><blockquote><em>What does the client want from the server?</em></blockquote><p><strong>TLS</strong></p><blockquote><em>How do we authenticate and cryptographically protect the connection?</em></blockquote><p><strong>Firewall</strong></p><blockquote><em>Should this traffic be allowed?</em></blockquote><p><strong>VPN</strong></p><blockquote><em>How can I create a protected tunnel between network endpoints?</em></blockquote><p><strong>Proxy</strong></p><blockquote><em>Can an intermediary act on behalf of the client?</em></blockquote><p><strong>Reverse Proxy</strong></p><blockquote><em>Can an intermediary receive requests before they reach my backend?</em></blockquote><p><strong>Load Balancer</strong></p><blockquote><em>Which backend should handle this request?</em></blockquote><h3>Final Thought</h3><p>The biggest shift in my understanding was realizing that networking isn’t really about memorizing protocols.</p><p>It’s about following the <strong>journey of data</strong>.</p><p>When I type a URL, I can now ask:</p><pre>How did my device get an IP?</pre><pre>How did the domain become an IP address?</pre><pre>How did my packet find its next hop?</pre><pre>How did it cross the Internet?</pre><pre>How did the server know which service should receive it?</pre><pre>How was the connection established?</pre><pre>How was it secured?</pre><pre>How did the request reach the correct backend?</pre><pre>How did the response come back?</pre><p>Once those questions start making sense, networking becomes much less abstract.</p><p>And as a backend developer, that’s the part I’m finding most valuable:</p><blockquote><strong><em>Don’t learn networking as 20 separate interview questions. Learn it as one journey that your request takes through the system.</em></strong></blockquote><p>That mental model makes everything from <strong>REST APIs to microservices, cloud networking, reverse proxies, databases, WebSockets and system design</strong> significantly easier to reason about.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c6ddb958bb2c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Real-Time Communication in Backend Systems: Long Polling, SSE, WebSockets & Webhooks]]></title>
            <link>https://ashishksahoo.medium.com/real-time-communication-in-backend-systems-long-polling-sse-websockets-webhooks-bfec92a8a512?source=rss-95f47ff57945------2</link>
            <guid isPermaLink="false">https://medium.com/p/bfec92a8a512</guid>
            <category><![CDATA[real-time-communication]]></category>
            <category><![CDATA[system-design-concepts]]></category>
            <category><![CDATA[backend-development]]></category>
            <category><![CDATA[websocket]]></category>
            <dc:creator><![CDATA[Ashish Kumar Sahoo]]></dc:creator>
            <pubDate>Sun, 27 Sep 2026 11:00:41 GMT</pubDate>
            <atom:updated>2026-09-27T11:00:41.207Z</atom:updated>
            <content:encoded><![CDATA[<p>While learning backend development, I came across a group of concepts that initially looked almost identical:</p><p><strong>Long Polling, Server-Sent Events, WebSockets, and Webhooks.</strong></p><p>All of them involve some form of communication beyond the traditional:</p><pre>Client → Request → Server<br>Client ← Response ← Server</pre><p>But they solve <strong>different problems</strong>.</p><p>The easiest way to understand them is not by memorizing definitions, but by asking:</p><blockquote><strong><em>Who needs to communicate with whom, and how often?</em></strong></blockquote><p>Here’s how I now understand them.</p><h3>1. Long Polling — “Tell me when something happens”</h3><p>The simplest approach is <strong>long polling</strong>.</p><p>Instead of the client repeatedly asking:</p><pre>&quot;Anything new?&quot;<br>&quot;Anything new?&quot;<br>&quot;Anything new?&quot;</pre><p>the client sends a request and the server keeps it open for a while.</p><pre>Client ────────────────→ Server<br>[waiting...]<br>Client ←──── New Data ── Server</pre><p>Once the server has something useful to return, it responds.</p><p>The client then immediately makes another request.</p><h3>Example</h3><p>Imagine a notification system.</p><p>Instead of polling every second:</p><pre>Request → Response<br>Request → Response<br>Request → Response</pre><p>the client can make one request and wait:</p><pre>Request<br>   ↓<br>Server waits<br>   ↓<br>New notification arrives<br>   ↓<br>Response<br>   ↓<br>Client makes another request</pre><h3>Where can it be useful?</h3><ul><li>Notifications</li><li>Simple chat systems</li><li>Job/status updates</li><li>Systems where real-time requirements aren’t extremely strict</li></ul><h3>The downside</h3><p>The connection is still based on normal HTTP request/response semantics.</p><p>For a large number of clients, holding many requests open can create additional server, connection, proxy, and load-balancer overhead.</p><p>So while long polling is relatively simple, it isn’t always the best solution for high-frequency real-time communication.</p><h3>2. Server-Sent Events — “Keep listening”</h3><p><strong>Server-Sent Events (SSE)</strong> takes the idea further.</p><p>With SSE, the browser establishes an HTTP connection and the server can continuously send events over that connection.</p><p>The important characteristic is:</p><blockquote><strong><em>SSE is primarily one-way: Server → Client.</em></strong></blockquote><pre>Client<br>   │<br>   │  HTTP connection<br>   ▼<br>Server<br>   │<br>   ├──── Event 1 ────→ Client<br>   ├──── Event 2 ────→ Client<br>   ├──── Event 3 ────→ Client<br>   └──── Event 4 ────→ Client</pre><p>The client doesn’t need to repeatedly request every update.</p><h3>Example: Live dashboard</h3><p>Imagine a monitoring dashboard showing:</p><pre>CPU: 62%<br>Memory: 71%<br>Requests/sec: 1,240</pre><p>The server can continuously push updates:</p><pre>CPU → 64%<br>CPU → 61%<br>CPU → 59%</pre><p>without requiring a new HTTP request for every update.</p><h3>Other use cases</h3><p>SSE works particularly well for:</p><ul><li>Notifications</li><li>Live feeds</li><li>Progress updates</li><li>Monitoring dashboards</li><li>Streaming server-generated updates</li><li>AI-generated text streaming</li></ul><p>One major advantage is its simplicity when communication is naturally <strong>server → browser</strong>.</p><p>If the client also needs frequent bidirectional communication, WebSockets may be a better fit.</p><h3>3. WebSockets — “Let’s keep the conversation open”</h3><p>This is where things become more interesting.</p><p>WebSockets provide a <strong>persistent, bidirectional communication channel</strong>.</p><p>Unlike SSE, both sides can send messages whenever needed.</p><pre>Client  ←──────────────→  Server<br>        bidirectional<br>        communication</pre><p>A WebSocket connection commonly begins with an HTTP-based handshake/upgrade, after which communication uses WebSocket frames rather than ordinary HTTP request/response exchanges.</p><p>Conceptually:</p><pre>HTTP connection<br>      ↓<br>Upgrade<br>      ↓<br>WebSocket connection<br>      ↓<br>Persistent communication</pre><p>Now either side can send data:</p><pre>Client ─── message ───→ Server<br>Client ←── event ────── Server<br>Client ─── message ───→ Server<br>Client ←── update ───── Server</pre><h3>Why is this useful?</h3><p>Consider a multiplayer game.</p><p>The client needs to continuously send:</p><pre>Player moved<br>Player attacked<br>Player changed direction</pre><p>while the server needs to send:</p><pre>Enemy moved<br>Player took damage<br>Game state changed</pre><p>Waiting for a new HTTP request every time would be inefficient and cumbersome.</p><p>WebSockets provide a persistent channel for this type of interaction.</p><h3>Common use cases</h3><ul><li>Chat applications</li><li>Multiplayer games</li><li>Collaborative applications</li><li>Real-time dashboards</li><li>Trading interfaces</li><li>Live interactions</li></ul><p>The key mental model I use is:</p><blockquote><strong><em>SSE = server pushes to client.</em></strong><em><br></em><strong><em>WebSocket = both client and server can continuously communicate.</em></strong></blockquote><h3>4. Webhooks — “Don’t keep asking me. I’ll call you.”</h3><p>Webhooks are different from the previous three.</p><p>Here we’re generally talking about <strong>server-to-server communication</strong>.</p><p>Suppose I build an application that uses a payment provider.</p><p>I initiate a payment:</p><pre>My Backend<br>     ↓<br>Payment Provider</pre><p>But the payment may not complete immediately.</p><p>Instead of continuously asking:</p><pre>&quot;Is the payment successful?&quot;<br>&quot;Is it successful now?&quot;<br>&quot;Now?&quot;<br>&quot;Now?&quot;</pre><p>the payment provider can send an HTTP request to my backend when the event occurs.</p><pre>Payment Provider<br>       │<br>       │ POST /webhook<br>       ▼<br>My Backend</pre><p>For example:</p><pre>{<br>  &quot;event&quot;: &quot;payment.completed&quot;,<br>  &quot;payment_id&quot;: &quot;12345&quot;<br>}</pre><p>My backend receives the event and updates its database.</p><p>This is the fundamental idea behind webhooks:</p><blockquote><strong><em>One system notifies another system when an event happens.</em></strong></blockquote><h3>But Webhooks Need More Engineering Than Just an Endpoint</h3><p>This was one of the important things I realized while studying them.</p><p>A webhook endpoint shouldn’t simply do:</p><pre>receive request<br>      ↓<br>trust request<br>      ↓<br>update database</pre><p>There are several things to consider.</p><h3>1. Verify authenticity</h3><p>The external provider should generally sign the webhook payload, and your application should verify the signature using the provider’s documented mechanism.</p><p>Otherwise, anyone could potentially send:</p><pre>POST /webhook<br><br>payment.completed</pre><p>to your endpoint.</p><h3>2. Handle duplicate events</h3><p>Webhook providers may retry delivery if they don’t receive a successful response.</p><p>That means your system may receive:</p><pre>payment.completed<br>payment.completed<br>payment.completed</pre><p>The application should therefore be designed to handle duplicate deliveries safely.</p><p>This is where <strong>idempotency</strong> becomes important.</p><p>For example:</p><pre>event_id = abc123</pre><p>Before processing:</p><pre>Has abc123 already been processed?<br>        │<br>     ┌──┴──┐<br>    Yes    No<br>     │      │<br>   Ignore  Process</pre><h3>3. Don’t perform everything inside the webhook request</h3><p>A good architecture might look like:</p><pre>External Provider<br>       │<br>       ▼<br>Webhook API<br>       │<br>       ├── Verify signature<br>       ├── Validate payload<br>       └── Store event<br>              │<br>              ▼<br>            Queue<br>              │<br>              ▼<br>        Background Worker<br>              │<br>              ▼<br>          Database</pre><p>This makes the webhook endpoint faster and gives the application more control over retries and failures.</p><h3>So Which One Should I Use?</h3><p>This is the question I found more useful than memorizing definitions.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9NvytqNWVXFBib02_iaPLA.png" /></figure><p>A simple decision tree is:</p><pre>Need external system to notify your backend?<br>                │<br>               YES<br>                ↓<br>             Webhook<br><br>Need server → browser updates?<br>                │<br>               YES<br>                ↓<br>               SSE<br><br>Need continuous two-way communication?<br>                │<br>               YES<br>                ↓<br>           WebSocket<br><br>Need something simpler and occasional?<br>                │<br>               YES<br>                ↓<br>          Long Polling<br></pre><p>Of course, real systems can combine multiple approaches.</p><p>For example, a modern application could use:</p><pre>Payment Provider<br>      ↓<br>   Webhook<br>      ↓<br>   Backend<br>      ↓<br>    Queue<br>      ↓<br>Database update<br>      ↓<br>     SSE<br>      ↓<br>   Browser</pre><p>Now a payment event from an external system can eventually become a real-time update in the user’s browser.</p><h3>The Bigger Lesson</h3><p>The most important thing I took away from these concepts is that <strong>“real-time communication” isn’t one technology.</strong></p><p>Different communication patterns solve different problems.</p><h3>Long Polling</h3><blockquote><em>“Ask me, and I’ll keep your request open until I have something.”</em></blockquote><h3>SSE</h3><blockquote><em>“Keep this connection open; I’ll send you updates.”</em></blockquote><h3>WebSocket</h3><blockquote><em>“Let’s keep a two-way communication channel open.”</em></blockquote><h3>Webhook</h3><blockquote><em>“You don’t need to keep asking me. I’ll notify your server when something happens.”</em></blockquote><p>Once started thinking in terms of <strong>communication direction, connection lifetime, and event ownership</strong>, the differences became much easier to understand.</p><p>And that’s probably the bigger lesson in backend engineering:</p><blockquote><strong><em>Don’t choose a technology because it’s called “real-time.” Choose the communication pattern that actually matches the problem.</em></strong></blockquote><p>That distinction becomes especially important when moving from small projects to production systems, where connection management, retries, idempotency, authentication, scaling, failure handling, and observability start becoming just as important as the protocol itself.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bfec92a8a512" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The Ultimate AWS Beginner’s Guide: From Concepts to Reality]]></title>
            <link>https://ashishksahoo.medium.com/the-ultimate-aws-beginners-guide-from-concepts-to-reality-6a101dcaca15?source=rss-95f47ff57945------2</link>
            <guid isPermaLink="false">https://medium.com/p/6a101dcaca15</guid>
            <category><![CDATA[aws-rds]]></category>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[amazon-web-services]]></category>
            <category><![CDATA[aws-ec2]]></category>
            <category><![CDATA[cloud-services]]></category>
            <dc:creator><![CDATA[Ashish Kumar Sahoo]]></dc:creator>
            <pubDate>Wed, 15 Jul 2026 08:45:29 GMT</pubDate>
            <atom:updated>2026-07-15T08:45:29.649Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2Fpn5JbzuscXS4z7lboBow.png" /><figcaption>aws with restaurent analogy</figcaption></figure><p>This guide is split into two parts to help you master Amazon Web Services (AWS):</p><ul><li><strong>Part 1: The Restaurant Analogy</strong> (A high-level, intuitive story to understand how all the pieces connect).</li><li><strong>Part 2: The Core Concepts Technical Reference</strong> (A highly structured breakdown of each service, complete with code examples, troubleshooting, and architectural alternatives).</li><li><strong>Part 3: Debugging &amp; Identifying Problems</strong> (A master cheat sheet for tracking down errors when your app crashes using CloudWatch, CloudTrail, and VPC Flow Logs).</li></ul><h3>Part 1: Demystifying AWS (The Restaurant Analogy)</h3><p>If you’ve ever looked at an AWS architecture diagram, you were probably overwhelmed by the alphabet soup of acronyms: EC2, RDS, VPC, ALB, IGW, NAT. It looks like a complex military operation.</p><p>But building a scalable, secure app on AWS is exactly like designing and running a massive, high-end restaurant. Let’s open our doors.</p><h3>1. The Building &amp; The Zones: VPC, Public, and Private Subnets</h3><p>Before you can hire chefs or seat customers, you need a building. In AWS, your building is your <strong>VPC (Virtual Private Cloud)</strong>. It is your isolated, private slice of the cloud.</p><p>Inside your building, you set up specific zones (Subnets). You don’t want customers walking directly into the kitchen, right?</p><ul><li><strong>The Public Subnet (The Dining Area):</strong> The front of the house. It is accessible from the outside street. Customers can walk in and interact with the staff.</li><li><strong>The Private Subnet (The Kitchen):</strong> The back of the house. Customers are strictly forbidden. Only the internal staff can go back and forth to communicate with the kitchen.</li></ul><h3>2. The Front Doors: Internet Gateway (IGW)</h3><p>You have a beautiful dining area, but currently, it’s completely walled off. To let customers (internet traffic) inside your restaurant, you must install front doors. In AWS, the <strong>Internet Gateway (IGW)</strong> acts as these main doors. Without it, your VPC is completely isolated.</p><h3>3. The Bouncer: API Gateway</h3><p>Your restaurant is getting popular, but some people are trying to sneak in without a reservation, and others are aggressively ordering 100 drinks a minute. You need a Bouncer: the <strong>API Gateway</strong>. It stands at the front of your application, checks IDs (Authentication), and ensures nobody orders too fast (Rate Limiting).</p><h3>4. The Host (Maitre D’): Application Load Balancer (ALB)</h3><p>Once past the bouncer, customers meet the Host. You have 10 waiters working. If the Host sends every customer to Waiter #1, that waiter will crash. The <strong>Application Load Balancer (ALB)</strong> is your perfect Host. It looks at all incoming web traffic and distributes it evenly across all your available servers.</p><h3>5. The Chefs and Waiters: Amazon EC2</h3><p>Now we meet the actual workers: <strong>Amazon EC2 (Elastic Compute Cloud)</strong>. These are your virtual computers. You rent them, choose their operating system, and they do the heavy lifting — running your backend code, serving webpages, and processing logic.</p><h3>6. The Secure Delivery Door: NAT Gateway</h3><p>Your Chefs are safely isolated in the Kitchen (Private Subnet). But they need to order fresh ingredients from external suppliers on the internet (like downloading a software update). You install a <strong>NAT Gateway</strong> in the Dining Area (Public Subnet). Think of this as a secure mail slot. The Chefs can push a request out through the slot, and ingredients are passed back in. But random people on the street cannot initiate a connection through this slot.</p><h3>7. The Master Ledger: Amazon RDS</h3><p>Finally, every restaurant needs a ledger to keep track of tabs and recipes. This is your Database. Instead of giving a Chef a notebook that could catch fire, you use <strong>Amazon RDS</strong>. This is like hiring a Premium Accounting Firm that sits in a secure vault. They organize the data, automatically photocopy the ledger every night (Backups), and secretly maintain an identical backup vault in the next town over in case of a disaster (Multi-AZ).</p><h3>Visualizing the Complete AWS Restaurant Flow</h3><p>Here is how all these pieces connect together to form a highly secure, scalable architecture:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/468/1*BuuR5Qwwfz7kGSnvULagsw.png" /></figure><h3>Part 2: Core Concepts Technical Reference</h3><h3>1. Amazon EC2 (Elastic Compute Cloud)</h3><p><strong>What is it?</strong> A virtual computer in the cloud. You choose the OS, memory, and CPU power.</p><p><strong>Code Example (Connecting a Frontend App to EC2):</strong></p><pre>// A simple React frontend calling an API hosted on an EC2 instance<br>async function fetchFromEC2() {<br>  try {<br>    // Calling the EC2 Public IP address (or ALB domain)<br>    const response = await fetch(&#39;http://54.123.45.67:3000/api/users&#39;);<br>    const data = await response.json();<br>    console.log(data);<br>  } catch (error) {<br>    console.error(&quot;EC2 Connection Failed:&quot;, error);<br>  }<br>}</pre><p><strong>Why should someone use it?</strong> You have absolute, ultimate control over the environment. You can install any software, run long background video processing tasks, and tweak the OS kernel if needed.</p><p><strong>If not used, what will be the problem?</strong> Without EC2 (or an equivalent compute service), you cannot run your backend application logic in the cloud. You would have to buy and maintain physical servers in your own house.</p><p><strong>Possible Alternatives:</strong></p><ul><li><strong>PaaS (Vercel, Render):</strong> Much easier, but very expensive at scale and limits background tasks.</li><li><strong>AWS Fargate (Containers):</strong> Serverless Docker containers. No OS to manage.</li><li><strong>AWS Lambda:</strong> Serverless functions. You just upload code, and AWS runs it on demand.</li></ul><p><strong>Common Problems &amp; How to Tackle them:</strong></p><ul><li><strong>Problem:</strong> Single Point of Failure.</li><li><strong>How to tackle:</strong> Put your EC2 instances inside an <strong>Auto Scaling Group (ASG)</strong> spanning multiple data centers.</li><li><strong>If not tackled, what it will cost (Impact):</strong> When the EC2 instance inevitably crashes, your entire application goes offline, costing you customers and revenue until you manually reboot it.</li></ul><h3>2. Amazon RDS (Relational Database Service)</h3><p><strong>What is it?</strong> A fully managed relational database (PostgreSQL, MySQL, SQL Server).</p><p><strong>Code Example (Connecting to RDS in Node.js):</strong></p><pre>const { Client } = require(&#39;pg&#39;);<br><br>const client = new Client({<br>  host: &#39;my-database.cwxyz.us-east-1.rds.amazonaws.com&#39;, // RDS Endpoint<br>  port: 5432,<br>  user: &#39;postgres&#39;,<br>  password: &#39;securePassword123&#39;,<br>  database: &#39;myapp_production&#39;,<br>});<br><br>await client.connect();<br>const result = await client.query(&#39;SELECT * FROM users&#39;);</pre><p><strong>Why should someone use it?</strong> It automates the hardest parts of database management: nightly backups, security patches, and instant failovers (Multi-AZ) if a server burns down.</p><p><strong>If not used, what will be the problem?</strong> You would have to manually install a database on an EC2 instance. You would be responsible for writing backup scripts, managing storage disks, and trying to recover data manually if the server crashes.</p><p><strong>Possible Alternatives:</strong></p><ul><li><strong>DBaaS (Supabase, PlanetScale):</strong> Even easier to set up, perfect for modern web apps.</li><li><strong>Amazon Aurora:</strong> AWS’s premium, ultra-fast version of RDS.</li><li><strong>Amazon DynamoDB:</strong> A NoSQL database that scales infinitely but uses documents instead of tables.</li></ul><p><strong>Common Problems &amp; How to Tackle them:</strong></p><ul><li><strong>Problem:</strong> The database runs out of memory because too many users are connected.</li><li><strong>How to tackle:</strong> Implement an <strong>AWS RDS Proxy</strong> to manage and pool connections efficiently.</li><li><strong>If not tackled, what it will cost (Impact):</strong> The database will freeze under heavy traffic, taking down your entire app during your busiest (and most profitable) moments.</li></ul><h3>3. Public and Private Subnets (VPC)</h3><p><strong>What is it?</strong> Network zones within your Virtual Private Cloud. Public Subnets touch the internet; Private Subnets do not.</p><p><strong>Code Example (Infrastructure as Code — Terraform):</strong></p><pre># This creates a highly secure Private Subnet<br>resource &quot;aws_subnet&quot; &quot;private_kitchen&quot; {<br>  vpc_id     = aws_vpc.main.id<br>  cidr_block = &quot;10.0.1.0/24&quot;<br>  map_public_ip_on_launch = false # This makes it private!<br>  <br>  tags = { Name = &quot;Private-Backend-Subnet&quot; }<br>}</pre><p><strong>Why should someone use it?</strong> For impenetrable network security. It physically isolates your most sensitive assets from the public internet.</p><p><strong>If not used, what will be the problem?</strong> If you put your database in a Public Subnet, anyone in the world can run port scanners against it and try to brute-force your passwords.</p><p><strong>Possible Alternatives:</strong></p><ul><li><strong>Fully Serverless (Lambda + DynamoDB):</strong> AWS handles the VPC and subnets completely invisibly in the background.</li></ul><p><strong>Common Problems &amp; How to Tackle them:</strong></p><ul><li><strong>Problem:</strong> Developers put their backend API in the Private Subnet, but forget to configure a Load Balancer in the Public Subnet to route traffic to it.</li><li><strong>How to tackle:</strong> Architect properly: User -&gt; Public ALB -&gt; Private EC2.</li><li><strong>If not tackled, what it will cost (Impact):</strong> A catastrophic data breach. Hackers can steal your entire user database, leading to massive lawsuits and a destroyed reputation.</li></ul><h3>4. NAT Gateway (Network Address Translation)</h3><p><strong>What is it?</strong> A service that allows your private servers to securely download from the internet without letting the internet initiate a connection inwards.</p><p><strong>Code Example (How a private EC2 uses it):</strong> No application code is needed! Once the NAT Gateway is configured in the AWS Console, the EC2 instance just runs commands normally:</p><pre># Running this on a Private EC2 instance works perfectly because of the NAT Gateway<br>curl https://api.stripe.com/v1/charges<br>sudo apt-get update</pre><p><strong>Why should someone use it?</strong> To allow your highly secure Private Subnet servers to fetch OS updates, download GitHub code, or talk to external APIs like Stripe/SendGrid.</p><p><strong>If not used, what will be the problem?</strong> Your private servers will be completely blind to the outside world. They will not be able to process payments, send emails via APIs, or download critical security patches.</p><p><strong>Possible Alternatives:</strong></p><ul><li><strong>VPC Endpoints (AWS PrivateLink):</strong> Used if you only need to talk to other <em>AWS</em> services (like S3). It bypasses the internet entirely.</li><li><strong>The “Everything Public” Approach:</strong> Move the server to a public subnet (cheaper, but risky).</li></ul><p><strong>Common Problems &amp; How to Tackle them:</strong></p><ul><li><strong>Problem:</strong> NAT Gateways charge per Gigabyte of data processed. They get very expensive very fast.</li><li><strong>How to tackle:</strong> Use VPC Endpoints for heavy AWS-internal traffic (like downloading huge files from S3).</li><li><strong>If not tackled, what it will cost (Impact):</strong> The “NAT Tax” will blindside you, potentially adding hundreds or thousands of unexpected dollars to your monthly AWS bill.</li></ul><h3>5. Internet Gateway (IGW)</h3><p><strong>What is it?</strong> The front door of your VPC that connects it to the World Wide Web.</p><p><strong>Code Example (Connecting a VPC to the IGW via Terraform):</strong></p><pre>resource &quot;aws_internet_gateway&quot; &quot;main_doors&quot; {<br>  vpc_id = aws_vpc.main.id<br>}<br># A Route Table is needed to point traffic to the IGW<br>resource &quot;aws_route&quot; &quot;internet_access&quot; {<br>  route_table_id         = aws_vpc.main.main_route_table_id<br>  destination_cidr_block = &quot;0.0.0.0/0&quot; # The whole internet<br>  gateway_id             = aws_internet_gateway.main_doors.id<br>}</pre><p><strong>Why should someone use it?</strong> It is literally the only way for your AWS network to communicate with customers on the internet.</p><p><strong>If not used, what will be the problem?</strong> Your app will be a ghost town. No one outside of your own AWS account will be able to access your website.</p><p><strong>Possible Alternatives:</strong></p><ul><li><strong>AWS Direct Connect:</strong> A physical fiber-optic cable connecting an enterprise office directly to AWS, bypassing the public internet entirely.</li></ul><p><strong>Common Problems &amp; How to Tackle them:</strong></p><ul><li><strong>Problem:</strong> Misconfiguring route tables and accidentally routing a Private Subnet straight to the IGW, making it public.</li><li><strong>How to tackle:</strong> Strictly audit your Route Tables and use Infrastructure as Code (like Terraform) to prevent manual click-errors.</li><li><strong>If not tackled, what it will cost (Impact):</strong> You accidentally expose your private databases to the internet, resulting in a data breach.</li></ul><h3>6. ALB (Application Load Balancer)</h3><p><strong>What is it?</strong> A traffic cop that sits in front of your EC2 instances, decrypts HTTPS traffic, and distributes it evenly.</p><p><strong>Code Example (ALB conceptually routing traffic):</strong> The ALB does this automatically, but your frontend calls the ALB’s domain name, not the EC2 IP:</p><pre>// The Frontend NEVER knows the EC2 IPs. It only knows the ALB.<br>const response = await fetch(&#39;https://api.my-awesome-app.com/users&#39;);</pre><p><strong>Why should someone use it?</strong> For high availability and scale. It ensures no single server gets overwhelmed, and if a server dies, the ALB instantly stops sending traffic to it.</p><p><strong>If not used, what will be the problem?</strong> All user traffic would hit a single EC2 instance. When traffic spikes, that server will crash.</p><p><strong>Possible Alternatives:</strong></p><ul><li><strong>Nginx / HAProxy:</strong> You can manually install and configure your own load balancer on a public EC2 instance (much harder to maintain).</li><li><strong>Network Load Balancer (NLB):</strong> Used for ultra-low latency, non-HTTP traffic (like multiplayer gaming protocols).</li></ul><p><strong>Common Problems &amp; How to Tackle them:</strong></p><ul><li><strong>Problem:</strong> The ALB requires your app to be “stateless.” If a user logs in on Server A, and the ALB routes them to Server B, they get logged out.</li><li><strong>How to tackle:</strong> Store user session data in a central database (RDS) or an in-memory cache (Redis) instead of on the server’s hard drive.</li><li><strong>If not tackled, what it will cost (Impact):</strong> Users will randomly get logged out or lose shopping cart items on every click, resulting in abandoned carts and lost revenue.</li></ul><h3>7. API Gateway</h3><p><strong>What is it?</strong> A managed service that acts as a “Bouncer” for your backend APIs, handling authentication, throttling, and routing.</p><p><strong>Code Example (Protecting an API with API Gateway):</strong></p><pre>// Frontend calling the API Gateway, passing a required API Key<br>async function callSecureAPI() {<br>  const response = await fetch(&#39;https://xyz123.execute-api.us-east-1.amazonaws.com/prod/data&#39;, {<br>    headers: {<br>      &#39;x-api-key&#39;: &#39;your-secure-api-key-here&#39;<br>    }<br>  });<br>}</pre><p><strong>Why should someone use it?</strong> Instead of writing complex code in your Node.js backend to check API keys and throttle abusive users, you let AWS handle it at the edge of the network before it even touches your servers.</p><p><strong>If not used, what will be the problem?</strong> Malicious users or bots can spam your backend API with millions of requests, overwhelming your EC2 servers and racking up massive compute bills (a DDoS attack).</p><p><strong>Possible Alternatives:</strong></p><ul><li><strong>ALB (Application Load Balancer):</strong> Often used instead of API Gateway for standard web apps, as it is cheaper for pure traffic routing if you don’t need advanced API throttling.</li></ul><p><strong>Common Problems &amp; How to Tackle them:</strong></p><ul><li><strong>Problem:</strong> API Gateway has an unchangeable hard timeout limit of 29 seconds. If your backend takes 30 seconds to run a report, the connection dies.</li><li><strong>How to tackle:</strong> Design your API asynchronously. The API Gateway should immediately return a 202 Accepted with a Job ID, and the client checks back later for the result.</li><li><strong>If not tackled, what it will cost (Impact):</strong> Users attempting to run complex reports or uploads will constantly receive 504 Gateway Timeout errors, making your application feel broken and unusable.</li></ul><h3>Part 3: How to Debug and Identify Problems in AWS</h3><p>When your app breaks (e.g., a user gets a 500 error or the site won’t load), the hardest part of cloud computing is figuring out <em>where</em> in the restaurant the problem occurred. Did the Bouncer reject them? Did the Chef burn the food? Did the Accountant lose the ledger?</p><p>AWS provides specific tools to track down the exact problem. Here is the ultimate debugging cheat sheet:</p><h3>1. Amazon CloudWatch (The Master Dashboard)</h3><p>CloudWatch is the central nervous system of AWS. It acts as the security cameras and alarms for your restaurant.</p><ul><li><strong>Metrics:</strong> It tracks CPU usage on EC2, connection counts on RDS, and error rates on your Load Balancers.</li><li><strong>Logs:</strong> You can install the “CloudWatch Agent” on your EC2 servers to automatically stream your backend application logs (like Node.js or Python console.log statements) into a searchable dashboard.</li><li><strong>Alarms:</strong> If CPU hits 90%, CloudWatch can automatically text your phone or trigger an Auto Scaling Group to add more servers.</li></ul><h3>2. AWS CloudTrail (The Audit Log)</h3><p>While CloudWatch monitors the <em>application</em>, CloudTrail monitors the <em>developers</em>.</p><ul><li><strong>How to use it:</strong> If a database suddenly disappears or a server crashes because someone changed a firewall rule, CloudTrail tells you exactly <strong>“Who did what, and at what time.”</strong> It logs every single API call made in your AWS account.</li></ul><h3>3. VPC Flow Logs (The Network Detective)</h3><p>If your app is timing out and you suspect a network issue (e.g., the EC2 instance can’t talk to the RDS database, or the internet can’t reach the EC2 instance), use VPC Flow Logs.</p><ul><li><strong>How to use it:</strong> It records every single packet of data trying to enter or leave your subnets. If you look at the logs and see REJECTED, you immediately know your Security Group (Firewall) rules are misconfigured.</li></ul><h3>4. Service-Specific Debugging Checklist</h3><p>If an error occurs, follow this path to isolate it:</p><ol><li><strong>Check the API Gateway (The Front Door):</strong></li></ol><ul><li><em>Tool:</em> Enable <strong>Execution Logging</strong> in API Gateway.</li><li><em>What to look for:</em> Are requests being rejected due to bad API keys or Rate Limiting before they even reach your code?</li></ul><p><strong>2. Check the ALB (The Traffic Cop):</strong></p><ul><li><em>Tool:</em> Enable <strong>Access Logs</strong> (saves to an S3 bucket) and check CloudWatch HTTP 5xx metrics.</li><li><em>What to look for:</em> If the ALB says 502 Bad Gateway, it means the ALB successfully routed the traffic, but the EC2 instance rejected it or crashed. The network is fine; the problem is your code.</li></ul><p><strong>3. Check the EC2 Instance (The Code):</strong></p><ul><li><em>Tool:</em> SSH into the machine and read the raw logs (e.g., /var/log/syslog or your Node.js PM2 logs), or check CloudWatch Logs.</li><li><em>What to look for:</em> Did the code throw an Unhandled Exception? Did it run out of RAM (OOM kill)?</li></ul><p><strong>4. Check the RDS Database (The Ledger):</strong></p><ul><li><em>Tool:</em> Enable <strong>Performance Insights</strong> and the <strong>Slow Query Log</strong> in RDS.</li><li><em>What to look for:</em> The code might be fine, but a specific SQL query (like searching millions of users without an index) is taking 45 seconds to run, causing the EC2 instance to time out while waiting for the database.</li></ul><h3>Final Summary</h3><p>Mastering AWS is simply about understanding how data flows from the outside world into your private network.</p><ol><li><strong>Security first:</strong> Always put your backend (<strong>EC2</strong>) and database (<strong>RDS</strong>) in a <strong>Private Subnet</strong>. Only use the <strong>Internet Gateway</strong> and <strong>ALB</strong> in the public subnet to manage who is allowed in.</li><li><strong>Never rely on one server:</strong> Virtual computers will crash. Use <strong>Auto Scaling Groups</strong> and <strong>Multi-AZ RDS</strong> deployments to guarantee your app survives hardware failures without you lifting a finger.</li><li><strong>Monitor everything:</strong> When things break, don’t guess. Follow the traffic backward using <strong>CloudWatch</strong>, <strong>VPC Flow Logs</strong>, and <strong>CloudTrail</strong> to pinpoint the exact failure.</li></ol><p>With these core concepts, you now have the blueprint to architect, deploy, and debug enterprise-grade applications on AWS!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6a101dcaca15" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Stop Crashing Your Servers: The Ultimate Guide to Pagination (Offset vs. Cursor)]]></title>
            <link>https://ashishksahoo.medium.com/stop-crashing-your-servers-the-ultimate-guide-to-pagination-offset-vs-cursor-b3906ecd0ad0?source=rss-95f47ff57945------2</link>
            <guid isPermaLink="false">https://medium.com/p/b3906ecd0ad0</guid>
            <category><![CDATA[database-design]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[system-design-concepts]]></category>
            <dc:creator><![CDATA[Ashish Kumar Sahoo]]></dc:creator>
            <pubDate>Wed, 15 Jul 2026 08:22:16 GMT</pubDate>
            <atom:updated>2026-07-15T08:22:16.229Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dTkSuPwxzJBblH-FEMa-Ng.png" /></figure><blockquote>Ever clicked a link to view a list of orders and watched your browser freeze for 10 seconds? Or worse, received a panicked alert that your backend server just crashed due to an Out of Memory error?</blockquote><p>You might have a <strong>pagination problem</strong>.</p><p>In this guide, we will break down exactly what <strong>pagination </strong>is, why your application will fail without it, how to identify if you’re currently using it wrong, and the definitive difference between the two heavyweights: <strong>Offset-based</strong> and <strong>Cursor-based</strong> pagination.</p><h3>1. The Silent Killer: Missing Pagination</h3><p>Imagine a database with 1 million user records. Your frontend application asks the database for “all users.” Here is exactly what happens next:</p><ol><li><strong>Database Overload:</strong> The database struggles to scan and load 1 million records into its memory, blocking other critical queries.</li><li><strong>Network Bottleneck:</strong> Transferring 1 million records over the internet results in a massive, multi-megabyte API response.</li><li><strong>Application Crash:</strong> Your backend server attempts to process this massive payload in RAM, leading to fatal Out of Memory (OOM) errors.</li><li><strong>Browser Freeze:</strong> The browser tries to render 1 million rows of HTML. It freezes, stutters, and forces the user to force-quit the tab.</li></ol><h3>How to Identify This in Your Current App</h3><p>If you aren’t sure if your app is missing pagination, look for these symptoms:</p><ul><li><strong>The Developer Tools Test:</strong> Open your browser’s Network tab. If the API returning your data lists its size in Megabytes (MB) rather than Kilobytes (KB), you are pulling too much data.</li><li><strong>The “Hanging” UI:</strong> If navigating to a specific data table consistently causes the browser to lag or freeze.</li><li><strong>Cloud Bills:</strong> Unusually high costs for “Data Egress / Transfer Out” on AWS or Azure.</li></ul><h3>2. The Solution: Pagination</h3><p><strong>Pagination</strong> is the process of dividing a massive dataset into smaller, manageable chunks. Instead of fetching 1 million records, you fetch exactly what the user can see right now (e.g., 20 records).</p><p>When you paginate, performance becomes flat. Whether your database has 100 records or 100 million, fetching a single page of 20 takes the exact same amount of time.</p><p>There are two main ways to execute this. Let’s look at both.</p><h3>3. Method 1: Offset-Based Pagination</h3><p>This is the traditional [1] [2] [3] ... [10] pagination you see at the bottom of data tables. It relies on skipping a specific number of records (offset) and taking a set amount (limit).</p><p><strong>The SQL:</strong></p><pre>SELECT * FROM users ORDER BY created_at DESC LIMIT 20 OFFSET 40;</pre><p><em>(Translation: Skip the first 40 users, and give me the next 20).</em></p><h3>The Architecture Flow</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/917/1*mcvEORrQwPlXWwEnc8IYqQ.png" /><figcaption>offset-pagination</figcaption></figure><h3>When to use it:</h3><ul><li><strong>Admin Dashboards &amp; Data Tables:</strong> Where users actually need to jump randomly to specific pages (e.g., “I know that order is somewhere around page 50”).</li><li><strong>Static Data:</strong> Where data isn’t being inserted or deleted rapidly.</li></ul><h3><strong>WARNING</strong></h3><p><strong>The Flaw:</strong> Offset gets incredibly slow on deep pages. OFFSET 500000 forces the database to scan and discard half a million rows before returning your 20 items.</p><h3>4. Method 2: Cursor-Based Pagination</h3><p>This is the modern approach, favored by massive platforms like Twitter, Slack, and standard GraphQL APIs. Instead of saying “skip 40 items”, you say “Give me 20 items that come <em>after</em> this specific item ID”.</p><p><strong>The SQL:</strong></p><pre>SELECT * FROM users WHERE id &gt; 1045 ORDER BY id ASC LIMIT 20;</pre><h3>The Architecture Flow</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/897/1*InFpjGdnxuIUNS_Rm7JN_g.png" /><figcaption>cursor-pagination</figcaption></figure><h3>When to use it:</h3><ul><li><strong>Infinite Scrolling:</strong> Social media feeds, mobile apps, or chat histories.</li><li><strong>Massive Datasets:</strong> Where performance must remain instant regardless of how deep the user scrolls.</li></ul><h3>5. The Breaking Point: When to Upgrade</h3><p>If you are currently using Offset-based pagination, you don’t necessarily need to rewrite your entire app today. However, you <strong>must</strong> upgrade to Cursor-based pagination if you hit any of these breaking points:</p><h3>A. You switch to an “Infinite Scroll” UI</h3><p>Offset pagination is terrible for infinite scroll. As the user scrolls deeper, the OFFSET number gets larger, the database works harder, and the app eventually lags.</p><h3>B. You experience “Data Drift” (The Duplicate Item Bug)</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/917/1*eISJgCW5IJW7YNK5ojHSxQ.png" /></figure><p>If you have a high-traffic app where users frequently create new data, Offset pagination will break the user experience. Here is why:</p><p>Cursor pagination completely eradicates this bug because it anchors to a specific ID, ignoring anything inserted above it.</p><h3>C. You are building a Public API</h3><p>If you open your API to the public (like Stripe or GitHub), you must use Cursor pagination. If you use Offset, a poorly-written script could request OFFSET 10,000,000 and intentionally crash your database. Cursor pagination ensures every query is cheap and indexed.</p><h3>Conclusion</h3><ul><li>Need jump-to-page navigation on a moderately sized internal tool? <strong>Use Offset.</strong></li><li>Building an infinite scroll feed for millions of users? <strong>Use Cursor.</strong></li></ul><p>Pagination isn’t just a UI feature; it is the ultimate defense mechanism for your database and backend infrastructure. Implement it early, and implement it right.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b3906ecd0ad0" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to Actually Solve the N+1 Problem (The Hybrid Strategy)]]></title>
            <link>https://ashishksahoo.medium.com/how-to-actually-solve-the-n-1-problem-the-hybrid-strategy-636f1bf765a9?source=rss-95f47ff57945------2</link>
            <guid isPermaLink="false">https://medium.com/p/636f1bf765a9</guid>
            <category><![CDATA[system-design-concepts]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[database-design]]></category>
            <category><![CDATA[design-systems]]></category>
            <category><![CDATA[software-architecture]]></category>
            <dc:creator><![CDATA[Ashish Kumar Sahoo]]></dc:creator>
            <pubDate>Tue, 14 Jul 2026 07:15:27 GMT</pubDate>
            <atom:updated>2026-07-14T07:15:27.126Z</atom:updated>
            <content:encoded><![CDATA[<p>In Part 1, we learned that the N+1 query problem is like making a separate trip to the grocery store for every single item on your list. Because your application is crossing the network dozens or hundreds of times for a single page load, the user experiences significant delays.</p><p>So, how do we fix it? If making 11 trips to the database is bad, the obvious solution seems to be: <em>Just get everything in 1 trip!</em></p><p>In SQL, getting everything in one trip usually means using a JOIN. But as we&#39;ll see, blindly using JOINs can sometimes make the problem even worse.</p><h3>The False Fix: “Just JOIN Everything”</h3><p>Let’s return to our E-Commerce example from Part 1. We want to fetch a list of <strong>Orders</strong>. For each order, we also want the <strong>Customer</strong>, the <strong>Product</strong>, and the history of <strong>Order Logs</strong> (like “Placed”, “Packed”, “Shipped”).</p><p>If a developer decides to fix the N+1 problem by joining all these tables together into one massive query, they will write something like this:</p><pre>SELECT * FROM orders<br>JOIN users ON orders.user_id = users.id<br>JOIN products ON orders.product_id = products.id<br>JOIN order_logs ON orders.id = order_logs.order_id;</pre><p>This works perfectly for the Users and Products. An order has exactly one customer and one product.</p><p>But what about the Order_Logs? An order can have <em>many</em> logs.</p><p>When you JOIN a “Many” relationship, SQL creates a new row for every single child item. If Order #1 has 5 logs, the database will send back 5 rows for that one order. It will duplicate the Customer and Product data 5 times just to show you the 5 different log statuses.</p><p>This leads to a phenomenon called <strong>Row Explosion</strong>.</p><p>If you fetch 100 orders, and each order has an average of 20 logs, the database will generate and send you <strong>2,000 rows</strong>. Most of that data is identical, wasted duplicates. Your application will use up large amounts of memory trying to sort through it.</p><h3>The Real Solution: The Hybrid Strategy</h3><p>To fix this efficiently, modern tech companies use a “Hybrid Strategy”. Instead of using zero JOINs (the N+1 problem) or joining absolutely everything (Row Explosion), they mix two techniques based on a very simple rule of thumb:</p><blockquote><strong><em>Rule of Thumb:</em></strong><em> <br></em>Fetch parents once → Fetch children in batches → Assemble in memory.</blockquote><p>Let’s break this down into two practical rules you can use every day.</p><h4>Rule 1: For Singular Relationships ➡️ Use JOINs</h4><p><em>(Many-to-One or One-to-One)</em></p><p>Because an Order only has exactly ONE Customer and exactly ONE Product, joining them is safe. It will not duplicate rows. It simply adds more columns to your result.</p><pre>-- Query 1: Fetch the Orders, Customers, and Products safely.<br>SELECT * FROM orders<br>JOIN users ...<br>JOIN products ...<br>LIMIT 10;</pre><p><em>Result: Exactly 10 clean rows.</em></p><h4>Rule 2: For Plural Relationships ➡️ Use Batch Fetching</h4><p><em>(One-to-Many or Many-to-Many)</em></p><p>We still need the Order_Logs, but we don&#39;t want to JOIN them. Instead, we look at the 10 orders we just found (let&#39;s say they have IDs 1 through 10), and we do a <strong>second, separate query</strong> asking specifically for those logs.</p><pre>-- Query 2: Batch fetch the logs for the 10 orders<br>SELECT * FROM order_logs <br>WHERE order_id IN (1, 2, 3, 4, 5, 6, 7, 8, 9, 10);</pre><p><em>Result: Returns only the exact logs that exist. No duplicated order data.</em></p><h3>The Magic of the ORM (In-Memory Stitching)</h3><p>We just reduced a 41-query disaster down to exactly <strong>2 highly efficient queries</strong>. We avoided network spam, and we avoided Row Explosion.</p><p>But how do these two separate sets of data connect?</p><p>If you are writing raw SQL, you would have to write a few lines of code to group the logs by their order_id and attach them to the correct orders.</p><p>However, if you are using a modern ORM (Object-Relational Mapper) like SQLAlchemy in Python, Hibernate in Java, or Django ORM, the framework does this for you automatically. It takes the results of Query 1 and Query 2 and seamlessly stitches them together in your server’s memory.</p><p>Here is what that Hybrid Strategy looks like in SQLAlchemy:</p><pre>from sqlalchemy.orm import joinedload, selectinload<br><br>orders = (<br>    session.query(Order)<br>    .options(<br>        joinedload(Order.user),       # Singular: JOIN it!<br>        joinedload(Order.product),    # Singular: JOIN it!<br>        selectinload(Order.logs)      # Plural: Batch Fetch it!<br>    )<br>    .limit(10)<br>    .all()<br>)</pre><h3>Final Takeaway</h3><p>The N+1 problem is a structural issue, but it is easily fixed once you stop thinking of the database as a place to run for loops.</p><p>By applying the Hybrid Strategy - JOINing singular relationships and Batch Fetching plural ones - you can ensure your application remains incredibly fast and responsive, no matter how much data you throw at it.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=636f1bf765a9" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The N+1 Query Problem Explained Simply]]></title>
            <link>https://ashishksahoo.medium.com/the-n-1-query-problem-explained-simply-d03bd842c26f?source=rss-95f47ff57945------2</link>
            <guid isPermaLink="false">https://medium.com/p/d03bd842c26f</guid>
            <category><![CDATA[database]]></category>
            <category><![CDATA[design-systems]]></category>
            <category><![CDATA[software-engineering]]></category>
            <dc:creator><![CDATA[Ashish Kumar Sahoo]]></dc:creator>
            <pubDate>Tue, 14 Jul 2026 07:04:56 GMT</pubDate>
            <atom:updated>2026-07-14T07:17:05.878Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HtnO_avM5-i7hsriFxqJzQ.png" /></figure><p>If you build applications that talk to a database, you will eventually encounter the N+1 query problem. It is a common structural mistake in how code retrieves related data, and it is the most frequent cause of slow web pages.</p><p>To understand it perfectly so you never forget it, let’s step away from code for a minute and look at a real-world analogy.</p><h3>The Grocery Store Analogy</h3><p>Imagine you are at home, and you realize you need to buy 10 different items from the grocery store.</p><p><strong>The Normal Way (1 Trip)</strong> You write all 10 items on a single shopping list. You drive to the store, put all 10 items in your cart, pay, and drive home. <em>Total trips to the store: 1</em></p><p><strong>The N+1 Way (11 Trips)</strong> You look in your fridge and notice you need milk. You drive to the store, buy milk, and drive home. Once home, you check the pantry and realize you need eggs. You drive to the store, buy eggs, and drive home. You repeat this process for all 10 items. <em>Total trips to the store: 1 (finding out what you need) + 10 (buying the items individually) = 11 trips.</em></p><p>The N+1 query problem in programming is exactly this. Your code is driving back and forth to the database to fetch data one piece at a time, instead of asking for everything it needs in a single trip.</p><h3>The Code Example</h3><p>Let’s translate this to a real application. Suppose you are building a simple blog. The homepage needs to display the 10 most recent articles, along with the name of the author who wrote each article.</p><p>In your database, you have two tables:</p><ol><li><strong>Articles:</strong> Contains the article text and an author_id.</li><li><strong>Authors:</strong> Contains the author’s name and details.</li></ol><p>Here is how a developer might naturally write this code:</p><pre># Trip 1: Get the 10 most recent articles<br>articles = database.execute(&quot;SELECT * FROM articles LIMIT 10&quot;)<br><br># Prepare a list to send to the user&#39;s browser<br>homepage_data = []<br><br># Loop through the 10 articles<br>for article in articles:<br>    <br>    # Inside the loop: Go back to the database for EACH article<br>    author = database.execute(f&quot;SELECT * FROM authors WHERE id = {article.author_id}&quot;)<br>    <br>    homepage_data.append({<br>        &quot;title&quot;: article.title,<br>        &quot;author_name&quot;: author.name<br>    })</pre><h3>The Math (Why it is called N+1)</h3><p>Let’s count the trips to the database.</p><ol><li><strong>The “1”:</strong> The code makes <strong>1</strong> initial query to get the list of articles.</li><li><strong>The “N”:</strong> The code enters a loop. Because there are 10 articles, the loop runs 10 times. Inside that loop is another database query. Therefore, the code makes <strong>10</strong> additional queries to get the authors. (In mathematics, ’N’ represents the number of items in the list).</li></ol><p><strong>Total Queries = N + 1</strong> In our example, N is 10. So it takes 10 + 1 = 11 queries to load a very simple homepage.</p><p>If your homepage displayed 50 articles, it would take 50 + 1 = 51 queries.</p><h3>Why is this a problem?</h3><p>The issue is not that databases are slow at finding data. Databases are highly optimized and can find an author in a fraction of a millisecond.</p><p>The issue is the <strong>travel time</strong> (network latency).</p><p>Every time your code says database.execute(), it has to open a connection, send a request over the network to the database server, wait for the database to process it, and wait for the data to travel back over the network.</p><p>Just like driving to the grocery store takes much longer than picking up the milk once you are inside, the network travel time is the bottleneck. By making 51 separate trips across the network instead of 1 or 2 trips, the application becomes noticeably slow for the user.</p><blockquote>Now that we understand the core problem - that our code is making too many separate trips - <a href="https://medium.com/@ashishksahoo/how-to-actually-solve-the-n-1-problem-the-hybrid-strategy-636f1bf765a9?sharedUserId=ashishksahoo"><strong>we can look at how to solve it in Part 2</strong></a><strong>.</strong></blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d03bd842c26f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Understanding the N+1 Query Problem: From First Principles to Real-World Solutions]]></title>
            <link>https://ashishksahoo.medium.com/understanding-the-n-1-query-problem-from-first-principles-to-real-world-solutions-ace1f8d93f6c?source=rss-95f47ff57945------2</link>
            <guid isPermaLink="false">https://medium.com/p/ace1f8d93f6c</guid>
            <category><![CDATA[database]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[system-design-concepts]]></category>
            <category><![CDATA[scalability]]></category>
            <dc:creator><![CDATA[Ashish Kumar Sahoo]]></dc:creator>
            <pubDate>Sat, 11 Jul 2026 08:09:54 GMT</pubDate>
            <atom:updated>2026-07-11T08:09:54.561Z</atom:updated>
            <content:encoded><![CDATA[<p>As developers, we often focus on making our applications <strong>functionally correct</strong>. If the API returns the expected data, we consider the job done. However, as applications grow and the number of users increases, another factor becomes equally important: <strong>performance</strong>.</p><p>One of the most common performance issues in backend development is the <strong>N+1 Query Problem</strong>. It’s not a bug that crashes your application — it silently slows it down as your data grows.</p><p>In this article, we’ll understand what the N+1 Query Problem is, why it occurs, how to identify it, and the best ways to solve it using practical examples.</p><h3>What Exactly Is the N+1 Query Problem?</h3><p>The N+1 Query Problem occurs when an application:</p><ol><li>Executes <strong>one query</strong> to fetch a list of records.</li><li>Executes <strong>one additional query for each record</strong> to fetch related information.</li></ol><p>If there are <strong>N records</strong>, the total number of database queries becomes:</p><pre>1 + N</pre><p>Hence the name <strong>N+1 Query Problem</strong>.</p><p>The application still produces the correct result, but it becomes increasingly slower as the amount of data grows.</p><h3>Why Does It Happen?</h3><p>The root cause is simple:</p><p>Instead of fetching all the required data in one go, the application repeatedly asks the database for additional information while processing each record.</p><p>The typical flow looks like this:</p><pre>Fetch a list<br>      ↓<br>Loop through each record<br>      ↓<br>Run another database query</pre><p>Every iteration creates another trip to the database.</p><p>Even if each query is fast, thousands of unnecessary database round trips significantly increase response time.</p><h3>A Real-World Analogy</h3><p>Imagine you’re a waiter in a restaurant.</p><p>A customer asks for:</p><ul><li>A Burger</li><li>Fries</li><li>Coke</li><li>Dessert</li></ul><h3>Inefficient Approach</h3><p>You walk to the kitchen.</p><p>“One burger.”</p><p>Walk back.</p><p>Then again.</p><p>“One fries.”</p><p>Walk back.</p><p>Then again.</p><p>“One Coke.”</p><p>Walk back.</p><p>Then again.</p><p>“Dessert.”</p><p>You’ve made four separate trips.</p><h3>Efficient Approach</h3><p>Walk once.</p><p>“Burger, fries, Coke, and dessert.”</p><p>One trip.</p><p>Same result.</p><p>Much faster.</p><p>A database works the same way.</p><p>Every query is another trip to the database.</p><h3>A Practical Database Example</h3><p>Suppose we have two tables.</p><h3>Employees</h3><p>Employee ID Name Department ID<br>1Ashish22Rahul13Ankit2</p><h3>Departments</h3><p>Department IDDepartment Name1HR2Engineering</p><p>We want to display:</p><p>EmployeeDepartmentAshishEngineeringRahulHRAnkitEngineering</p><p>A beginner might write:</p><pre>const employees = await getEmployees();<br>for (const employee of employees) {<br>    const department = await getDepartment(employee.departmentId);<br>}</pre><p>What actually happens?</p><pre>Query 1:<br>SELECT * FROM Employees;</pre><p>Then</p><pre>SELECT * FROM Departments WHERE id = 2;</pre><p>Then</p><pre>SELECT * FROM Departments WHERE id = 1;</pre><p>Then</p><pre>SELECT * FROM Departments WHERE id = 2;</pre><p>Three employees resulted in four database queries.</p><p>If there were 10,000 employees, the application would execute:</p><pre>1 + 10,000 = 10,001 Queries</pre><p>This is the N+1 Query Problem.</p><h3>Why Is This Bad?</h3><p>Every database query involves:</p><ul><li>Sending a request</li><li>Network communication</li><li>Parsing SQL</li><li>Finding the data</li><li>Returning the response</li></ul><p>Even if each query takes only 5 milliseconds:</p><pre>10,000 × 5 ms = 50 seconds</pre><p>The problem isn’t the database.</p><p>The problem is repeatedly asking the database for information that could have been retrieved much more efficiently.</p><h3>How to Identify the Problem</h3><p>Whenever your code follows this pattern:</p><pre>Fetch list<br>      ↓<br>      Loop<br>      ↓<br>Database query inside loop</pre><p>Pause and ask yourself:</p><blockquote><em>“Am I making one database request for every record?”</em></blockquote><p>If the answer is yes, you’re likely facing an N+1 Query Problem.</p><p>For example:</p><pre>const orders = await getOrders();<br><br>for (const order of orders) {<br>    const customer = await getCustomer(order.customerId);<br>}</pre><p>The warning sign is the database call inside the loop.</p><h3>Even Worse: Nested N+1</h3><p>Consider this code:</p><pre>const users = await getUsers();<br><br>for (const user of users) {<br>    const posts = await getPosts(user.id);<br>    for (const post of posts) {<br>        const comments = await getComments(post.id);<br>    }<br>}</pre><p>Imagine:</p><ul><li>100 users</li><li>20 posts per user</li><li>10 comments per post</li></ul><p>Queries become:</p><pre>Users      : 1<br>Posts      : 100<br>Comments   : 2000<br>Total      : 2101 Queries</pre><p>Performance degrades dramatically.</p><h3>Solution 1: SQL JOIN</h3><p>The simplest solution is to fetch related data together.</p><p>Instead of querying employees first and departments later:</p><pre>SELECT<br>employees.name,<br>departments.department_name<br>FROM employees<br>JOIN departments<br>ON employees.department_id = departments.id;</pre><p>Now the database returns everything in one optimized query.</p><p>Databases are designed for joins and can execute them efficiently.</p><h3>Solution 2: Eager Loading</h3><p>Modern ORMs provide eager loading.</p><p>Instead of:</p><pre>const posts = await prisma.post.findMany();<br><br>for (const post of posts) {<br>    await prisma.user.findUnique({<br>        where: {<br>            id: post.userId<br>        }<br>    });<br>}</pre><p>Use:</p><pre>const posts = await prisma.post.findMany({<br>    include: {<br>        user: true<br>    }<br>});</pre><p>Other ORMs provide similar features:</p><h3>Sequelize</h3><pre>Post.findAll({<br>    include: User<br>});</pre><h3>Mongoose</h3><pre>Post.find().populate(&quot;user&quot;)</pre><p>The ORM retrieves related data efficiently without one query per record.</p><h3>Solution 3: Batch Fetching</h3><p>Sometimes a JOIN isn’t the best choice.</p><p>Suppose invoices reference customers.</p><p>Instead of querying one customer at a time:</p><pre>Customer 1<br>Customer 5<br>Customer 2<br>Customer 5<br>Customer 9</pre><p>Collect all unique IDs first:</p><pre>1<br>2<br>5<br>9</pre><p>Then execute:</p><pre>SELECT *<br>FROM Customers<br>WHERE id IN (1,2,5,9);</pre><p>Build a lookup map:</p><pre>{<br>    1: {...},<br>    2: {...},<br>    5: {...},<br>    9: {...}<br>}</pre><p>Now the loop performs only in-memory lookups.</p><h3>Solution 4: Caching</h3><p>Sometimes the same data is requested repeatedly.</p><p>Imagine 100 orders belonging to the same customer.</p><p>Without caching:</p><pre>Customer Query<br>Customer Query<br>Customer Query<br>Customer Query</pre><p>With caching:</p><pre>First Query<br>↓<br>Cache<br>↓<br>Memory<br>↓<br>Memory<br>↓<br>Memory</pre><p>Only one database query is executed.</p><p>Caching works well for:</p><ul><li>Countries</li><li>Departments</li><li>Categories</li><li>Product metadata</li><li>User profiles</li><li>Configuration values</li></ul><h3>Solution 5: DataLoader (GraphQL)</h3><p>GraphQL APIs frequently encounter N+1 problems.</p><p>Without batching:</p><pre>100 Users<br>↓<br>100 Database Queries</pre><p>With DataLoader:</p><pre>100 Users<br>↓<br>Collect IDs<br>↓<br>Single Batched Query</pre><p>Instead of making one request per resolver, DataLoader batches them automatically.</p><h3>Real-World Scenarios</h3><h3>E-Commerce Platform</h3><p>A product page displays:</p><ul><li>Product</li><li>Seller</li><li>Rating</li><li>Inventory</li></ul><p>Bad approach:</p><pre>100 Products<br>↓<br>100 Seller Queries<br>↓<br>100 Rating Queries<br>↓<br>100 Inventory Queries</pre><p>301 database queries.</p><p>Better approach:</p><p>Use JOINs or eager loading to fetch all related information together.</p><h3>Admin Dashboard</h3><p>Displaying:</p><ul><li>Users</li><li>Orders</li><li>Payments</li><li>Addresses</li></ul><p>Running separate queries inside loops quickly leads to N+1 problems.</p><p>Instead, fetch relationships efficiently or batch related requests.</p><h3>A Simple Rule to Remember</h3><p>Whenever you write code like:</p><pre>const items = await fetchItems();<br>for (const item of items) {<br>    await databaseQuery(item.id);<br>}</pre><p>Stop.</p><p>Ask yourself:</p><ol><li>Can I fetch everything using a JOIN?</li><li>Can my ORM eagerly load the relationship?</li><li>Can I batch these IDs into one query?</li><li>Would caching eliminate repeated lookups?</li><li>If I’m using GraphQL, should I use DataLoader?</li></ol><p>If the answer to any of these questions is “yes,” you can probably eliminate the N+1 Query Problem.</p><h3>Key Takeaways</h3><ul><li>The N+1 Query Problem is a performance issue, not a correctness issue.</li><li>It occurs when one initial query is followed by one additional query per record.</li><li>The biggest warning sign is a database query inside a loop.</li><li>The problem becomes more severe as data grows.</li><li>Common solutions include SQL JOINs, eager loading, batch fetching, caching, and GraphQL DataLoader.</li><li>Learning to recognize this pattern early will help you build scalable applications and write production-quality backend code.</li></ul><p>The next time you see a database query inside a loop, don’t just ask, <em>“Does this work?”</em> Ask a better question:</p><blockquote><strong><em>“Will this still perform well when my application has a million records?</em></strong></blockquote><p>That mindset is what separates developers who write working code from engineers who build systems that scale.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ace1f8d93f6c" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>