<?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 Sameer Ahmed on Medium]]></title>
        <description><![CDATA[Stories by Sameer Ahmed on Medium]]></description>
        <link>https://medium.com/@sameerahmed56?source=rss-e4526effdd7c------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*lsc3oPMQQqrSPLPX8acd8Q.png</url>
            <title>Stories by Sameer Ahmed on Medium</title>
            <link>https://medium.com/@sameerahmed56?source=rss-e4526effdd7c------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 23 Nov 2026 03:04:38 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@sameerahmed56/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[Isolation Levels in Relational Database]]></title>
            <link>https://sameerahmed56.medium.com/the-divide-into-i-in-acid-855b98334530?source=rss-e4526effdd7c------2</link>
            <guid isPermaLink="false">https://medium.com/p/855b98334530</guid>
            <category><![CDATA[database-design]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[database]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[isolation-level]]></category>
            <dc:creator><![CDATA[Sameer Ahmed]]></dc:creator>
            <pubDate>Sun, 26 Jul 2026 14:48:17 GMT</pubDate>
            <atom:updated>2026-08-01T15:42:44.327Z</atom:updated>
            <content:encoded><![CDATA[<p>Isolation Levels in Relational Database</p><p>The Core Misconception of Locks vs. Isolation Levels</p><p>Let’s look at this the way we would if we were debugging a production outage, because the textbook definitions of ACID usually fall apart the minute you hit scale.</p><p>When you’re building complex systems especially anything involving heavy concurrency you have to understand that the database is constantly lying to you. It gives you the illusion that your transaction is the only one happening, while in reality, it’s juggling thousands of concurrent threads all trying to mutate the same memory pages.</p><p>Here is the real breakdown of how isolation levels work under the hood, how they differ from explicit locks, and how you actually use them.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*O-fwTxtX22hMO80lYxQYVA.png" /></figure><h3>The Core Misconception: Locks vs. Isolation Levels</h3><p>A lot of engineers confuse these two. Let’s clear it up immediately.</p><p><strong>Isolation Levels</strong> are the <em>rules of engagement</em>. They are the database’s automatic, systemic policies that dictate what versions of data a transaction is allowed to see. It’s about <em>visibility</em>. <strong>Locks</strong> are manual, pessimistic control mechanisms. They dictate who is allowed to <em>mutate</em> or <em>access</em> data right now.</p><p>Imagine you are building a real-time bidding simulation for an auction. Two concurrent transactions try to bid on the same thing at the exact same millisecond.</p><ul><li>The <strong>Isolation Level</strong> determines if Transaction B can <em>see</em> Transaction A’s uncommitted bid amount while making its own calculation.</li><li>An explicit <strong>Lock</strong> (like SELECT ... FOR UPDATE) is you manually telling the database: &quot;I don&#39;t care about the visibility rules, physically block anyone else from touching this player&#39;s row until my bid logic finishes computing.&quot;</li></ul><p>Using explicit locks everywhere kills throughput. That’s why databases invented <strong>MVCC (Multi-Version Concurrency Control)</strong>.</p><h3>The Engine: MVCC (Multi-Version Concurrency Control)</h3><p>Modern relational databases (like InnoDB for MySQL, or PostgreSQL) rarely use brute-force read-locks anymore. Instead, they use MVCC. Think of it like Git for your database rows.</p><p>When you update a row, the database doesn’t overwrite it in place. It creates a <em>new version</em> of that row. In InnoDB, every row has two hidden columns: DB_TRX_ID (the transaction ID that last modified it) and DB_ROLL_PTR (a pointer to the undo log, where the previous version of the row lives).</p><p>When your transaction runs a query, the database generates a <strong>Read View</strong> (a snapshot). The isolation level you choose simply tells the database <em>how</em> to construct that Read View.</p><p>Here is how each level manages that Read View.</p><h3>1. Read Uncommitted</h3><p><strong>The Mechanism:</strong> The database engine throws the Read View out the window. It simply scans the B-Tree index and grabs the absolute latest data sitting on the disk pages, completely ignoring the DB_TRX_ID and whether the transaction that wrote it has committed or aborted.</p><p><strong>The Anomaly (Dirty Read):</strong> You read data that is eventually rolled back. You are operating on data that technically never existed in the permanent record.</p><p><strong>Pros:</strong> Maximum possible throughput. Zero overhead for checking visibility rules.</p><p><strong>Cons:</strong> Severe logical corruption in application state.</p><p><strong>Real World Use Case:</strong> Almost never used in transactional systems. However, if you are running massive, offline analytical aggregations on a high-velocity logging table—where a 0.001% margin of error on a COUNT(*) is perfectly fine—you might use this to ensure your heavy analytics query doesn&#39;t impact the performance of the writers.</p><h3>2. Read Committed (The Django/Default Standard)</h3><p><strong>The Mechanism:</strong> The database generates a <em>brand new Read View for every single query</em> inside your transaction. When you run SELECT, the engine looks at the active transaction list. It traverses the DB_ROLL_PTR (undo log) for every row, skipping any versions written by transactions that haven&#39;t committed yet.</p><p><strong>The Anomaly (Non-Repeatable Read):</strong> Because the snapshot refreshes on every statement, data can mutate while your transaction is running.</p><pre>BEGIN;<br>SELECT status FROM users WHERE id = 1; -- Returns &#39;ACTIVE&#39;<br>-- Another thread updates the user to &#39;BANNED&#39; and commits.<br>SELECT status FROM users WHERE id = 1; -- Returns &#39;BANNED&#39;<br>COMMIT;</pre><p><strong>Pros:</strong> No dirty reads. Very high concurrency because readers don’t block writers.</p><p><strong>Cons:</strong> Application logic can’t trust that a read remains valid.</p><p><strong>Real World Use Case:</strong> 95% of standard web applications. When a user updates their profile, or you load a standard web page, this level is perfect. You accept the slight risk of race conditions in exchange for not crippling your database with locks.</p><h3>3. Repeatable Read</h3><p><strong>The Mechanism:</strong> The database generates a Read View <em>exactly once</em>, at the start of the transaction, and uses that exact same snapshot for every subsequent query until you commit. Even if other transactions commit new data, your transaction ignores them, forcefully reading the older versions from the undo log.</p><p><strong>The Anomaly (Phantom Read):</strong> This is where it gets tricky. In standard SQL theory, a Repeatable Read freezes <em>existing</em> rows, but doesn’t prevent <em>new</em> rows from being inserted into your search range. So a COUNT(*) might return 5 the first time, and 6 the second time (a phantom row appeared). <em>(Note: InnoDB physically prevents this using Gap Locks, which we&#39;ll get to in a second. Postgres prevents it purely via advanced MVCC).</em></p><p><strong>Pros:</strong> You get a stable, non-mutating view of the data.</p><p><strong>Cons:</strong> Undo logs can grow massive if long-running transactions are kept open, slowing down the whole database.</p><p><strong>Real World Use Case:</strong> Financial reporting, batch jobs, and backups. If you kick off a daily reporting script at midnight, you want the data to represent the system exactly as it was at 12:00:00 AM, even if the script takes 10 minutes to run and users are still doing things in the background.</p><h3>4. Serializable</h3><p><strong>The Mechanism:</strong> This guarantees that executing transactions concurrently yields the exact same state as if you ran them one by one. How it does this depends heavily on the engine.</p><ul><li><strong>InnoDB (Pessimistic):</strong> It abandons MVCC for these queries and relies on heavy locking. It uses <strong>Next-Key Locks</strong>. If you run SELECT * FROM orders WHERE user_id = 5, InnoDB doesn&#39;t just lock user 5&#39;s existing orders. It puts a &quot;Gap Lock&quot; on the index space <em>around</em> user 5. Any other thread trying to insert a new order for user 5 will physically hang until you commit.</li><li><strong>Postgres (Optimistic):</strong> It uses SSI (Serializable Snapshot Isolation). It lets transactions run concurrently using MVCC, but it tracks a dependency graph of who is reading and writing what. If it detects a cycle that would cause an anomaly, it aborts one of the transactions with a serialization_failure.</li></ul><p><strong>The Anomaly:</strong> None. (Though you must handle Write Skew, which Serializable solves).</p><p><strong>Pros:</strong> Bulletproof data integrity.</p><p><strong>Cons:</strong> Deadlocks become a daily reality. Throughput plummets.</p><p><strong>Real World Use Case:</strong> Let&#39;s say you are building an execution engine for something like Zerodha, processing Nifty 50 ETF buy orders. If two users are trying to execute a market order against the exact same limited block of available shares, a Non-Repeatable Read could result in overselling the asset. You enforce Serializable isolation here so the database forcefully serializes the state, guaranteeing exact ledger mathematics.</p><h3>When to rely on Isolation vs. Explicit Locks</h3><p>As a senior engineer, your default stance should be: <strong>Rely on Read Committed, and use explicit row-level locks or application-level versioning for the critical paths.</strong></p><p>Setting your entire database to Serializable is usually a lazy architectural choice that will cause your database to fall over under load. Instead, if you have a highly contested resource—like updating a user&#39;s wallet balance—you stay in Read Committed, but you handle the concurrency explicitly:</p><pre>BEGIN;<br>-- This is an explicit lock. It tells the DB to drop the MVCC illusion <br>-- for this specific row and physically block other writers.<br>SELECT balance FROM wallets WHERE user_id = 99 FOR UPDATE;<br>-- Application logic calculates new balance...<br>UPDATE wallets SET balance = balance - 500 WHERE user_id = 99;<br>COMMIT;</pre><p>This gives you the best of both worlds: 99% of your application runs with high-throughput MVCC, and the 1% that requires strict financial integrity gets the explicit lock it needs.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=855b98334530" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Handling External Service Rate Limiting and Failures in Distributed System]]></title>
            <link>https://blog.stackademic.com/handling-external-service-rate-limiting-and-failures-in-ditributed-system-03b8534cc195?source=rss-e4526effdd7c------2</link>
            <guid isPermaLink="false">https://medium.com/p/03b8534cc195</guid>
            <category><![CDATA[rate-limiting]]></category>
            <category><![CDATA[distributed-systems]]></category>
            <category><![CDATA[system-design-interview]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[software-engineering]]></category>
            <dc:creator><![CDATA[Sameer Ahmed]]></dc:creator>
            <pubDate>Fri, 29 May 2026 09:30:47 GMT</pubDate>
            <atom:updated>2026-06-01T06:58:38.948Z</atom:updated>
            <content:encoded><![CDATA[<p>Why sleep + retry won’t work.</p><p>Most third-party API documentation is a lie of omission. Vendors hand you a pristine cURL snippet, perhaps a basic Python requests.get() example, and send you on your way. They assume a utopian network where packets never drop, DNS always resolves, and servers never buckle under load.</p><p>Production reality is a hostile environment.</p><p>This guide dissects a single, seemingly trivial engineering problem and scales it from a naive script to a globally distributed architecture. We will strictly use Python, discarding theoretical fluff in favor of production-grade code, architectural trade-offs, and the brutal realities of distributed state.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WWM3PDMyh60dwKUpMfa0mg.png" /></figure><h3>The Case Study</h3><p>You are tasked with writing a Python function, fetch_all(urls), that takes a list of thousands of URLs and hits an external vendor&#39;s API.</p><h4>The constraints are absolute:</h4><ol><li><strong>Rate Limiting:</strong> The API strictly enforces a limit of 10 requests per second. Exceeding this triggers a 429 Too Many Requests response and potentially a temporary IP ban.</li><li><strong>Unreliability:</strong> The vendor’s infrastructure is flaky. Roughly 5% of all calls fail with a 5xx Server Error (e.g., 502 Bad Gateway, 504 Gateway Timeout), but these failures are transient and succeed upon a retry.</li></ol><p>Here is how a script evolves into a production grade distributed system.</p><h3>Level 1: Single Host, Synchronous</h3><p>The baseline approach to this problem is a synchronous for loop using the standard requests library. The immediate hurdle isn&#39;t the rate limit, a standard synchronous loop doing TLS handshakes over the public internet might struggle to hit 10 requests per second anyway but the 5% failure rate.</p><p>Inexperienced engineers often attempt to handle retries by wrapping the HTTP call in a while loop with a time.sleep() statement. This is a massive anti-pattern. Custom retry loops are breeding grounds for off-by-one errors, infinite loops, and unreadable code. Furthermore, a static sleep(2) guarantees that when the vendor API hiccups, your system will slam their recovering servers with a synchronized wave of retries two seconds later, potentially knocking them back offline.</p><p>The professional standard is to use exponential backoff with jitter. We abandon custom loops and leverage robust state-machine libraries like tenacity.</p><pre>import time<br>import requests<br>from requests.exceptions import HTTPError, ConnectionError, Timeout<br>from tenacity import (<br>    retry,<br>    stop_after_attempt,<br>    wait_exponential,<br>    wait_random_exponential,<br>    retry_if_exception_type,<br>    before_sleep_log<br>)<br>import logging<br><br>logging.basicConfig(level=logging.INFO)<br>logger = logging.getLogger(__name__)<br># Define which exceptions warrant a retry. We don&#39;t retry 404s or 400s.<br>RETRYABLE_EXCEPTIONS = (ConnectionError, Timeout)<br>def is_retryable_http_error(exception):<br>    &quot;&quot;&quot;Only retry 5xx errors and 429s.&quot;&quot;&quot;<br>    if isinstance(exception, HTTPError):<br>        status = exception.response.status_code<br>        return status == 429 or 500 &lt;= status &lt; 600<br>    return False<br>@retry(<br>    # Stop trying after 5 total attempts<br>    stop=stop_after_attempt(5),<br>    # Wait 2^x * 1 second between each retry, up to 10 seconds, adding random jitter<br>    wait=wait_random_exponential(multiplier=1, max=10),<br>    retry=retry_if_exception_type(RETRYABLE_EXCEPTIONS) | retry_if_exception_type(HTTPError),<br>    before_sleep=before_sleep_log(logger, logging.WARNING)<br>)<br>def fetch_single(session: requests.Session, url: str) -&gt; dict:<br>    response = session.get(url, timeout=5)<br>    response.raise_for_status()<br>    return response.json()<br>def fetch_all(urls: list[str]):<br>    results = []<br>    # Use a Session to pool connections, avoiding TLS handshake overhead per request<br>    with requests.Session() as session:<br>        for url in urls:<br>            try:<br>                # We enforce the 10 req/sec limit trivially by sleeping 0.1s<br>                time.sleep(0.1) <br>                data = fetch_single(session, url)<br>                results.append(data)<br>            except Exception as e:<br>                logger.error(f&quot;Failed to fetch {url} permanently: {e}&quot;)<br>                results.append(None)<br>    return results</pre><h4><strong>Why this works at Level 1:</strong></h4><p>We utilize requests.Session() to maintain an underlying TCP connection pool. The tenacity decorator handles the state machine of retrying. We explicitly use wait_random_exponential to introduce <em>jitter</em>. Jitter ensures that if 50 requests fail simultaneously at T=0, they do not all retry exactly at T=2, T=4, and T=8. The randomization spreads the load, preventing self-inflicted denial-of-service attacks against the vendor.</p><h4><strong>Where it breaks:</strong></h4><p>It is catastrophically slow. Because it is synchronous, waiting for I/O blocks the entire thread. If a request takes 500ms to resolve, our loop is blocked for that half-second. We will never reach our allowed throughput of 10 requests per second. We are leaving bandwidth on the table.</p><h3>Level 2: Single Host, Concurrent</h3><p>To maximize our 10 requests per second allowance, we must decouple request dispatching from response waiting. Python offers ThreadPoolExecutor for thread-based concurrency, but for massive I/O bound workloads, asyncio combined with aiohttp is vastly superior due to reduced memory overhead and lack of OS-level context switching.</p><p>However, moving to concurrent execution introduces a lethal trap: confusing <em>concurrency</em> with <em>rate</em>.</p><p>A standard mistake is wrapping the async calls in an asyncio.Semaphore(10). A Semaphore limits the number of <em>in-flight</em> requests. If the vendor API is fast and responds in 50 milliseconds, a Semaphore of 10 will allow 10 requests to complete, immediately freeing up the slots to fire 10 more. In a single second, your code will fire 200 requests, obliterate the rate limit, and drown in 429 Too Many Requests errors.</p><p>We do not need a concurrency limit; we need a mathematical rate limiter, specifically an implementation of the Token Bucket or Leaky Bucket algorithm. We will use the aiolimiter library.</p><pre>import asyncio<br>import aiohttp<br>from aiolimiter import AsyncLimiter<br>from tenacity import retry, stop_after_attempt, wait_random_exponential, retry_if_exception_type<br><br># 10 requests per 1 second<br>rate_limiter = AsyncLimiter(max_rate=10, time_period=1)<br>@retry(<br>    stop=stop_after_attempt(5),<br>    wait=wait_random_exponential(multiplier=1, max=10),<br>    retry=retry_if_exception_type((aiohttp.ClientError, asyncio.TimeoutError))<br>)<br>async def fetch_single_async(session: aiohttp.ClientSession, url: str) -&gt; dict:<br>    # The rate limiter ensures we never exceed the token allowance<br>    async with rate_limiter:<br>        async with session.get(url, timeout=5) as response:<br>            if response.status in {429, 500, 502, 503, 504}:<br>                # Force tenacity to retry by raising an exception<br>                response.raise_for_status() <br>            return await response.json()<br>async def fetch_all_async(urls: list[str]):<br>    # Limit concurrent open connections to a reasonable number (e.g., 100)<br>    # This prevents exhausting local file descriptors, entirely separate from the 10 req/s limit.<br>    connector = aiohttp.TCPConnector(limit=100)<br>    <br>    async with aiohttp.ClientSession(connector=connector) as session:<br>        tasks = [fetch_single_async(session, url) for url in urls]<br>        # gather fires them all concurrently; the rate limiter inside fetch_single_async throttles them<br>        results = await asyncio.gather(*tasks, return_exceptions=True)<br>        return results<br># Execution:<br># asyncio.run(fetch_all_async(urls))</pre><h4><strong>Why this works at Level 2:</strong></h4><p>We have separated concerns. aiohttp.TCPConnector prevents our machine from running out of ephemeral ports or file descriptors. AsyncLimiter enforces the strict time-based constraint. tenacity handles the flaky vendor network. The application will effortlessly saturate the 10 req/s limit without breaching it.</p><h4><strong>Where it breaks:</strong></h4><p>State is entirely local to memory. This architecture functions perfectly right up until you deploy it behind a WSGI server or into a task queue. If you use a framework like Django and background workers like Celery, spinning up 4 Celery worker processes means you now have 4 isolated memory spaces. Each worker initializes its own AsyncLimiter(10, 1).</p><p>Worker A fires 10 requests. Worker B fires 10 requests. You are now pushing 40 requests per second. The external API bans your IP address.</p><h3>Level 3: Single Host, Multiple Services</h3><p>When scaling Python applications, we invariably move to multi-process architectures to bypass the Global Interpreter Lock (GIL) or to process background tasks asynchronously. Our rate limiting state must move out of process memory and into a shared, centralized data store.</p><p>Redis is the industry standard for this.</p><p>However, naive Redis interactions will destroy your rate limit through race conditions. If you execute a Python script that reads a key (GET rate_count), checks if it is under 10, increments it (INCR rate_count), and proceeds, you have created a classic Time-Of-Check to Time-Of-Use (TOCTOU) vulnerability. Two concurrent Celery workers will read the value as 9, both will bypass the check, both will increment, and your limit is breached.</p><p>You must ensure atomicity. In Redis, this means using Lua scripts. Redis guarantees that Lua scripts execute atomically; no other Redis command or script can run while a script is executing.</p><p>Here is the implementation of a distributed sliding window rate limiter using Redis Lua scripting within Python.</p><pre>import time<br>import asyncio<br>import aiohttp<br>from redis.asyncio import Redis<br><br># Lua script for a sliding window rate limiter<br># KEYS[1]: the rate limit key<br># ARGV[1]: window size in milliseconds<br># ARGV[2]: max requests per window<br># ARGV[3]: current timestamp in milliseconds<br># ARGV[4]: unique identifier for the request<br>LUA_SLIDING_WINDOW = &quot;&quot;&quot;<br>local key = KEYS[1]<br>local window = tonumber(ARGV[1])<br>local limit = tonumber(ARGV[2])<br>local now = tonumber(ARGV[3])<br>local member = ARGV[4]<br>-- Remove elements outside the current window<br>redis.call(&#39;ZREMRANGEBYSCORE&#39;, key, 0, now - window)<br>-- Count remaining elements<br>local current_requests = redis.call(&#39;ZCARD&#39;, key)<br>if current_requests &lt; limit then<br>    -- Add current request to the sorted set<br>    redis.call(&#39;ZADD&#39;, key, now, member)<br>    -- Set TTL to ensure cleanup if the system dies<br>    redis.call(&#39;PEXPIRE&#39;, key, window)<br>    return 1 -- Allowed<br>else<br>    return 0 -- Throttled<br>end<br>&quot;&quot;&quot;<br>class RedisRateLimiter:<br>    def __init__(self, redis_pool: Redis, key: str, max_requests: int, window_ms: int):<br>        self.redis = redis_pool<br>        self.key = key<br>        self.max_requests = max_requests<br>        self.window_ms = window_ms<br>        <br>    async def acquire(self):<br>        while True:<br>            now_ms = int(time.time() * 1000)<br>            req_id = f&quot;{now_ms}-{id(self)}&quot; # Cheap unique ID<br>            <br>            allowed = await self.redis.eval(<br>                LUA_SLIDING_WINDOW, <br>                1, <br>                self.key, <br>                self.window_ms, <br>                self.max_requests, <br>                now_ms, <br>                req_id<br>            )<br>            <br>            if allowed == 1:<br>                return<br>            # Wait before polling again. In a real system, you&#39;d calculate <br>            # exact sleep time based on the oldest element in the ZSET.<br>            await asyncio.sleep(0.05) <br>async def fetch_single_distributed(session, url, limiter):<br>    # Using the same tenacity retry decorator conceptually<br>    await limiter.acquire()<br>    async with session.get(url) as response:<br>        response.raise_for_status()<br>        return await response.json()<br># Execution involves passing the initialized RedisRateLimiter to all tasks.</pre><h4><strong>Why this works at Level 3:</strong></h4><p>We have elevated our state to an external, atomic truth source. No matter how many Celery workers, Gunicorn processes, or bare scripts are running on this host, they all must consult Redis. The Lua script guarantees mathematical precision over the request rate.</p><h4><strong>Where it breaks:</strong></h4><p>The shift to a distributed system. Once you scale out to 50 worker nodes across three distinct AWS Availability Zones (AZs), this locking mechanism becomes a severe liability.</p><p>Network latency between your workers in us-east-1a and your centralized Redis cluster in us-east-1b might be 2-5 milliseconds. The constant polling (await asyncio.sleep(0.05)) against Redis by 50 aggressive nodes will saturate your network bandwidth and spike Redis CPU usage. Worse, as multiple nodes acquire locks and experience variable network jitter, they will fire requests in uneven bursts, potentially triggering vendor algorithms that flag micro-bursts (e.g., hitting all 10 requests in a 10ms window, leaving the remaining 990ms idle).</p><h3>Level 4: Distributed System</h3><p>At massive scale, architectures must shift paradigms. Requesting permission to perform an action (Locking/Polling) scales poorly. We must transition to a Streaming/Queuing architecture.</p><p>We completely invert the control flow. The 50 worker nodes no longer govern the rate limit. Instead, they act as blind execution engines. We introduce a centralized message broker, such as Kafka or RabbitMQ, to orchestrate the flow of time.</p><h4>The Architecture</h4><ul><li><strong>The Producers:</strong> Your application logic (web endpoints, cron jobs) drops URLs into a Kafka topic named api_outbound_requests. They do not execute HTTP calls; they only publish intent.</li><li><strong>The Broker:</strong> Kafka holds the URLs durably. If your entire cluster crashes, no data is lost.</li><li><strong>The Pacer (The Dispatcher):</strong> A highly specialized, singleton service reading from Kafka. Its <em>only</em> job is to pull messages from Kafka and push them into the worker queues at a strict, metered rate of exactly 10 requests per second.</li><li><strong>The Consumers (Workers):</strong> Your 50 worker nodes listen to a secondary, high-throughput queue (e.g., RabbitMQ or an in-memory stream managed by the Pacer). When they receive a message, they execute the HTTP call immediately without checking any locks.</li></ul><h4>Handling the 5% Failure Rate in a Distributed Broker</h4><p>When a worker node experiences the 5% 5xx error, we cannot simply use an in-memory tenacity loop. If a node holds a message for 10 seconds of exponential backoff, it blocks the Kafka partition, dragging down total system throughput.</p><p>Instead, we use a <strong>Dead Letter Queue (DLQ) / Retry Topic Pattern</strong>:</p><ul><li>If Worker Node #47 fails to fetch a URL, it acknowledges the message (removing it from the main queue) and publishes it to a new Kafka topic: api_retry_1.</li><li>A separate consumer listens to api_retry_1, which inherently has a delayed processing configuration, or uses a scheduler to push the message back into the main stream after the backoff period.</li></ul><p>This architecture fundamentally resolves the rate limiting issue without shared locks. A single, unified stream controls the velocity of the system.</p><h4>The CAP Theorem Reality</h4><p>This architecture forces a confrontation with the CAP theorem. If network connectivity between your data center and the Kafka broker partitions, you must choose between Consistency and Availability.</p><ul><li>Do you let the workers keep firing HTTP requests using cached, local rate limiters (Availability), risking thousands of 429 errors and a vendor ban?</li><li>Or do you halt all outbound requests until the broker is reachable (Consistency), guaranteeing strict compliance but degrading your own application’s uptime?</li></ul><p>In third-party API integration, the vendor holds the ultimate authority. Breaching their rate limit often results in cryptographic IP bans. Therefore, you must favor <strong>Consistency</strong>. If the broker is unreachable, the system must fail closed and cease all outbound traffic.</p><h3>The Interviewer’s Perspective</h3><p>Major technology companies frequently use variations of this fetch_all problem in systems design and coding rounds. When interviewing for mid-to-senior level roles (e.g., SDE-2 or L4), the panel is not assessing if you know the requests syntax. They are hunting for specific engineering signals.</p><h4><strong>What an L4/SDE-2 Panel is Looking For:</strong></h4><ul><li><strong>Understanding of Concurrency vs. Parallelism:</strong> An automatic rejection often occurs if a candidate tries to solve I/O blocking by spawning unbound threads (threading.Thread(target=fetch) in a loop). An L4 candidate must articulate why asynchronous I/O is the correct tool for network waiting.</li><li><strong>The Semaphore Trap:</strong> As detailed in Level 2, proposing a Semaphore as a rate limiter is a fatal flaw. Demonstrating knowledge of the Token Bucket or Leaky Bucket algorithm proves you understand flow control over time, not just spatial memory limits.</li><li><strong>Idempotency and State:</strong> The interviewer will ask, “What if the power goes out halfway through the list?” A junior engineer scrambles to write the remaining array to a text file. A senior candidate immediately discusses idempotency making sure the API call is safe to repeat (e.g., using a unique Idempotency-Key in the HTTP header) and storing state in a durable queue.</li><li><strong>Observability:</strong> Top candidates don’t just write except Exception as e: print(e). They specify structured logging, emitting metrics to Prometheus/Datadog on HTTP status codes, and tracking the p99 latency of the external API.</li></ul><h4><strong>Red Flags:</strong></h4><ul><li>Writing custom retry logic instead of using established backoff libraries.</li><li>Failing to distinguish between client-side errors (4xx) and server-side errors (5xx). Retrying a 401 Unauthorized is a waste of compute.</li><li>Assuming the network is reliable.</li></ul><h3>Bigger Perspective</h3><p>You must look past the codebase and evaluate the macro-architectural impact, financial cost, and organizational debt. An engineer interrogates the system with questions that lack binary answers.</p><p><strong>1. Backpressure and Cascade Failures</strong></p><p>“What happens when the vendor API experiences a hard outage for 6 hours?”</p><p>If our Kafka queue continues to accept intent from upstream microservices, the topic will bloat. When the vendor recovers, we will have a backlog of millions of messages. Processing them at 10 requests per second will take days. How do we implement intelligent load shedding? Do we implement a Circuit Breaker pattern that trips and instantly rejects incoming requests from our own UI rather than queuing them indefinitely?</p><p><strong>2. Multi-Tenant Fairness</strong></p><p>“Our platform has 5,000 customers. Customer A uploads a batch of 100,000 URLs. Customer B uploads 5 URLs. Because we use a FIFO Kafka queue, Customer B’s request is stuck behind 2.7 hours of Customer A’s processing. How do we ensure fairness?”</p><p>This requires designing round-robin partition reading, priority queues, or dynamic throttling per tenant to ensure a single aggressive user does not monopolize the global 10 req/s allocation.</p><p><strong>3. The Cost of the Retry Storm</strong></p><p>“A 5% failure rate on 10,000,000 daily requests means we are executing 500,000 useless network calls, burning our own egress bandwidth and compute.”</p><p>At what point do we stop trusting the vendor’s SLA? Should we implement an adaptive backoff that slows down the <em>entire</em> system reducing our baseline rate to 2 req/s — when we detect the 5xx rate climbing above 2%, giving the vendor room to breathe?</p><p><strong>4. Synchronous Illusions on the Frontend</strong></p><p>“A user clicks ‘Sync Data’ in our React frontend. They expect an immediate result, but our backend pushed the job to a Kafka queue constrained to 10 req/s.”</p><p>How do we model this asynchronous reality to the user? We must design a robust polling mechanism, Server-Sent Events (SSE), or WebSockets to stream the eventual consistency back to the client, bridging the gap between a fast UI and a deliberately bottlenecked distributed backend.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=03b8534cc195" width="1" height="1" alt=""><hr><p><a href="https://blog.stackademic.com/handling-external-service-rate-limiting-and-failures-in-ditributed-system-03b8534cc195">Handling External Service Rate Limiting and Failures in Distributed System</a> was originally published in <a href="https://blog.stackademic.com/">Stackademic</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Gossip Protocol: How thousand node communicate]]></title>
            <link>https://sameerahmed56.medium.com/gossip-protocol-how-thousand-node-communicate-463d64803867?source=rss-e4526effdd7c------2</link>
            <guid isPermaLink="false">https://medium.com/p/463d64803867</guid>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[system-design-interview]]></category>
            <category><![CDATA[gossip-protocol]]></category>
            <category><![CDATA[design-systems]]></category>
            <category><![CDATA[software-engineering]]></category>
            <dc:creator><![CDATA[Sameer Ahmed]]></dc:creator>
            <pubDate>Sun, 05 Apr 2026 00:41:06 GMT</pubDate>
            <atom:updated>2026-04-05T00:41:06.562Z</atom:updated>
            <content:encoded><![CDATA[<p>The protocol which builds distributed databases.</p><p>Imagine you are managing a database cluster with five nodes. How do they know which nodes are alive? Easy. You have them ping each other every second. Node A pings B, C, D, and E. Node B pings A, C, D, and E.</p><p>In computer science, this is an <strong>O(N²)</strong> communication complexity. For 5 nodes, that’s 25 network connections. It works perfectly.</p><p>Now, imagine you are Amazon. You are running DynamoDB across 10,000 nodes. If every node pings every other node every second, that is 100,000,000 network calls per second just to say, <em>“Hey, I’m still here.”</em> Your network switches will physically melt. The entire bandwidth of your data center will be consumed by servers taking attendance.</p><p>You can’t use a centralized registry (like a single master server that keeps track of everyone) because if that master server dies, the entire 10,000-node cluster suffers total amnesia and collapses.</p><p>So, how do thousands of independent machines maintain a shared understanding of the world without a central coordinator and without DDOSing themselves?</p><p>They act like human beings in a corporate office. They use the <strong>Gossip Protocol</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*AV-5ukJg-PoW_FzR" /></figure><h3>Part 1: The working of Distributed Systems</h3><p>The Gossip Protocol (often formally called an <em>Epidemic Protocol</em>) was literally derived from mathematical biology. It models how a highly contagious virus spreads through a population, or how a juicy rumor spreads through a high school.</p><p>The core philosophy is radically simple: <strong>A node does not talk to everyone. It only talks to a few random neighbors.</strong></p><p>Here is the exact lifecycle of a Gossip event:</p><ol><li><strong>The Spark:</strong> Node A receives a piece of new information (e.g., “Node Z just crashed” or “User 123 updated their password”).</li><li><strong>The Infection:</strong> Every second (the “tick” or “gossip interval”), Node A randomly selects <strong>k</strong> other nodes from its address book. <strong>k</strong> is called the <strong>Fanout</strong> (typically a small number, like 3).</li><li><strong>The Transmission:</strong> Node A sends the new information to those 3 random nodes.</li><li><strong>The Epidemic:</strong> In the next second, Node A, plus the 3 newly infected nodes, all pick 3 <em>more</em> random nodes and spread the message.</li></ol><p>Even in a cluster of 10,000 nodes, the mathematics of exponential growth guarantee that the entire cluster will receive the message in a fraction of a second.</p><p>Because the spread is exponential, the time it takes for a message to reach every node in a network of size <strong>N </strong>is logarithmic: O(log N).</p><p>If it takes 4 rounds to infect 100 nodes, it only takes roughly 7 rounds to infect 1,000 nodes, and 14 rounds to infect 10,000 nodes. The system scales beautifully.</p><h4>The Math Behind the Madness</h4><p>If we want to get truly rigorous, we model this using the <strong>SIR Model</strong> from epidemiology:</p><ul><li><strong>S (Susceptible):</strong> Nodes that don’t know the rumor yet.</li><li><strong>I (Infective):</strong> Nodes that know the rumor and are actively spreading it.</li><li><strong>R (Removed/Recovered):</strong> Nodes that know the rumor but have stopped spreading it (because they realized everyone else already knows).</li></ul><p>The rate at which the network becomes infected is governed by a set of differential equations:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/350/1*FqBFjGX8jqvfsF_ujfkmyw.png" /></figure><p>Where beta is the infection rate (how many nodes we contact per tick) and gamma is the removal rate.</p><p>The beauty of this math is that it proves <strong>fault tolerance</strong>. Even if 20% of your network cables are randomly severed, the protocol routes around the damage organically. There are no fixed paths to break. As long as the network isn’t completely partitioned into two isolated islands, the virus <em>will</em> infect the host.</p><h3>Part 2: The Three Mechanics of Gossip</h3><p>When we actually implement this in code, we don’t just blindly scream into the void. Nodes have to agree on <em>how</em> they exchange information. There are three paradigms:</p><h4>1. Push Gossip (The Rumor Monger)</h4><p>Node A has new data. It randomly picks Node B and pushes the data to it.</p><ul><li><strong>The Good:</strong> Incredibly fast at the beginning of an epidemic when almost nobody knows the rumor.</li><li><strong>The Bad:</strong> Terrible at the end. When 99% of the cluster is already infected, Node A is just blindly pushing data to nodes that already have it, wasting network bandwidth.</li></ul><h4>2. Pull Gossip (The Curious Neighbor)</h4><p>Node A randomly picks Node B and asks, <em>“Do you have any new updates that have happened since timestamp X?”</em> Node B replies with the delta.</p><ul><li><strong>The Good:</strong> Extremely efficient at the end of an epidemic. If Node A is the only node that missed the message, it will proactively pull it from someone who has it.</li><li><strong>The Bad:</strong> Horribly slow at the beginning. If only Node Z has the rumor, it takes a long time for someone to randomly ask Node Z for it.</li></ul><h4>3. Push-Pull Gossip (The Industry Standard)</h4><p>To solve the trade-offs, production systems use Push-Pull.</p><p>Node A sends a digest (a tiny cryptographic hash or version vector) of its current state to Node B.</p><p>Node B looks at the digest, compares it to its own state, and says, <em>“Ah! You have a newer version of the topology than I do, but I have a newer user record than you do.”</em> They then exchange exactly the missing pieces.</p><h3>Part 3: Anti-Entropy vs. Rumor Mongering</h3><p>Gossip protocols are generally split into two distinct sub-categories based on what they are trying to achieve.</p><h4>Rumor Mongering (Dissemination)</h4><p>This is used for high-frequency, transient events. Think of a Twitter trending topic.</p><p>When a new node joins the cluster, it wants to broadcast its arrival. It generates a “Rumor.” The nodes gossip this rumor aggressively. However, to save bandwidth, a node will stop gossiping the rumor once it randomly contacts a few nodes that already know it (entering the ‘Recovered’ state in our SIR model).</p><p>Because nodes eventually stop broadcasting, there is a tiny, non-zero mathematical probability that a rumor dies out before reaching 100% of the cluster.</p><h4>Anti-Entropy (State Synchronization)</h4><p>This is the heavy artillery. Anti-entropy doesn’t just broadcast events; it compares the <em>entire state</em> of the system to ensure absolute eventual consistency.</p><p>Every node periodically picks a random peer and compares their entire internal database (usually using something called a <strong>Merkle Tree</strong>, which is a tree of cryptographic hashes that allows you to find mismatched data with O(log N) comparisons).</p><p>If a node was completely severed from the network for an hour, Rumor Mongering would fail it. Anti-Entropy guarantees that when the node reconnects, it will magically heal its state by comparing Merkle Trees with its neighbors.</p><h3>Part 4: The Masterpiece: The SWIM Protocol</h3><p>If you want to understand how Gossip is used to solve real-world architectural nightmares, we have to look at <strong>SWIM (Scalable Weakly-consistent Infection-style Process Group Membership Protocol)</strong>.</p><p>SWIM is the protocol that powers HashiCorp’s Consul (via Serf) and allows thousands of microservices to discover each other instantly.</p><p>Remember our O(N²) pinging problem at the beginning? SWIM uses Gossip to fix failure detection.</p><p>Here is how a SWIM node determines who is dead and who is alive:</p><ol><li><strong>The Direct Ping:</strong> Every second, Node A picks exactly <em>one</em> random node from its list (let’s say Node B). It sends a direct UDP PING to Node B.</li><li><strong>The Happy Path:</strong> Node B receives the ping and instantly fires back an ACK. Node A marks Node B as &quot;Alive.&quot; Network load is tiny O(1) per node per second).</li><li><strong>The Suspicion:</strong> What if Node B doesn’t respond? Node A doesn’t immediately declare Node B dead. Network packets get dropped all the time. Instead, Node A marks Node B as Suspicious.</li><li><strong>The Indirect Ping (The Genius Move):</strong> Node A randomly selects 3 <em>other</em> nodes (C, D, and E). It sends them a PING-REQ(B) message. It is essentially asking, <em>&quot;Hey guys, I can&#39;t reach B. Can you try calling him for me?&quot;</em></li><li><strong>The Proxy:</strong> Nodes C, D, and E all fire independent direct PINGs to Node B.</li><li><strong>The Verdict:</strong> If Node B was just ignoring Node A because of a bad local network switch, but it responds to Node C, Node C forwards the ACK back to Node A. Node A clears the suspicion. Node B lives.</li><li><strong>The Gossip:</strong> If <em>nobody</em> can reach Node B, Node A declares Node B DEAD. It then packages this &quot;Node B is Dead&quot; message into a Rumor, and injects it into the Gossip Protocol. Within milliseconds, the entire 10,000-node cluster knows to stop routing traffic to Node B.</li></ol><p>SWIM completely eliminates the O(N²) heartbeat problem while maintaining a deterministic, mathematically provable failure detection time, completely immune to isolated network packet drops. It is one of the most elegant algorithms in modern infrastructure.</p><h3>Part 5: Real-World Implementations</h3><p>Let’s look at where you are actually using this right now without realizing it.</p><p><strong>1. Apache Cassandra (Topology &amp; Schema)</strong></p><p>Cassandra is a masterless database. Any node can accept a write. But if you execute CREATE TABLE on Node 1, how do Nodes 2 through 100 know the table exists?</p><p>Cassandra uses a Gossip protocol running every second. Nodes exchange “Endpoint State” (who is alive, what their IP addresses are, how much disk space they have) and “Schema State.” If Node 1 bumps its schema version to v2, it gossips this. Node 5 sees v2, realizes it is on v1, and immediately initiates a pull request to fetch the new DDL.</p><p><strong>2. Amazon DynamoDB &amp; Riak</strong></p><p>Dynamo completely pioneered this space in its original 2007 whitepaper. It uses Gossip for cluster membership and failure detection, allowing Amazon’s shopping cart to survive massive datacenter outages organically.</p><p><strong>3. Bitcoin &amp; Blockchain</strong></p><p>When you submit a Bitcoin transaction, you do not send it to a central server. You submit it to a random node you are connected to. That node verifies it and gossips it to its peers. Those peers gossip it to their peers. Within seconds, tens of thousands of mining rigs across the globe have your transaction in their memory pools, all coordinated entirely by pure Gossip.</p><h3>Part 6: The Sharp Edges (Why You Don’t Build This Yourself)</h3><p>If I catch a mid-level engineer trying to implement a Gossip protocol from scratch in their microservices, I will immediately shut down the PR. Gossip is breathtakingly elegant on paper, but it is a chaotic nightmare to debug in production.</p><p>Here are the critical trade-offs you must accept if you use systems built on Gossip:</p><p><strong>1. Eventual Consistency is Mandatory</strong></p><p>By definition, Gossip takes time to spread. If you write a piece of data to Node A, there is a physical window of time (microseconds to milliseconds) where Node B does not have that data. If a user reads from Node B during that window, they get stale data. You cannot use Gossip for distributed locking or financial transactions.</p><p><strong>2. The “Network Storm” Vulnerability</strong></p><p>If your fanout factor <strong>k </strong>is too high, or your gossip interval is too aggressive, you will accidentally DDOS your own network. This happened frequently in early versions of these systems. A brief network partition would occur, nodes would queue up massive backlogs of state changes, the partition would heal, and the nodes would suddenly vomit gigabytes of Gossip data at each other, saturating the network cards and taking the whole cluster offline.</p><p><strong>3. Debugging is Inherently Non-Deterministic</strong></p><p>If a bug causes a bad piece of state to propagate, tracing the root cause is like trying to trace who Patient Zero was in a global pandemic. Because nodes talk to random peers, the execution path is completely different every single time. Traditional linear logging is useless. You have to rely on complex vector clocks and distributed tracing to reconstruct the crime scene.</p><p><strong>4. The “Zombie Node” Problem</strong></p><p>Imagine Node A dies. The cluster gossips that Node A is dead. A week later, you accidentally boot Node A back up with its old hard drive. Node A starts gossiping its old, outdated state (which it thinks is current). If your versioning vectors aren’t perfectly airtight, Node A’s stale data can “re-infect” the cluster, resurrecting deleted rows. This is why systems like Cassandra require strict procedures (like nodetool removenode) to permanently execute a node.</p><h3>The Verdict</h3><p>The Gossip Protocol represents a fundamental philosophical shift in system design. It is the admission that at a certain scale, strict control is impossible. You cannot micromanage 10,000 servers. Instead, you have to engineer the environment, define the rules of interaction, and let the system organically manage itself through the mathematics of chaos.</p><p>When you need strong, immediate consistency — like ensuring only one microservice can process a specific bank transfer at a time Gossip is the wrong tool. You need strict, centralized coordination.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=463d64803867" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Change Data Capture (CDC)]]></title>
            <link>https://sameerahmed56.medium.com/change-data-capture-cdc-373a36e1656e?source=rss-e4526effdd7c------2</link>
            <guid isPermaLink="false">https://medium.com/p/373a36e1656e</guid>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[database]]></category>
            <category><![CDATA[system-design-interview]]></category>
            <category><![CDATA[change-data-capture]]></category>
            <category><![CDATA[design-systems]]></category>
            <dc:creator><![CDATA[Sameer Ahmed]]></dc:creator>
            <pubDate>Sat, 14 Mar 2026 01:33:38 GMT</pubDate>
            <atom:updated>2026-03-14T01:33:38.041Z</atom:updated>
            <content:encoded><![CDATA[<p>We need to talk about the most terrifying phrase in distributed systems: <strong>The Dual Write</strong>.</p><p>Grab a Tea 🍵.<br>If you are building a modern, decoupled architecture, you are eventually going to hit a wall that has broken thousands of senior engineers before you. It usually happens right around the time you realize your primary database can’t do everything.</p><p>Let me paint a picture. Let’s say we are building a Proposal/Dating Web App. We have a slick React frontend and a Node.js backend. When a user updates their dating profile maybe they change their bio or swipe “Yes” on someone , our Node backend needs to do a few things:</p><ol><li>Save the updated profile to our primary PostgreSQL database so it’s safely stored.</li><li>Update our Elasticsearch cluster so other users can immediately find them when filtering by interests.</li><li>Send an event to our Python-based Matching Engine to recalculate their compatibility scores.</li></ol><p>So, the junior engineer on the team writes this code:</p><pre>async function updateUserProfile(userId, data) {<br>    // 1. Save to Postgres<br>    await db.query(&#39;UPDATE profiles SET bio = $1 WHERE id = $2&#39;, [data.bio, userId]);<br>    <br>    // 2. Update Elasticsearch<br>    await elasticSearch.update({ id: userId, bio: data.bio });<br>    <br>    // 3. Notify the Matching Engine via RabbitMQ or Kafka<br>    await messageBroker.publish(&#39;profile_updates&#39;, { id: userId, bio: data.bio });<br>    <br>    return { success: true };<br>}</pre><p>It looks clean. It makes logical sense. It will absolutely destroy your data integrity in production.</p><h3>The Nightmare of the Dual Write</h3><p>What happens if line 1 succeeds, but line 2 fails because Elasticsearch is doing a garbage collection pause? Now your primary database says the user likes “hiking,” but the search engine still says they like “couch surfing.”</p><p>“No problem,” you say. “I’ll just wrap it in a try/catch and rollback the database if the search engine fails!&quot;</p><p>Okay, but what if line 1 and 2 succeed, but your Node server literally loses power and crashes <em>before</em> line 3 executes? The database is updated. The search index is updated. The Matching Engine never gets the memo. Your system is now permanently fractured.</p><p>You cannot wrap a database commit, an HTTP call to a search engine, and a TCP call to a message broker in a single atomic transaction. The network will fail you.</p><p>So, how do we fix this? Historically, engineers tried <strong>Polling</strong>. They would add an updated_at timestamp to the Postgres table. Then, a cron job would run every 5 seconds: SELECT * FROM profiles WHERE updated_at &gt; NOW() - 5 seconds. It would grab the changed rows and push them to Elastic and Kafka.</p><p>Polling is garbage. It puts a massive, constant CPU load on your primary database. Worse, it completely misses hard deletes. If a user deletes their dating profile, the row is gone. The polling query will never see it. The user will be gone from Postgres, but their ghost will live on in Elasticsearch forever, showing up in other people’s matches.</p><p>This brings us to the holy grail of data consistency: <strong>Change Data Capture (CDC)</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*_zo5cnA7gMrxO8OY" /></figure><h3>Hijacking the Database’s Brain</h3><p>To understand CDC, you have to understand how relational databases actually save data.</p><p>When you tell PostgreSQL to UPDATE profiles..., it doesn&#39;t immediately go find the user on the hard drive and overwrite the text. Searching a massive hard drive is slow.</p><p>Instead, Postgres writes that command down in a sequential, append-only file called the <strong>Write-Ahead Log (WAL)</strong>. (In MySQL, it’s called the binlog and in Mongo, the oplog. The database essentially says, <em>&quot;I promise I will update the actual hard drive later, but for now, I have safely written down the intention to do so.&quot;</em> If the server crashes 3 seconds later, when it reboots, it just reads the WAL and reapplies the changes.</p><p>The WAL is the absolute, ground-truth history of everything that has ever happened to your database.</p><p><strong>Change Data Capture</strong> is the technique of tapping directly into that transaction log. Instead of our Node.js app trying to coordinate updates to Elastic and Kafka, our Node app does exactly one thing: It writes to Postgres.</p><p>Then, a separate CDC tool usually <strong>Debezium</strong>, which is the undisputed king of this space connects to Postgres. Debezium disguises itself as a database replica. Postgres thinks, <em>“Oh, you’re a backup database! Here, let me stream every single change from my WAL to you as it happens.”</em></p><p>Debezium takes that raw stream of database changes, formats it into beautiful JSON events, and pushes those events directly into Apache Kafka.</p><h3>CDC Implementation Approaches</h3><p>How did we arrive at WAL-based CDC? We got here because everything else we tried ended in tears. If you are debating how to synchronize data between a primary database and a secondary system (like a Python-based matching engine, a Redis cache, or an Elasticsearch cluster), here are the evolutionary stages you will go through:</p><h4>Approach 1: Polling (The Timestamp Hack)</h4><p>You add an updated_at timestamp column to every table. You write a script that wakes up every 10 seconds, runs SELECT * FROM table WHERE updated_at &gt; last_check, and publishes the results.</p><ul><li><strong>Why it fails:</strong> It is brutal on your database CPU. It delays data sync by up to 10 seconds. And most fatally, <strong>it cannot detect deletes</strong>. If a row is deleted, it’s gone. The polling query will never see it, and your downstream systems will retain a ghost record forever.</li></ul><h4>Approach 2: Database Triggers (The DBA’s Nightmare)</h4><p>You write a literal SQL Trigger on the table: AFTER UPDATE ON users EXECUTE FUNCTION write_to_audit_table(). Your application polls the audit table, reads the changes, and then deletes them.</p><ul><li><strong>Why it fails:</strong> Triggers execute <em>synchronously</em> within the exact same transaction as your original update. If your trigger logic takes 50 milliseconds to run, you just added 50 milliseconds of latency to your user’s API request. Under heavy load, triggers will cause lock contention and bring your database to its knees.</li></ul><h4>Approach 3: Dual Writes (The Distributed Monolith)</h4><p>Your application code tries to play traffic cop. await db.update(); await elasticSearch.update(); await kafka.publish();</p><ul><li><strong>Why it fails:</strong> Network partitions. If the database update succeeds but the Kafka publish times out, your systems are out of sync. You can never mathematically guarantee consistency across disparate systems in application code without implementing insanely complex Two-Phase Commits (2PC), which ruin performance.</li></ul><h4>Approach 4: Log-Based CDC (The Holy Grail)</h4><p>You do none of the above. Your application writes <em>only</em> to the primary database and immediately returns. A separate, dedicated infrastructure component reads the WAL asynchronously and reliably publishes the events to a message broker.</p><ul><li><strong>Why it wins:</strong> It is 100% invisible to your application code. It adds zero latency to your API. It captures every single insert, update, and hard delete. It guarantees strict chronological ordering.</li></ul><h3>The CDC Event</h3><p>When a user updates their bio, Debezium doesn’t just say “User 5 was updated.” It gives you the entire story. The Kafka payload looks something like this:</p><pre>{<br>  &quot;op&quot;: &quot;u&quot;, <br>  &quot;before&quot;: {<br>    &quot;id&quot;: 5,<br>    &quot;bio&quot;: &quot;Couch surfing champion.&quot;<br>  },<br>  &quot;after&quot;: {<br>    &quot;id&quot;: 5,<br>    &quot;bio&quot;: &quot;I love hiking!&quot;<br>  },<br>  &quot;source&quot;: {<br>    &quot;db&quot;: &quot;dating_app&quot;,<br>    &quot;table&quot;: &quot;profiles&quot;,<br>    &quot;txId&quot;: 84920<br>  }<br>}</pre><p>Look at how powerful that is. You get the before state and the after state. The op tells you if it was an insert (i), update (u), or delete (d).</p><h3>Solving the Problems Polling Couldn’t</h3><p>Remember the two massive problems we had before?</p><p><strong>1. The Crash Problem:</strong> What if our Node app crashes immediately after saving to Postgres? It doesn’t matter. The transaction is safely in the Postgres WAL. Debezium reads it directly from the disk log and pushes it to Kafka. Kafka holds it safely. Even if the Elasticsearch worker is offline for maintenance, the event waits in Kafka. When the worker boots up, it reads the CDC event and updates the index. <em>Eventual consistency is guaranteed.</em></p><p><strong>2. The Hard Delete Problem:</strong> If a user rage-quits the app and deletes their profile, Postgres removes the row. But the WAL records a delete operation. Debezium captures this and sends a CDC event with &quot;op&quot;: &quot;d&quot; and an empty after state (often called a &quot;tombstone&quot; message). Your downstream consumers see the tombstone and know exactly who to purge from the search index and the matching engine. No more ghost profiles.</p><h3>The Real-World Architecture</h3><p>If we were whiteboarding this Dating Web App today, here is exactly how I would structure it:</p><ul><li><strong>The Core App:</strong> The React frontend hits the Node API. The API validates the business logic and executes a single SQL transaction against PostgreSQL. The API instantly returns 200 OK to the user. The UI feels blazingly fast.</li><li><strong>The Veins (Debezium + Kafka):</strong> Debezium is silently monitoring Postgres. Within milliseconds of the commit, Debezium streams the change event into a Kafka topic named postgres.dating_app.profiles.</li><li><strong>The Consumers: <br>- </strong>An indexing microservice is subscribed to that topic. It reads the event and pushes the new bio to Elasticsearch.<br>- A Python worker is also subscribed to that exact same topic. It sees the bio change, runs a quick NLP (Natural Language Processing) check, and updates the user’s personality vector in a vector database for better matching.</li></ul><p>We have completely decoupled our systems. The Node API doesn’t know Elasticsearch exists. It doesn’t know the Python matching engine exists. You can add ten new microservices tomorrow maybe an analytics engine or an email marketing trigger and they just hook into the Kafka CDC stream without you ever touching the core Node.js codebase.</p><h3>The Cost Of Using CDC</h3><p>I’m not going to sit here and tell you CDC is magic without warning you about the sharp edges. When you adopt CDC, you are coupling your microservices directly to your database schema.</p><p>Think about it. If your Python worker expects the CDC event to contain a bio field, and a junior backend engineer decides to rename that column in Postgres to description and runs a database migration... everything breaks. The Node app updates description, Debezium faithfully streams the description change, and the Python worker crashes because it&#39;s looking for bio.</p><p>By exposing your database tables to the rest of your architecture, your database schema essentially becomes your public API contract.</p><p>To mitigate this, mature engineering teams often use the <strong>Outbox Pattern</strong> alongside CDC. Instead of Debezium tailing the profiles table directly, the Node app writes the profile update to the profiles table, and <em>in the exact same SQL transaction</em>, it inserts a JSON event payload into a dedicated outbox_events table.</p><p>Debezium then tails <em>only</em> the outbox_events table. This allows the backend engineers to refactor the internal profiles table however they want, as long as they keep writing the agreed-upon JSON structure into the outbox. It creates a firewall between your raw data schema and your event consumers.</p><h3>Real-World Use Cases</h3><p>Once you have this raw stream of truth flowing into Kafka, your entire architectural mindset shifts. Here is what Engineers actually use CDC for in the wild:</p><p><strong>1. The Bulletproof Cache Invalidation</strong> Caching is famously one of the two hardest problems in computer science. How do you ensure your Redis cache doesn’t serve stale data?</p><ul><li><em>The Old Way:</em> Your Node app updates Postgres, then manually deletes the key in Redis. If the Redis call fails, you serve stale data.</li><li><em>The CDC Way:</em> Your Node app only updates Postgres. A dedicated Cache Invalidator service listens to the Debezium Kafka topic. When it sees an &quot;op&quot;: &quot;u&quot; for user 1042, it evicts user:1042 from Redis. Your application code is completely scrubbed of caching logic.</li></ul><p><strong>2. The CQRS Pattern (Command Query Responsibility Segregation)</strong> Let’s say your dating app allows complex spatial queries (“Find active users within 5 miles who like dogs, sorted by match percentage”). Postgres is terrible at this at scale. Elasticsearch is perfect for it. With CDC, Postgres is your <strong>Command Model</strong> (where writes happen securely). Debezium streams those writes into Kafka, and an indexing worker formats them and dumps them into Elasticsearch, which becomes your <strong>Query Model</strong> (where reads happen instantly).</p><p><strong>3. The Unbreakable Audit Log</strong> Compliance department needs a history of every time a user’s subscription status changed over the last 5 years? If you just overwrite the row in Postgres, that history is gone. With CDC, you route the subscriptions Kafka topic into an AWS S3 data lake or Snowflake. Because Kafka holds the immutable log of every before and after state, you have a mathematically perfect, legally binding audit trail built for free.</p><p><strong>4. Triggering Complex Domain Logic (The Matchmaker)</strong> When a user updates their preferences, your Python matching algorithm needs to recalculate their compatibility vectors. Instead of the Node API making a synchronous REST call to the Python service (which might time out), the Python service just tails the Kafka topic. It reacts to the data changing in real-time, completely decoupled from the web frontend.</p><p>CDC isn’t just a tool; it’s a fundamental shift in how you think about state. Your database is no longer just a static bucket where data sits. It becomes a beating heart, pumping state changes out to the rest of your nervous system in real-time.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=373a36e1656e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Database Indexing: The Performance Trick Nobody Explained Properly]]></title>
            <link>https://blog.stackademic.com/why-physics-matter-when-creating-database-index-ecb74f879b5d?source=rss-e4526effdd7c------2</link>
            <guid isPermaLink="false">https://medium.com/p/ecb74f879b5d</guid>
            <category><![CDATA[database-indexing]]></category>
            <category><![CDATA[design-systems]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[system-design-interview]]></category>
            <category><![CDATA[web-development]]></category>
            <dc:creator><![CDATA[Sameer Ahmed]]></dc:creator>
            <pubDate>Mon, 09 Mar 2026 19:04:24 GMT</pubDate>
            <atom:updated>2026-06-01T06:56:16.205Z</atom:updated>
            <content:encoded><![CDATA[<p>Single most misunderstood, abused, and critical component of database performance: <strong>The Index</strong>.</p><p>Understanding indexes is the difference between an application that falls over at 10,000 users and an application that hums along effortlessly at 10 million.</p><p>Most tutorials will give you the “phonebook” analogy. They’ll say, <em>“An index is like the index at the back of a book!”</em> That is a cute explanation for a junior engineer, but it is dangerously incomplete for a Senior Engineer. If you actually want to master distributed systems, you have to understand exactly what the database engine is doing with the physical hard drive.</p><p>We are going to go all the way to the metal. We’ll look at how data is stored on disk, the actual data structures that make indexing possible, how to design composite indexes that cheat the system, and why your database will sometimes look at your beautiful index and maliciously choose to ignore it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/0*W5MPGRgx5ryy4oC3.png" /></figure><h3>The Reality of the Hard Drive</h3><p>To understand the solution, you must deeply understand the problem.</p><p>When you write a SQL query like SELECT * FROM users WHERE email = &#39;test@example.com&#39;, the database does not magically know where that data is.</p><p>A database table is, physically, just a massive file (or series of files) sitting on a hard drive (SSD or NVMe these days). But the database doesn’t read the hard drive row by row. It reads the hard drive in chunks called <strong>Pages</strong> or <strong>Blocks</strong> (usually 8KB or 16KB in size).</p><p>Imagine your table has 10 million rows. Those rows are packed tightly into thousands of 8KB Pages on the disk.</p><p>If you don’t have an index, the database has absolutely no choice but to perform a <strong>Sequential Scan</strong> (or Full Table Scan).</p><ol><li>The database asks the OS to fetch Page 1 from the disk into RAM.</li><li>It scans every row in Page 1. <em>“Is this test@example.com? No. No. No.”</em></li><li>It drops Page 1, fetches Page 2.</li><li>It repeats this process until it has dragged all 10 million rows off the disk, through the CPU cache, just to find that one single row.</li></ol><p>In computer science, this is <strong>O(N)</strong> time complexity. It scales linearly with your data. On a small table, it’s instantaneous. On a 50GB table, your hard drive I/O gets absolutely crushed, your RAM is flooded with useless pages, and your application times out.</p><p>We need a way to find a specific row without reading the whole file. We need to reduce disk I/O.</p><h3>The B-Tree</h3><p>If you type CREATE INDEX idx_email ON users(email);, the database does not just create a list of emails. It builds an incredibly sophisticated data structure called a <strong>B-Tree</strong> (specifically, a <strong>B+Tree</strong> in almost all modern relational databases like Postgres and MySQL).</p><p>Why a tree? Why not a hash map?</p><p>Hash maps give you <strong>O(1)</strong> lookups, which is faster! The problem is that hash maps scramble data. They are useless for range queries. If you want to find WHERE age BETWEEN 20 AND 30, a hash map cannot help you. A B+ Tree keeps data sorted, allowing for both exact matches and blazing-fast range scans.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/806/0*O-S1atEKM2K8RyAB.png" /></figure><p>Let’s look at the anatomy of this B+Tree:</p><ol><li><strong>The Root Node:</strong> The entry point at the top. It contains ranges of values and pointers to the next level down.</li><li><strong>Internal Nodes:</strong> The middle managers. They further subdivide the ranges and point to the bottom level.</li><li><strong>Leaf Nodes:</strong> The bottom layer. <strong>This is the most important part.</strong> In a B+Tree, all the actual index values (the emails we are indexing) live down here in the leaf nodes, strictly sorted in alphabetical order.</li><li><strong>The Linked List:</strong> In a B+ Tree, every leaf node has a pointer to the leaf node directly next to it. They form a doubly-linked list. This makes range scans incredibly fast.</li></ol><h4>How the Lookup Actually Works</h4><p>Let’s say you search for &#39;test@example.com&#39;.</p><ol><li>The database loads the <strong>Root Node</strong> (1 Page, 8KB) into RAM. It looks at the ranges. It sees that &#39;test&#39; falls between the pointers for &#39;s&#39; and &#39;u&#39;.</li><li>It follows that pointer and loads one <strong>Internal Node</strong> (1 Page, 8KB). It sees &#39;test&#39; falls between &#39;te&#39; and &#39;th&#39;.</li><li>It follows that pointer and loads the <strong>Leaf Node</strong> (1 Page, 8KB). It scans the sorted leaf node and finds &#39;test@example.com&#39;.</li></ol><p>Instead of scanning 10 million rows across 50,000 pages, the database found your exact email by loading exactly <strong>3 pages</strong> into memory. It traversed the tree in <strong>O(log N)</strong> time. This is the magic of indexing. The tree is incredibly “shallow” and “wide” (high fanout), meaning even a table with a billion rows rarely has a B-Tree deeper than 4 or 5 levels.</p><h3>Clustered vs. Non-Clustered Indexes</h3><p>Alright, the B+Tree found the email &#39;test@example.com&#39; in the leaf node. But your query was SELECT * FROM users. You didn&#39;t just ask for the email; you asked for the whole row (name, bio, password hash, created date).</p><p>Where is the rest of the data?</p><p>This brings us to the most critical architectural difference between databases like MySQL (InnoDB) and PostgreSQL. You must understand the difference between a Clustered Index and a Non-Clustered Index.</p><h4>The Clustered Index (Index-Organized Tables)</h4><p>In MySQL/InnoDB, every table <strong>must</strong> have a Clustered Index (usually the Primary Key).</p><p>“Clustered” means the B+Tree index <em>is</em> the table.</p><p>When you navigate down the B+Tree of the Primary Key and reach the Leaf Node, the Leaf Node doesn’t just contain the ID; it contains the <strong>entire row of data</strong>. The physical data on the hard drive is literally organized and sorted by the Primary Key. You can only have one Clustered Index per table, because the data can only be physically sorted one way.</p><h4>The Non-Clustered Index (Secondary Indexes)</h4><p>What if you search by email? email is a Secondary Index (Non-Clustered).</p><p>You traverse the idx_email B+Tree. You hit the leaf node. The rest of the row isn&#39;t there. Instead, the leaf node contains the email string and a <strong>Pointer</strong> to the actual row.</p><ul><li>In MySQL, this pointer is the Primary Key.</li><li>In Postgres (which uses heap tables rather than clustered tables), this pointer is a Tuple Identifier (TID), which is the exact physical hard drive address (Page number + Offset) of the row.</li></ul><h4>The “Double Lookup” Tax (Bookmark Lookup)</h4><p>If you use a secondary index, you pay a tax.</p><ol><li>You traverse the Email Index <strong>O(log N)</strong> to find the pointer.</li><li>You take that pointer and go to the Primary Table (or Primary Key Index) to fetch the actual row data <strong>O(log N) </strong>again, or a random disk seek).</li></ol><p>If you are querying a single user for your dating app backend, a double lookup takes less than a millisecond. Nobody cares.</p><p>But if you write a query that matches 50,000 users, and the database has to do 50,000 random disk seeks to fetch the rest of the columns… the index actually becomes slower than just scanning the whole table. (We’ll come back to this when we talk about the Optimizer).</p><h3>Mastering Composite Indexes</h3><p>Single-column indexes are for beginners. Production systems die or thrive on <strong>Composite Indexes </strong>indexes built on multiple columns.</p><p>Imagine you are building a matchmaking query for a dating application. You want to find all active female users in New York.</p><pre>SELECT * FROM users <br>WHERE status = &#39;active&#39; <br>  AND gender = &#39;F&#39; <br>  AND city = &#39;New York&#39;;</pre><p>A junior engineer will create three separate indexes: one on status, one on gender, and one on city.</p><p><strong>This is a terrible idea.</strong> Modern databases generally only use <em>one index per table per query</em> (there are exceptions like Bitmap Index Scans, but they are expensive). If you have three separate indexes, the database will pick the “best” one (maybe city), find all 500,000 users in New York, drag all 500,000 rows into memory, and manually filter out the males and inactive users.</p><p>You need a Composite Index:</p><p>CREATE INDEX idx_match ON users (status, gender, city);</p><h4>How a Composite Index Works</h4><p>Think of a composite index exactly like sorting a massive Excel spreadsheet.</p><p>If you create the index on (status, gender, city), the database sorts the entire B+Tree by status first. Then, <em>within</em> each status, it sorts by gender. Then, <em>within</em> each gender, it sorts by city.</p><p>Because of this rigid sorting hierarchy, composite indexes obey the <strong>Left-Prefix Rule</strong>.</p><p>You can only use the index if your query uses the columns from left to right without skipping any.</p><ul><li>WHERE status = &#39;active&#39; -&gt; <strong>Uses the index.</strong> (Fast)</li><li>WHERE status = &#39;active&#39; AND gender = &#39;F&#39; -&gt; <strong>Uses the index.</strong> (Faster)</li><li>WHERE status = &#39;active&#39; AND gender = &#39;F&#39; AND city = &#39;New York&#39; -&gt; <strong>Uses the index.</strong> (Fastest)</li></ul><p>But look what happens if you break the chain:</p><ul><li>WHERE gender = &#39;F&#39; AND city = &#39;New York&#39; -&gt; <strong>DOES NOT USE THE INDEX.</strong> Why? Because the tree is sorted by status first. Without providing the status, the database doesn&#39;t know where to start traversing the tree. It’s like trying to find someone in a phonebook by their first name instead of their last name. The index is completely useless.</li></ul><p><em>Architectural Takeaway:</em> Always order the columns in your composite index starting with the column you query most frequently, or the column that has the highest cardinality (the most unique values).</p><h3>The “God Tier” Optimizations</h3><p>If you want to write queries that return in sub-millisecond times, you need to use these two advanced techniques.</p><h4>1. The Covering Index (Index-Only Scan)</h4><p>Remember the “Double Lookup” tax? Where we had to jump from the secondary index back to the main table to get the rest of the columns?</p><p>What if we just put all the columns we need <em>inside</em> the index?</p><p>Let’s say your API needs to list the names of all active users in a city.</p><p>SELECT name FROM users WHERE status = &#39;active&#39; AND city = &#39;Chicago&#39;;</p><p>If we create this index: CREATE INDEX idx_chicago_users ON users (status, city, name);</p><p>When the database traverses the B+Tree and hits the leaf node to find the active users in Chicago, it notices that the name column is literally sitting right there in the leaf node. It doesn&#39;t need to do a Bookmark Lookup to the main table. It has all the data it needs to satisfy the query directly from the index.</p><p>This is called an <strong>Index-Only Scan</strong>. It completely entirely bypasses the main table on the hard drive. It is the absolute fastest way a relational database can return data. (In Postgres, you can explicitly define this using the INCLUDE keyword: CREATE INDEX idx_users ON users (status, city) INCLUDE (name);).</p><h4>2. The Partial Index (Filtered Index)</h4><p>Let’s say you are building an AI-powered DSA Interview prep tool. You have a questions table with 10,000 algorithmic problems. You have a background worker that constantly queries for questions that are pending evaluation by the local MLX-Whisper model.</p><p>SELECT * FROM questions WHERE evaluation_status = &#39;pending&#39;;</p><p>Usually, 99% of the questions are completed, and only 1% are pending. If you index the entire evaluation_status column, you are wasting massive amounts of disk space indexing the word &#39;completed&#39; 9,900 times, which you will literally never query for.</p><p>Instead, you write a <strong>Partial Index</strong>:</p><p>CREATE INDEX idx_pending_evals ON questions (created_at) WHERE evaluation_status = &#39;pending&#39;;</p><p>The database builds a tiny, ultra-fast B+ Tree that <em>only</em> contains rows where the status is pending. It takes up kilobytes of memory instead of megabytes, inserts are instantly fast, and your background worker can pull pending tasks in microseconds.</p><h3>Why We Don’t Index Everything</h3><p>If indexes make SELECT queries so fast, why don&#39;t we just index every single column in the table?</p><p>Because indexes are not free. They are actively hostile to your database’s write performance.</p><p>Every time you execute an INSERT, UPDATE, or DELETE, the database doesn&#39;t just write to the main table. It has to go and update <em>every single B-Tree index</em> associated with that table.</p><p>If you have a table with 15 indexes, one single INSERT statement actually requires 16 physical disk writes. Furthermore, as you insert data into random places in the B+Tree, the 8KB leaf nodes fill up. When a leaf node gets completely full, the database has to perform a <strong>Page Split </strong>it halts the transaction, allocates a new page, moves half the data over, and rebalances the tree. Page splits are computationally expensive and cause disk fragmentation.</p><p><strong>The Golden Rule:</strong> Indexes accelerate SELECT (Reads), but they penalize INSERT/UPDATE/DELETE (Writes).</p><p>In a heavy read-oriented system (like an e-commerce catalog), index aggressively. In a heavy write-oriented system (like an IoT telemetry database capturing 10,000 metrics a second), drop every index you can possibly live without.</p><h3>The Query Optimizer</h3><p>This is the final, most frustrating piece of the puzzle. You design the perfect index. You run your query. It’s slow. You type EXPLAIN ANALYZE SELECT ... and you see the database is doing a Seq Scan (Full Table Scan) and completely ignoring your index.</p><p>Why? Because the database <strong>Optimizer</strong> is a highly paranoid, cost-based mathematical engine.</p><p>The Optimizer keeps <strong>Statistics</strong> on your data. It knows exactly how many rows are in the table, and it knows the approximate distribution of values (Cardinality).</p><p>Before it executes your query, the Optimizer calculates the cost of using your index vs. the cost of a full table scan.</p><p>Remember the “Double Lookup” tax?</p><p>If you write a query like SELECT * FROM users WHERE gender = &#39;M&#39;; (assuming a 50/50 gender split in a 10 million row table).</p><p>The Optimizer thinks: <em>“If I use the index, I have to traverse the tree, find 5 million pointers, and then do 5 million random disk jumps to fetch the rows. Random disk I/O is slow. You know what’s faster? Just reading the main table sequentially from start to finish and throwing away the female rows.”</em></p><p>The database will dynamically choose to ignore your index if it determines that fetching a large percentage of the table (usually somewhere around the 15% to 20% mark, known as the “Tipping Point”) is cheaper via a sequential scan than via 5 million random index lookups.</p><p>If your database is ignoring an index it <em>should</em> be using, it means your database statistics are out of date. The database thinks the table is tiny when it’s actually huge. In Postgres, you fix this by running ANALYZE users;, which forces the database to scan the table and recalculate its internal math.</p><h3>The Indexing Checklist</h3><p>When I am reviewing a pull request that introduces a slow query or modifies a massive database table, I run through this exact mental checklist:</p><ul><li><strong>Is there a Sequential Scan in the </strong><strong>EXPLAIN plan?</strong> If the table has more than 1,000 rows, kill the PR until an index is added.</li><li><strong>Are we breaking the Left-Prefix Rule?</strong> Ensure the WHERE clause columns match the composite index column order from left to right.</li><li><strong>Are we using functions on indexed columns?</strong> If you write WHERE LOWER(email) = &#39;test@example.com&#39;, the database <strong>cannot</strong> use the standard email index. You must either create a Function-Based Index (CREATE INDEX ON users (LOWER(email))) or fix the application to store lowercase emails.</li><li><strong>Can we make it a Covering Index?</strong> If the query only selects two or three columns, add them to the index via INCLUDE to get an Index-Only Scan.</li><li><strong>Is this a high-write table?</strong> If yes, scrutinize every single index. Drop any index that hasn’t been hit by a read query in the last 30 days (most databases have views, like pg_stat_user_indexes, to show you unused indexes).</li></ul><p>Indexing is where software engineering meets physical engineering. You are no longer just writing code; you are actively managing the movement of a mechanical disk head (or electrons in an SSD). Master the B-Tree, respect the cost of writes, and learn to read the EXPLAIN plan, and you will never fear a slow database again.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ecb74f879b5d" width="1" height="1" alt=""><hr><p><a href="https://blog.stackademic.com/why-physics-matter-when-creating-database-index-ecb74f879b5d">Database Indexing: The Performance Trick Nobody Explained Properly</a> was originally published in <a href="https://blog.stackademic.com/">Stackademic</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Why the OSI Model is the Only Way to Debug]]></title>
            <link>https://sameerahmed56.medium.com/why-the-osi-model-is-the-only-way-to-debug-128d1815e52d?source=rss-e4526effdd7c------2</link>
            <guid isPermaLink="false">https://medium.com/p/128d1815e52d</guid>
            <category><![CDATA[system-design-interview]]></category>
            <category><![CDATA[system-design-concepts]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Sameer Ahmed]]></dc:creator>
            <pubDate>Fri, 06 Mar 2026 09:16:18 GMT</pubDate>
            <atom:updated>2026-03-06T09:16:18.846Z</atom:updated>
            <content:encoded><![CDATA[<p>Learn to read it, and you’ll never be lost in your own infrastructure again.</p><p>Let’s be honest. If you went to a university for computer science, you probably memorized a cheesy mnemonic for the OSI model the night before a networking exam. You passed the test, immediately dumped it from your short-term memory, and went back to writing React components or Python scripts, assuming the “network layers” were someone else’s problem.</p><p>Fast forward five years. You’re a engineer now. It’s 2:00 PM on a Thursday, and your microservice is randomly dropping 3% of its requests to the database. The database CPU is fine. Your application logs show generic Connection Timeout errors. Your junior engineers are staring at the code, wildly guessing that maybe it&#39;s a bug in the ORM or a bad async/await implementation.</p><p>This is the exact moment you need the OSI model.</p><p>Let’s pull the OSI model out of the dusty textbooks and look at how it actually governs every single byte of data your applications send, and more importantly, how you use it to find out exactly who is to blame when things break.</p><h3>The OSI Model is a Lie (Sort Of)</h3><p>Before we break down the layers, we need to clear the air: <strong>The OSI (Open Systems Interconnection) model does not actually exist in the wild.</strong></p><p>It’s a conceptual framework created in the 1980s. The actual internet runs on the TCP/IP model, which is much messier and clumps several of these layers together. But we still use the 7-layer OSI model because it gives us an incredibly precise vocabulary. It allows a frontend dev, a backend dev, and a network engineer to point to the exact same abstract concept without misunderstanding each other.</p><p>When data leaves your application, it travels <em>down</em> the 7 layers, getting wrapped in a new envelope at each step (we call this <strong>Encapsulation</strong>). When it reaches the destination, it travels <em>up</em> the layers, getting unwrapped.</p><p>Let’s trace the journey of a single HTTP request from the bottom up because physical reality is where most of our problems actually start.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*9M-_yajOTLhg4s_N" /></figure><h3>Layer 1: The Physical Layer (The “Is It Plugged In?” Layer)</h3><p>This is the raw, unadulterated reality of the universe. Layer 1 doesn’t know what an IP address is. It doesn’t know what JSON is. It only knows about electrical voltages over copper wires, pulses of light through fiber-optic cables, and radio frequencies bouncing through the air (Wi-Fi).</p><p>Data at this layer is just a massive, dumb stream of 1s and 0s.</p><ul><li><strong>The Hardware:</strong> Cables, network hubs, repeaters, Wi-Fi antennas.</li><li><strong>The Diagnostic:</strong> When an engineer says “The server is down,” I always verify Layer 1 first. Did AWS literally have a backhoe cut a fiber line in us-east-1? Is the ethernet cable on the on-premise rack actually seated in the port? Is the server&#39;s power supply dead? You cannot debug an API if the electricity isn&#39;t flowing.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/594/0*Inw_JTsI3HWDeuBE.png" /></figure><h3>Layer 2: The Data Link Layer (The Neighborhood Watch)</h3><p>If Layer 1 is just a raw wire, Layer 2 is the system that tries to make sense of the chaos on that specific wire.</p><p>Imagine you are in a crowded room, shouting. Everyone hears you (Layer 1). But if you say, <em>“Hey John Doe, pass the salt,”</em> John knows to respond because you used his specific name.</p><p>That is Layer 2. It introduces <strong>MAC Addresses</strong> (Media Access Control). Every network card ever manufactured has a permanently burned-in MAC address. Layer 2 packages the 1s and 0s into “Frames” and handles getting that frame from one physical device to the <em>very next</em> physical device connected to the same local switch.</p><ul><li><strong>The Hardware:</strong> Network Switches.</li><li><strong>The Diagnostic:</strong> If two servers in the same subnet suddenly can’t talk to each other, but they can talk to the outside world, you have a Layer 2 problem. Usually, it’s a bad ARP cache (the table that maps IP addresses to MAC addresses) or a misconfigured switch VLAN dropping your frames.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/594/0*uzQXn1nXADg8CObg.png" /></figure><h3>Layer 3: The Network Layer (The Global Postal Service)</h3><p>Layer 2 only gets you to the machine physically plugged in next to you. If you want to talk to a server in Tokyo, you need Layer 3.</p><p>This is the realm of the <strong>IP Address</strong> (Internet Protocol). Layer 3 takes your data, wraps it in a “Packet,” slaps a source and destination IP address on it, and hands it to a Router.</p><p>Routers don’t care about the final application. They just look at the destination IP, look at their giant map of the internet (BGP routing tables), and say, <em>“I don’t know where exactly that server is, but I know sending it to this router in Chicago gets it closer.”</em> The packet hops from router to router until it arrives.</p><ul><li><strong>The Hardware:</strong> Routers.</li><li><strong>The Diagnostic:</strong> “I can ping the local gateway, but I can’t reach Google.” This is a classic Layer 3 failure. It means your subnet routing tables are messed up, or a firewall rule (Security Group) is aggressively dropping packets on port 443. traceroute is your best friend here.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/594/0*qWbZLe_MImE717FN.png" /></figure><h3>Layer 4: The Transport Layer (The Delivery Manager)</h3><p>We’ve arrived at the destination machine! But there’s a problem. That server in Tokyo is running a web server, an SSH daemon, and a database all at the same time. How does it know which application should receive your packet?</p><p>Layer 4 introduces <strong>Ports</strong>. It wraps the data into “Segments” (for TCP) or “Datagrams” (for UDP).</p><p>This is also the layer that handles the reliability we talked about in the last article. If you use <strong>TCP</strong> (Transmission Control Protocol), Layer 4 manages the handshakes, the sequence numbers, and the acknowledgments to ensure no data is lost. If you use <strong>UDP</strong> (User Datagram Protocol), Layer 4 just blasts the data out of a firehose and hopes for the best.</p><ul><li><strong>The Hardware/Software:</strong> Firewalls, Load Balancers (Layer 4 TCP load balancers like AWS Network Load Balancer).</li><li><strong>The Diagnostic:</strong> If your application logs are throwing Connection Refused, it means Layer 3 worked (you hit the machine), but Layer 4 failed (the port is closed or the service isn&#39;t listening). If you see Connection Reset by Peer, a firewall or a load balancer actively intercepted your TCP connection and killed it.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/594/0*r4Uso6G-QObMuAek.png" /></figure><h3>Layer 5: The Session Layer (The Secretary)</h3><p>To be totally frank, Layers 5 and 6 are where the OSI model gets a bit academic. In modern networking, these layers are usually just handled by the application code or the TLS library itself.</p><p>The Session Layer establishes, manages, and terminates the connections between the local and remote application. It handles things like graceful tear-downs, keeping the connection alive during idle periods, and checkpointing long downloads so they can resume if interrupted.</p><ul><li><strong>The Diagnostic:</strong> Have you ever written a database query that took 15 minutes, and halfway through, the client just magically disconnected? That’s often a Layer 5 issue where an idle timeout threshold was hit, and the session manager abruptly hung up the phone.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/358/0*SX-cYkgfHFTIe0y_.png" /></figure><h3>Layer 6: The Presentation Layer (The Translator)</h3><p>The Presentation layer is responsible for translating data from the network format into a format the application actually understands.</p><p>This is where data serialization happens. Turning a Python dictionary into a JSON string? That’s Presentation layer logic. Compacting data into Protobufs for a gRPC call? Presentation layer.</p><p>Crucially, this is also where <strong>Encryption</strong> lives. When you use HTTPS, the TLS/SSL handshake and the subsequent symmetric encryption of your payloads happen right here. It takes the plain text, scrambles it into unreadable cipher text, and passes it down to Layer 4 to be shipped.</p><ul><li><strong>The Diagnostic:</strong> “The API is returning data, but my parser is throwing a SyntaxError: Unexpected token &lt; in JSON at position 0.&quot; That is a Layer 6 failure. Your server returned an HTML error page, but your client blindly tried to parse it as JSON. Or, if you see SSL Handshake Failed that’s Layer 6 actively refusing to establish trust.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/594/0*y-wz6QNxX1v8LSTj.png" /></figure><h3>Layer 7: The Application Layer (Where We Live)</h3><p>Finally. We made it to the top.</p><p>Layer 7 is the closest layer to the end-user. It provides the protocols that your software actually uses to do its job.</p><ul><li><strong>HTTP/HTTPS</strong> for web traffic.</li><li><strong>SMTP</strong> for sending emails.</li><li><strong>WebSockets</strong> for real-time chat.</li><li><strong>DNS</strong> to resolve “https://www.google.com/search?q=google.com&quot; into an IP address.</li></ul><p>This is where you write your REST APIs, your GraphQL mutations, and your serverless functions.</p><ul><li><strong>The Hardware/Software:</strong> Nginx, Apache, API Gateways (Layer 7 Load Balancers like AWS Application Load Balancer).</li><li><strong>The Diagnostic:</strong> If the request returns a 500 Internal Server Error, or a 404 Not Found, or a 401 Unauthorized congratulations. Layers 1 through 6 worked perfectly. The network is completely fine. The data arrived beautifully intact. The failure is entirely your code&#39;s fault. Go fix your application.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/661/0*H7H6mOyxziVN_ljq.png" /></figure><h3>The Diagnostic Protocol: How to Actually Use This</h3><p>The reason seasoned engineers love the OSI model is that it gives you a deterministic search algorithm for fixing outages. We call it <strong>The Divide and Conquer Method</strong>.</p><p>When a complex distributed system breaks, you don’t just guess. You test the layers.</p><p>Let’s say a backend worker can’t reach a Redis cache.</p><ol><li><strong>Test Layer 3:</strong> Can I ping the Redis server&#39;s IP? Yes. (Layer 1, 2, and 3 are good. The cables are plugged in, and the routing is correct).</li><li><strong>Test Layer 4:</strong> Can I telnet or nc (netcat) to the Redis IP on port 6379? No. The connection hangs.</li><li><strong>The Diagnosis:</strong> Stop looking at the code. Stop looking at the Redis configuration. You have a Layer 4 problem. The security group or firewall is dropping packets on port 6379. Go fix the infrastructure.</li></ol><p>Alternatively, if telnet connects instantly (Layer 4 is good), but the Redis client in your code throws an Authentication Failed error... you know immediately it’s a Layer 7 problem. Your network is perfect; you just rotated the database password and forgot to update the environment variables.</p><p>Understanding the OSI model is what separates the engineers who blindly copy-paste Stack Overflow answers from the engineers who can walk into a catastrophic production outage, look at a chaotic dashboard, and say, “It’s a Layer 4 routing issue. I’ll have it fixed in five minutes.”</p><p>It’s the map of the territory. Learn to read it, and you’ll never be lost in your own infrastructure again.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=128d1815e52d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Unpacking Latency, Throughput, and Bandwidth]]></title>
            <link>https://blog.stackademic.com/unpacking-latency-throughput-and-bandwidth-69dd9dc931e0?source=rss-e4526effdd7c------2</link>
            <guid isPermaLink="false">https://medium.com/p/69dd9dc931e0</guid>
            <category><![CDATA[system-design-interview]]></category>
            <category><![CDATA[design-systems]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[latency]]></category>
            <category><![CDATA[throughput]]></category>
            <dc:creator><![CDATA[Sameer Ahmed]]></dc:creator>
            <pubDate>Wed, 04 Mar 2026 00:20:30 GMT</pubDate>
            <atom:updated>2026-03-10T08:32:47.917Z</atom:updated>
            <content:encoded><![CDATA[<p>It is not all about increasing pipe size.</p><p>It’s the most common misconception in the industry. We use the terms <strong>Latency</strong>, <strong>Throughput</strong>, and <strong>Bandwidth</strong> interchangeably in casual conversation. We complain that our home Wi-Fi “has low bandwidth” when a Netflix show buffers, or we boast about a “high-throughput” system just because it sits on a gigabit fiber connection.</p><p>But in distributed systems engineering, confusing these three concepts is fatal. Throwing more bandwidth at a latency problem is like adding more lanes to a highway to make a single car drive faster. It doesn’t work, it burns cash, and your users still abandon their shopping carts.</p><p>Let’s strip away the textbook definitions. We’re going to look at exactly what these three metrics are, how they mathematically strangle each other, and how you actually fix them when your pagers go off.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/826/0*O4f-ThiwhJfsWymW.png" /></figure><h3>The Highway Analogy (The Only One You’ll Ever Need)</h3><p>Before we get into TCP windows and packet routing, let’s establish a shared mental model. Imagine a physical highway connecting two cities: City A (your user’s browser) and City B (your backend server).</p><ul><li><strong>Bandwidth</strong> is the number of lanes on the highway. It is the absolute maximum capacity of the road.</li><li><strong>Latency</strong> is the speed limit combined with the physical distance. It is how long it takes <em>one single car</em> to drive from City A to City B.</li><li><strong>Throughput</strong> is the number of cars that <em>actually arrive</em> at City B every hour.</li></ul><p>If a bridge collapses in the middle of the highway and all traffic is squeezed into one lane, your <strong>Throughput</strong> plummets, even though the <strong>Bandwidth</strong> at the start of the highway is still wide open. If a police officer pulls someone over, the cars behind them have to brake- that’s a spike in <strong>Latency</strong>.</p><p>Let’s break them down at the network level.</p><h3>Bandwidth: The Physical Ceiling</h3><p>Bandwidth is a theoretical number. It is the absolute maximum amount of data that can be transmitted over a network link in a given amount of time, assuming absolutely zero interference, zero protocol overhead, and perfect conditions.</p><p>It is usually measured in bits per second (bps, Mbps, Gbps).</p><p>When you provision an EC2 instance on AWS and it says “Up to 10 Gbps Network Performance,” that is your bandwidth. You are paying for the diameter of the pipe.</p><p><strong>The Reality Check:</strong> As a backend engineer, bandwidth is rarely your actual bottleneck unless you are streaming 4K video, serving massive file downloads, or moving terabytes of database backups across regions. Text-based payloads (JSON, HTML, Protobufs) are incredibly tiny. A 1 Gbps connection can theoretically handle roughly 125 megabytes of JSON per second. That is a staggering amount of text.</p><p>If your JSON API is slow, I promise you, it is almost never a bandwidth problem.</p><h3>Latency: The Speed of Light Tax</h3><p>Latency is the silent killer of web applications. It is the time it takes for a single unit of data (a packet) to travel from the source to the destination.</p><p>In engineering, we almost always measure this as <strong>RTT (Round Trip Time), </strong>the time it takes for a request to go out and the acknowledgment to come back. We measure it in milliseconds (ms).</p><p>Unlike bandwidth, which you can upgrade by throwing money at your cloud provider, latency is bounded by the laws of physics. Light in a fiber-optic cable travels at roughly 200,000 kilometers per second. You cannot bribe the speed of light.</p><p>If your database is in us-east-1 (Virginia) and your user is in Sydney, Australia, the absolute physical minimum time it takes for a packet to travel there and back is around 130ms. But physical distance is only part of the equation. Latency is actually a compounding tax made of four parts:</p><ol><li><strong>Propagation Delay:</strong> The actual speed of light over the physical distance.</li><li><strong>Transmission Delay:</strong> The time it takes to push the bits onto the physical wire.</li><li><strong>Queuing Delay:</strong> The time your packet spends sitting in a router’s buffer somewhere in Omaha because a Netflix movie is hogging the line.</li><li><strong>Processing Delay:</strong> The time it takes your application server to deserialize the JSON, realize the user doesn’t have permissions, and generate a 403 Forbidden error.</li></ol><p><strong>The Reality Check:</strong> Latency is why modern web architecture pushes things to the “Edge.” It is why Content Delivery Networks (CDNs) like Cloudflare exist. You cannot make a packet travel from Sydney to Virginia faster. The only way to fix propagation latency is to move the data closer to the user by caching it in a Sydney data center.</p><h3>Throughput: The Ugly Truth</h3><p>Throughput is the ultimate metric of reality. If bandwidth is what you <em>paid for</em>, throughput is what you <em>actually get</em>.</p><p>It is the rate of successful, completely processed data delivery over a communication channel. We measure it in requests per second (RPS), transactions per second (TPS), or actual megabytes per second.</p><p>Throughput is deeply, inextricably tied to both Bandwidth and Latency, but it is also hostage to your application code.</p><p>You might have a massive 10 Gbps connection (High Bandwidth) and the user might be sitting right next door to the data center (Low Latency). But if your Node.js server has a memory leak, or if your database is experiencing row-level locking because of a bad migration, your API might only be able to process 5 requests per second.</p><p>Your bandwidth is huge. Your latency is low. But your <strong>Throughput</strong> is garbage.</p><h3>The Bandwidth-Delay Product</h3><p>Here is where Staff Engineers earn their paychecks. We need to talk about why high latency actively murders your throughput, even if you have infinite bandwidth.</p><p>Remember TCP? The protocol that powers HTTP? TCP guarantees that packets arrive in order and without corruption. To do this, the sender transmits a chunk of data, and then <em>stops and waits</em> for the receiver to send an Acknowledgment (ACK) before sending the next chunk.</p><p>The amount of data the sender is allowed to transmit before waiting for an ACK is called the <strong>TCP Window Size</strong>.</p><p>Imagine you are downloading a 1GB file over a massive 10 Gbps connection, but the server is on the other side of the planet (high latency, say 200ms RTT).</p><ol><li>Your server blasts out a TCP window’s worth of data (e.g., 64 kilobytes).</li><li>It hits the wire instantly because your bandwidth is huge.</li><li>But now, your server has to sit completely idle for 200ms waiting for the ACK from across the globe.</li><li>Once the ACK arrives, it sends the next 64KB.</li></ol><p>Your 10 Gbps pipe is sitting 99% empty because the protocol is constantly waiting on the speed of light. This relationship is mathematically defined by the <strong>Bandwidth-Delay Product (BDP)</strong>, which calculates the maximum amount of unacknowledged data that can be in transit:</p><blockquote><strong>Capacity = Bandwidth * RTT</strong></blockquote><p>If your TCP window size is smaller than your BDP, you are physically incapable of utilizing your full bandwidth. This is why downloading a file from a local server is blindingly fast, but downloading that exact same file from a server in Tokyo feels like a crawl, regardless of how good your home internet is.</p><h3>The Ultimate “Sneakernet” Example</h3><p>There is a famous thought experiment in computer science that perfectly illustrates the disconnect between these three metrics: <strong>The Station Wagon Full of Hard Drives.</strong></p><p>Imagine you need to move 100 Terabytes of data from an office in New York to an office in Los Angeles. You <em>could</em> upload it over a 1 Gbps fiber internet connection. That would take roughly 9 days.</p><p>Or, you could load 100 Terabyte hard drives into the trunk of a Honda Civic and literally drive the car from New York to LA. The drive takes 40 hours.</p><p>Which network is “better”?</p><ul><li><strong>The Internet Connection</strong> has a latency of 60ms.</li><li><strong>The Honda Civic</strong> has a latency of 40 hours (horrendous!).</li><li><strong>The Honda Civic’s Throughput</strong>, however, is around 5.5 Gbps (100TB divided by 40 hours).</li></ul><p>The car has higher throughput than the fiber-optic cable.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/0*-Q8rlMx6DaBMhEwW.png" /></figure><p>This is exactly how <strong>AWS Snowmobile</strong> works. When a company needs to move exabytes of data to the cloud, Amazon physically drives a literal 18-wheeler semi-truck packed with hard drives to their data center. It is a network with a latency of several weeks, but a throughput that destroys any internet connection on earth.</p><h3>How to Fix Them in the Wild</h3><p>When you are architecting a system, you have to diagnose which of the three is actually causing your bottleneck. You use different tools for each.</p><h4>1. How to Fix Latency Problems</h4><p>You cannot change the speed of light. You must shorten the distance or cheat the system.</p><ul><li><strong>CDNs (Cloudflare, Fastly):</strong> Cache your static assets (images, CSS, JS) on edge servers physically located in the user’s city.</li><li><strong>Edge Compute:</strong> Move your lightweight API routing or authentication logic to serverless edge workers that execute near the user before ever hitting your main backend.</li><li><strong>Read Replicas:</strong> If you have users in Europe, spin up a PostgreSQL read replica in Frankfurt so they don’t have to cross the Atlantic just to fetch their user profile.</li></ul><h4>2. How to Fix Throughput Problems</h4><p>Throughput is almost always a software or infrastructure scaling issue.</p><ul><li><strong>Connection Pooling:</strong> (Like we talked about in the last session). Stop opening new database connections per request.</li><li><strong>Asynchronous Processing:</strong> Don’t make the user wait for an email to send. Drop a message in RabbitMQ or SQS and return a 200 OK instantly.</li><li><strong>Horizontal Scaling:</strong> Put a load balancer in front of your API and spin up 10 more instances of your backend service.</li></ul><h4>3. How to Fix Bandwidth Problems</h4><p>If you are actually hitting a bandwidth ceiling (which usually happens on mobile networks with poor signal), you need to shrink your payloads.</p><ul><li><strong>Compression:</strong> Enable Gzip or Brotli compression on your load balancer. It can shrink JSON payloads by up to 80%.</li><li><strong>GraphQL or Sparse Fieldsets:</strong> Stop returning the entire user object if the frontend only needs the user’s first name.</li><li><strong>Pagination:</strong> Don’t return 1,000 records. Return 20, and give the client a cursor to fetch the next 20.</li></ul><p>The next time someone complains that the system is slow, stop and ask the right questions. Are the requests taking too long to make the round trip? Are we choking on the sheer volume of concurrent requests? Or are our payloads just too fat for the pipe?</p><p>Diagnose the right disease, and you’ll write the right prescription.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=69dd9dc931e0" width="1" height="1" alt=""><hr><p><a href="https://blog.stackademic.com/unpacking-latency-throughput-and-bandwidth-69dd9dc931e0">Unpacking Latency, Throughput, and Bandwidth</a> was originally published in <a href="https://blog.stackademic.com/">Stackademic</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How Connection Pooling Actually Works]]></title>
            <link>https://blog.stackademic.com/how-connection-pooling-actually-works-46014afce5fd?source=rss-e4526effdd7c------2</link>
            <guid isPermaLink="false">https://medium.com/p/46014afce5fd</guid>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[database-design]]></category>
            <category><![CDATA[system-design-interview]]></category>
            <category><![CDATA[connection-pool]]></category>
            <category><![CDATA[systems-thinking]]></category>
            <dc:creator><![CDATA[Sameer Ahmed]]></dc:creator>
            <pubDate>Fri, 27 Feb 2026 21:21:19 GMT</pubDate>
            <atom:updated>2026-02-27T21:22:15.962Z</atom:updated>
            <content:encoded><![CDATA[<p>Why your database is crying with pool size of <strong>1000</strong>.</p><p>We’ve all been there.</p><p>Your code is clean. The unit tests are glowing green. You pushed your shiny new API to production, and for the first few days, everything is beautifully fast. Endpoint response times are sitting pretty at 45 milliseconds. You feel like a genius.</p><p>Then, you get featured on the front page of Some News, or a Reels about your app goes viral, or maybe it’s just Diwali. Traffic spikes 10x.</p><p>You look at your monitoring dashboards expecting to see your CPU sweating a bit. Instead, you see a bloodbath. Your API is throwing 500 errors. Response times have spiked to 15 seconds. And your database? Its CPU is pinned at 100%, but it’s barely executing any actual queries.</p><p>You frantically check your logs and see the dreaded words: FATAL: sorry, too many clients already or MongoTimeoutError.</p><p>Congratulations. You just accidentally <strong>DDoSed</strong> your own database.</p><p>The culprit almost every single time? Misunderstanding how database connections actually work, and failing to use a connection pool correctly. Let’s pull back the curtain on what happens when your application talks to your database, whether you’re running a classic relational mammoth like PostgreSQL or a NoSQL cluster like MongoDB.</p><h3>The Anatomy of a Connection (Why “Hello” is so expensive)</h3><p>To understand why your database fell over, we have to look at what happens when your code executes db.connect().</p><p>When we write backend code, we tend to treat the database like a local dictionary. You ask for a user, you get a user. But over the network, establishing a connection is a violently expensive, multi-step negotiation. It is not a lightweight operation.</p><p>Let’s break down the exact sequence of events when a Node.js or Python backend tries to connect to a <strong>PostgreSQL or MySQL</strong> database.</p><p><strong>1. The TCP Handshake: </strong>Before your database even knows you exist, the networking layers have to agree to talk. Your server sends a SYN packet. The database replies SYN-ACK. Your server replies ACK. If your database is hosted in a different availability zone, these network hops alone cost precious milliseconds.</p><p><strong>2. The Cryptographic Handshake: </strong>You aren’t sending passwords in plaintext over the wire, right? (Right?!). So, your application and the database now have to negotiate a TLS/SSL connection. They exchange certificates, agree on cipher suites, and generate symmetric encryption keys. This requires actual, heavy mathematical computation on both the client and the database server.</p><p><strong>3. The Authentication Phase: </strong>Now, the database finally hears from your app. It checks its firewall rules (like pg_hba.conf in Postgres). It takes your hashed password, compares it to its internal tables, and verifies you have the permissions to access the specific schema you requested.</p><p><strong>4. The OS Allocation: </strong>Here is where the real damage happens, particularly with PostgreSQL. Postgres uses a “process-per-connection” architecture. This means every single time a connection is successfully authenticated, the operating system on the database server physically forks a brand new process.</p><p>The OS has to carve out a chunk of RAM (usually 2MB to 10MB) specifically for this connection’s workspace (used for sorting data, hashing, and caching).</p><p>MySQL handles this slightly differently — it uses a “thread-per-connection” model. Threads are lighter than full processes, which is why out-of-the-box MySQL can often stomach a higher raw connection count than Postgres. But the fundamental problem remains: allocating these resources on the fly is slow.</p><p>If you are opening and closing a brand new connection for every single HTTP request your API receives, your database spends 90% of its CPU power acting like a nightclub bouncer — checking IDs and opening doors — and only 10% of its time actually serving data.</p><h4>But wait, what about MongoDB?</h4><p>If you come from the Node.js/MERN stack world, you might be thinking, <em>“I use MongoDB. NoSQL scales better, so I don’t have to worry about this, right?”</em></p><p>Wrong. The mechanics are different, but the physics of the network still apply.</p><p>MongoDB uses a binary wire protocol. When your driver connects to a Mongo cluster, it doesn’t just open one pipe. If you are connecting to a Replica Set (which you absolutely are in production), your driver connects to the primary node and initiates a complex handshake using the hello (formerly isMaster) command.</p><p>But it doesn’t stop there. The driver has to discover the entire topology of your cluster. It silently opens background connections to the secondary nodes so it can monitor their health and latency. It sets up connection pools internally.</p><p>While MongoDB’s server-side architecture (which uses asynchronous, non-blocking I/O) handles thousands of idle concurrent connections much more gracefully than a default Postgres setup, tearing down and rebuilding that complex replica-set discovery topology on every single API request will absolutely decimate your application’s performance.</p><h3>Enter the Connection Pool</h3><blockquote>The solution to all of this is <strong>Connection Pooling</strong>.</blockquote><p>Think of a connection pool like a fleet of rental cars at an airport. When you land and need a car, Uber doesn’t frantically call a factory in Delhi to build you a car from scratch. They hand you the keys to a car that is already built, already fueled, and parked in the lot. When you are done, you bring it back, they wash it, and hand the keys to the next guy.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*iGOq2IpAzl7EhaVR08PHiw.png" /></figure><p>A database connection pool works exactly the same way.</p><p>When your application starts up, the pool manager immediately does the heavy lifting. It negotiates the TCP handshakes, the TLS encryption, and the authentications to open a set number of connections (let’s say 20). It keeps these connections warm in memory.</p><p>Now, look at the lifecycle of a user request:</p><ol><li>User clicks “Buy”.</li><li>Your app asks the pool: <em>“Give me a connection.”</em></li><li>The pool hands over an already-open pipe. <strong>(Time elapsed: 0.1 milliseconds)</strong>.</li><li>Your app executes INSERT INTO orders....</li><li>Your app tells the pool: <em>“I’m done.”</em></li><li>The pool clears the session state and puts the connection back in the lot for the next request.</li></ol><p>You have entirely bypassed the network, cryptographic, and OS allocation taxes for every subsequent query.</p><p>Client-Side vs. Server-Side Pooling</p><h3>Client-Side vs. Server-Side Pooling</h3><p>In modern distributed systems, we have to decide <em>where</em> this pool lives. This is a crucial architectural decision.</p><h4>1. Client-Side Pooling (In-App)</h4><p>This is the most common default. The pool lives inside the memory of your application process. If you are building a Node.js backend using the pg library, or a Python backend using SQLAlchemy, you are usually using an in-app pool.</p><ul><li><strong>Pros:</strong> Extremely fast. Zero network latency to get a connection from the pool.</li><li><strong>Cons:</strong> It doesn’t scale well horizontally.</li></ul><p>Let’s say you are launching a new social platform — maybe a dating web app. It’s a Friday night, traffic spikes, and you scale up to 50 Node.js backend instances to handle the HTTP requests. If each Node.js instance has a connection pool of 20, you just slammed your database with <strong>1,000 active connections</strong>. Most default PostgreSQL instances will crash or lock up entirely at around 300–500 connections because of the memory overhead of those OS processes.</p><h4>2. Server-Side Pooling (Middleware)</h4><p>When you graduate to serious distributed systems, you move the pool <em>out</em> of the application and into a dedicated piece of infrastructure. Tools like <strong>PgBouncer</strong> (for Postgres) or <strong>ProxySQL</strong> (for MySQL) sit between your applications and your database.</p><ul><li><strong>How it works:</strong> Your 50 Node.js instances open their 1,000 connections, but they don’t connect to the database. They connect to PgBouncer. PgBouncer is incredibly lightweight and can easily hold 10,000 idle connections from your apps. But PgBouncer only maintains a tiny pool of, say, 50 actual heavy connections to the underlying PostgreSQL database. It multiplexes the queries.</li><li><strong>The Result:</strong> Your apps think they have infinite connections. Your database only sees 50 connections. Everyone is happy, and the database survives the traffic spike.</li></ul><h3>The Biggest Lie in Backend Engineering: Pool Sizing</h3><p>Once developers understand what a pool is, they almost immediately make a catastrophic mistake when configuring it.</p><p>You look at your traffic. You expect 1,000 concurrent users. So, you go into your database configuration file and set max_pool_size = 1000.</p><p>Makes sense, right? One connection per user?</p><p><strong>This will destroy your database.</strong></p><p>To understand why, we have to talk about how CPUs actually work. Let’s say your database server is a beefy machine with 8 CPU cores. Mathematically, physically, and literally, that server can only execute 8 instructions at the exact same microsecond.</p><p>If you give it 8 connections, it assigns one connection to each core. The cores grind through the SQL queries at lightning speed, finish them, and grab the next ones.</p><p>If you give it 1,000 active connections, the operating system panics. It only has 8 cores, but 1,000 people are screaming at it. So, the OS scheduler starts doing something called <strong>Context Switching</strong>.</p><p>It pauses connection #1, saves its state to memory, loads the state for connection #2, lets it run for a fraction of a millisecond, pauses it, saves it, loads connection #3, and so on.</p><p>Context switching is wildly expensive. When you flood a database with hundreds of active connections, the CPU spends all of its time juggling the connections and almost no time actually executing your queries. Throughput plummets. Latency skyrockets. Your disk I/O thrashes as multiple queries try to read from different sectors of the hard drive simultaneously.</p><h4>The Magic Formula</h4><p>There is a famous formula for sizing connection pools, popularized by the PostgreSQL community and the developers of HikariCP (the gold standard of Java connection poolers):</p><blockquote><strong><em>Connections = (Core Count * 2) + Effective Spindle Count</em></strong></blockquote><p><em>(“Spindle count” is an older term referring to spinning hard drives. If you are on modern SSDs or NVMe drives, this represents a small, flat number for disk I/O concurrency).</em></p><p>Read that formula again.</p><p>If your database has 8 CPU cores, your ideal connection pool size is probably somewhere around <strong>20</strong>.</p><p>Not 200. Not 2,000. <strong>Twenty.</strong></p><p>“But wait,” you ask. “If I only have 20 connections, and 100 users try to hit the API at the exact same time, what happens to the other 80 users?”</p><p>They wait in the queue <em>inside your application memory</em>.</p><p>This is the secret to high-performance systems. It is infinitely faster to make an HTTP request wait 5 milliseconds in your Node.js or Python application while it waits for a connection to free up, than it is to overload the database and make the actual SQL query take 500 milliseconds to execute.</p><p>You want a large queue at the application level, and a very narrow, highly efficient bottleneck at the database level. Keep the database doing what it does best: reading and writing data as fast as physically possible without being distracted by connection management.</p><h3>The Microservices Trap: When Native Pooling Isn’t Enough</h3><p>If you are building a monolith, setting your pool size to 20 in your app configuration is easy. But modern architecture is rarely that simple.</p><p>Let’s say you built your backend using Serverless functions (like AWS Lambda), or you have a Kubernetes cluster running 50 replicas of your microservice.</p><p>If you configure your microservice to use a pool of 20 connections, and Kubernetes scales your service up to 50 pods… 50 pods * 20 connections = <strong>1,000 connections</strong>. You are back to accidentally DDoSing your database.</p><p>This is where the architecture splits between Relational and NoSQL.</p><h4>The Relational Fix: External Poolers (PgBouncer/ProxySQL)</h4><p>For Postgres and MySQL, the standard practice in distributed systems is to take the connection pool <em>out</em> of your application and put it into a dedicated piece of middleware infrastructure.</p><p>For Postgres, this is almost always <strong>PgBouncer</strong>.</p><p>PgBouncer sits between your microservices and your database. Your 50 Kubernetes pods open their 1,000 connections to PgBouncer. PgBouncer is incredibly lightweight and can easily hold tens of thousands of idle connections.</p><p>However, PgBouncer only maintains a tiny, strict pool of 20 <em>actual</em> connections to the underlying PostgreSQL database. As queries come in from the 1,000 app connections, PgBouncer multiplexes them, funneling them rapidly through the 20 database connections. Your apps think they have infinite scale; your database thinks it’s having a relaxed Tuesday.</p><h4>The MongoDB Reality</h4><p>MongoDB handles this differently. Because MongoDB doesn’t rely on heavy OS processes for every connection, it is much more tolerant of higher connection counts from distributed microservices. A modern Mongo cluster can handle thousands of concurrent connections with far less degradation than Postgres.</p><p>However, serverless environments (like AWS Lambda) will still destroy Mongo if you aren’t careful. If 1,000 Lambdas spin up, they will initiate 1,000 replica-set discovery handshakes simultaneously.</p><p>To fix this, MongoDB doesn’t typically use external middleware like PgBouncer. Instead, they rely on architectural workarounds: either strictly managing the maxPoolSize parameter on the native driver (keeping it very low per Lambda), using MongoDB Atlas Data API (which proxies queries over HTTPS instead of the stateful wire protocol), or carefully managing context execution so the connection object persists between serverless invocations.</p><h3>The Takeaway</h3><p>Database connections are the most fragile resource in your entire stack. They are expensive to create, heavy to maintain, and dangerous to mismanage.</p><p>If you take nothing else away from this, remember these three rules:</p><ol><li><strong>Never open a raw connection per request.</strong> If you are writing client.connect() and client.close() inside your route handlers, stop. Use your driver&#39;s pooling feature immediately.</li><li><strong>Keep it small.</strong> Your connection pool should be tied to the number of CPU cores on your database server, not the number of users on your website.</li><li><strong>Mind your horizontal scale.</strong> If you scale your application horizontally across multiple servers or serverless functions, you must calculate the <em>aggregate</em> number of connections hitting your database. If it gets too high, introduce a proxy.</li></ol><p>Treat your database like a finely tuned engine. Give it the exact amount of fuel it needs to run at redline, and not a drop more, lest you flood the engine and stall out in front of everyone.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=46014afce5fd" width="1" height="1" alt=""><hr><p><a href="https://blog.stackademic.com/how-connection-pooling-actually-works-46014afce5fd">How Connection Pooling Actually Works</a> was originally published in <a href="https://blog.stackademic.com/">Stackademic</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Message Queues vs Event Streams: Kafka vs (RabbitMQ, SQS)]]></title>
            <link>https://blog.stackademic.com/message-queues-vs-event-streams-or-should-i-say-kafka-vs-rabbitmq-sqs-d1d9ff0f3173?source=rss-e4526effdd7c------2</link>
            <guid isPermaLink="false">https://medium.com/p/d1d9ff0f3173</guid>
            <category><![CDATA[rabbitmq]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[kafka]]></category>
            <category><![CDATA[message-queue]]></category>
            <category><![CDATA[design-systems]]></category>
            <dc:creator><![CDATA[Sameer Ahmed]]></dc:creator>
            <pubDate>Wed, 25 Feb 2026 23:43:01 GMT</pubDate>
            <atom:updated>2026-02-26T00:05:01.841Z</atom:updated>
            <content:encoded><![CDATA[<p>If you internalize this difference, 90% of your architectural dilemmas will solve themselves.</p><p>Grab a whiteboard marker and pull up a chair. Let’s talk about decoupling.</p><p>If we were sitting together in a meeting room right now, looking at a messy architecture full of tangled microservices, I can almost guarantee someone would point to the middle of the board and say, “Let’s just throw Kafka in there.” Or maybe, “Let’s just use an SQS queue.”</p><p>They aren’t. Choosing between Apache Kafka, RabbitMQ, and Amazon SQS isn’t just a matter of picking a brand; it’s about fundamentally deciding how your systems are going to talk to each other, how they handle failure, and what your operational reality is going to look like at 2:00 AM on a Sunday.</p><p>So, let’s have a real, human-to-human conversation about this. We’re going to dive deep into how these things actually work under the hood, when to use them, and just as importantly when to run away from them.</p><h3>Commands vs Events</h3><p>Before we even look at the tools, we need to clear up the biggest source of confusion today. We often use the word “messaging” to cover two completely different concepts: <strong>Queues</strong> and <strong>Streams</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KZyczLbZLLc9tY3cUvI91g.png" /></figure><p>Imagine you are managing a restaurant.</p><p><strong>A Queue (RabbitMQ, SQS)</strong> is like the ticket wheel in the kitchen. A waiter writes down “Table 4 needs a burger,” and sticks it on the wheel. A chef pulls the ticket off, cooks the burger, and throws the ticket in the trash. The ticket was a command. It meant “do this specific thing.” Once the thing is done, the message’s life is over. If two chefs pull tickets, they get different tickets.</p><p><strong>A Stream (Kafka)</strong> is like the restaurant’s security camera and cash register log combined. It records everything: “Customer walked in at 12:01,” “Customer sat at Table 4 at 12:03,” “Burger was ordered at 12:05.” It is a permanent, immutable ledger of facts. The kitchen can look at this ledger to know what to cook. The accounting department can look at the exact same ledger at the end of the month to calculate revenue. The data isn’t deleted just because someone read it.</p><p>If you internalize this difference, 90% of your architectural dilemmas will solve themselves. Now, let’s break down the heavy hitters.</p><h3>Apache Kafka</h3><p>Let’s start with the big one. Apache Kafka is a beast. It was born at LinkedIn because they needed something that could handle massive, relentless pipelines of data without falling over.</p><p>Kafka doesn’t care about your specific tasks. It just takes an event — a serialized byte array and appends it to a log on a hard drive. That’s it. It’s a dumb broker and a highly intelligent consumer.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1C4qv-JohCaXjsEL4J_Scw.png" /></figure><h4>How It Actually Works</h4><p>When you send a message to Kafka, you send it to a <strong>Topic</strong>. But to scale, Kafka splits that topic into <strong>Partitions</strong> across different servers (Brokers). Think of partitions like different lanes on a highway.</p><p>Because Kafka doesn’t delete messages when they are read, it doesn’t keep track of who read what. That burden is pushed entirely onto your consumer. If you are writing a Python service to read from Kafka, your consumer has to maintain a little bookmark called an <strong>Offset </strong>that says, “I have read up to message #4,502 in Partition 2.”</p><p>If your Python app crashes, when it reboots, it looks at its offset and picks up right where it left off. And here is the magic superpower of Kafka: <strong>Replayability</strong>. Because the data is stored on disk for days (or forever), if you deploy a bug to production and corrupt your database, you can fix the bug, rewind your Kafka offset back to last Tuesday, and just re-read the stream to rebuild your state.</p><h4>The Catch</h4><p>Kafka is operationally heavy. You have to manage Zookeeper or KRaft quorums, you have to balance partition leaders, and if you get your partitioning keys wrong, you completely destroy your message ordering. It requires dedicated engineering bandwidth to maintain.</p><h4>Real-World Example</h4><p>Let’s say you are designing a system like Google Docs or a collaborative code editor. Multiple people are typing at the same time. You need to ensure every single keystroke is captured, ordered correctly, and broadcast to everyone else viewing the document.</p><ol><li><strong>The Producers:</strong> User A and User B’s browsers send keystroke events (&quot;inserted &#39;x&#39; at index 5&quot;) to a Kafka topic called document-edits.</li><li><strong>The Partitioning:</strong> You use the DocumentID as the partition key. This guarantees that every edit for a specific document goes to the exact same partition, ensuring strict chronological ordering.</li><li><strong>Consumer 1 (Real-time Broadcast):</strong> A WebSocket server reads the stream and pushes the edits to all connected clients.</li><li><strong>Consumer 2 (Storage):</strong> A completely separate background worker reads the exact same stream at its own pace and saves the final document state to a database.</li></ol><p>Kafka handles the immense firehose of keystrokes without breaking a sweat, and allows multiple separate systems to consume the same reality.</p><h3>RabbitMQ</h3><p>If Kafka is a dumb pipe with smart consumers, RabbitMQ is a genius pipe with dumb consumers. It uses the AMQP protocol and is built entirely around the idea of intelligent routing.</p><p>In RabbitMQ, you don’t send a message directly to a queue. That would be too simple. You send a message to an <strong>Exchange</strong>. The Exchange is like the sorting room at the post office. You configure <strong>Bindings</strong> (rules) that tell the Exchange how to route messages to different queues.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*08awpawUU_tvQ1bDxNU6rQ.png" /></figure><h4>How It Actually Works</h4><p>When a message lands in a queue, RabbitMQ sits there and waits for a consumer to take it. Once your worker grabs the message, RabbitMQ puts it in an “unacknowledged” state. It’s holding its breath. Your worker processes the job and then sends back an <strong>ACK</strong> (Acknowledgment). “I did it!” Only then does RabbitMQ permanently delete the message.</p><p>If your worker crashes midway and the TCP connection drops, RabbitMQ breathes out, takes the message back, and hands it to the next available worker. No data lost.</p><p>RabbitMQ shines when you need complex routing and you want the broker to handle the complexity so your microservices can be simple.</p><h4>The Catch</h4><p>Because RabbitMQ keeps state in memory (tracking exactly which message is in which queue, who has it, and waiting for ACKs), it can buckle under extreme load if consumers get too slow. If your queues fill up into the millions, RabbitMQ has to start paging to disk, and performance falls off a cliff.</p><h4>Real-World Example: The Ticket-Tracking System</h4><p>Imagine we’re building an enterprise IT ticket-tracking system. Users are submitting all sorts of tickets: hardware requests, software bugs, and critical server outages. We need a way to route these reliably to different departments.</p><ol><li><strong>The Producer:</strong> The web portal publishes a JSON payload to a TicketExchange. It attaches a routing key, like priority.high.server or priority.low.hardware.</li><li><strong>The Routing Magic:<br>- </strong>We bind the <strong>DevOps Queue</strong> to the exchange to catch anything matching *.server.<br>- We bind the <strong>IT Support Queue</strong> to catch *.hardware.<br>- We bind a <strong>PagerDuty Alert Queue</strong> to catch specifically priority.high.#.</li><li><strong>The Consumers:</strong> The workers just connect to their specific queues and process jobs. They don’t know about the routing rules.</li><li><strong>Priority Handling:</strong> RabbitMQ natively supports priority queues. So if a priority.high.server ticket comes in, RabbitMQ physically moves it to the front of the line so the next available DevOps worker gets it immediately, bypassing the backlog of password reset requests.</li></ol><p>You literally cannot do that routing natively in Kafka without writing a separate stream-processing application. RabbitMQ does it out of the box.</p><h3>Amazon SQS</h3><p>Alright, let’s talk about my personal favorite for 80% of daily engineering tasks: Amazon SQS (Simple Queue Service).</p><p>When I look at a team trying to stand up a Kafka cluster just to decouple an email-sending service, I usually stop them and point to SQS. SQS is the oldest service in AWS. It is not sexy. It does not have fancy routing like RabbitMQ. It does not have infinite replayability like Kafka.</p><p>What it does have is zero operational overhead. You literally just create the queue with one click, and you have an infinitely scalable, highly available buffer.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*N9Gs9CUn4Yvh-7P7e8KyGA.png" /></figure><h4>How It Actually Works</h4><p>SQS is entirely API-driven. You don’t hold open persistent TCP connections like you do with Kafka or RabbitMQ. Your workers make HTTP requests (ReceiveMessage) to AWS. We call this <strong>Long Polling</strong>. The worker knocks on SQS&#39;s door and says, &quot;Got any work?&quot; If not, SQS holds the connection open for up to 20 seconds before saying &quot;Nope.&quot;</p><p>When a worker pulls a message, SQS relies on a <strong>Visibility Timeout</strong>. If the timeout is 2 minutes, SQS makes that message invisible to all other workers for 2 minutes. If the worker finishes and deletes the message, great. If the worker has a memory leak and dies silently, the 2 minutes pass, and the message magically reappears in the queue for someone else to try.</p><p>And if a message keeps failing? SQS automatically shunts it to a <strong>Dead Letter Queue (DLQ)</strong> so it doesn’t block the rest of the pipeline, allowing your engineers to inspect the toxic payload on Monday morning.</p><h4>The Catch</h4><p>Standard SQS does not guarantee strict ordering, and it guarantees “at-least-once” delivery (meaning very rarely, you might get a duplicate message). If you absolutely need ordered, exactly-once processing, you have to use SQS FIFO queues, which have lower <strong>throughput</strong><em>(the rate at which a system, network, or device successfully processes or transfers data over a specific period, typically measured in bits per second)</em> limits compared to Standard SQS.</p><h4>Real-World Example: The AI Coding Assistant</h4><p>Let’s say we are building a local AI-powered coding assistant specifically for helping candidates prepare for DSA (Data Structures and Algorithms) interviews. Users submit a block of code, and we need to run it through an LLM to generate hints, check time complexity, and identify bugs.</p><p>LLM inference is slow. It can take 5 to 15 seconds per request. If 1,000 users submit code at the same time, our API will time out if we process it synchronously.</p><ol><li><strong>The Producer:</strong> The user hits submit. The API gateway immediately takes the code snippet, wraps it in JSON, drops it into an SQS queue called dsa-evaluations, and instantly returns a HTTP 202 Accepted to the user (&quot;We&#39;re working on it!&quot;).</li><li><strong>The Buffer:</strong> SQS holds those 1,000 requests safely. AWS manages the infrastructure. It won’t crash, no matter the spike.</li><li><strong>The Consumers:</strong> You have a fleet of backend Python workers utilizing strong concurrency management. They poll SQS, pull down a batch of 10 messages at a time, and feed them to the AI models.</li><li><strong>Auto-Scaling:</strong> You configure AWS to monitor the queue depth. As the queue grows, AWS spins up more worker instances. As the queue empties, it scales them down to zero, saving you money.</li></ol><p>You didn’t have to configure a cluster. You didn’t have to manage partitions. You just wrote a worker script and let AWS handle the heavy lifting of the queue.</p><h3>The Verdict: How to Make the Call</h3><p>So, we’re back at the whiteboard. Which one do you draw? Here is my what I think before making this call.</p><p><strong>Draw Kafka on the board if:</strong></p><ul><li>You are dealing with a continuous flow of facts or events (telemetry, clicks, logs).</li><li>You need a system of record that multiple, unrelated teams can consume from at different speeds.</li><li>You are building a real-time data lake or complex event-driven microservices that rely on Event Sourcing.</li><li>Your throughput is measured in tens of thousands (or millions) of messages per second.</li></ul><p><strong>Draw RabbitMQ on the board if:</strong></p><ul><li>You are building a traditional task-queue system where messages are commands to do work.</li><li>You need complex routing, filtering, and priority jumping baked right into the broker.</li><li>Your application requires fine-grained control over message acknowledgments and immediate retries.</li><li>You are okay managing the infrastructure and monitoring memory usage carefully.</li></ul><p><strong>Draw Amazon SQS on the board if:</strong></p><ul><li>You just need reliable, simple decoupling between a producer and a consumer.</li><li>You are dealing with spiky traffic and need a massive buffer to protect your backend database.</li><li>You want absolute zero maintenance overhead and are happy living in the AWS ecosystem.</li><li>Your background jobs can tolerate eventual consistency and out-of-order processing (or you are okay using SQS FIFO within its limits).</li></ul><p>Most mature systems I work on actually end up using a combination. It’s incredibly common to see a massive Kafka cluster acting as the central nervous system of an entire company, broadcasting domain events. Then, individual teams listen to that Kafka firehose, filter out what they care about, and dump those specific tasks into a local SQS queue for their specific workers to grind through.</p><p>Use the right tool for the job, respect the difference between a command and an event, and your on-call rotations will be a lot quieter.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d1d9ff0f3173" width="1" height="1" alt=""><hr><p><a href="https://blog.stackademic.com/message-queues-vs-event-streams-or-should-i-say-kafka-vs-rabbitmq-sqs-d1d9ff0f3173">Message Queues vs Event Streams: Kafka vs (RabbitMQ, SQS)</a> was originally published in <a href="https://blog.stackademic.com/">Stackademic</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[HTTP Evolution- 1.1 vs 2.0 vs 3.0]]></title>
            <link>https://blog.stackademic.com/http-evolution-1-1-vs-2-0-vs-3-0-076277ecf491?source=rss-e4526effdd7c------2</link>
            <guid isPermaLink="false">https://medium.com/p/076277ecf491</guid>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[internet]]></category>
            <category><![CDATA[https]]></category>
            <dc:creator><![CDATA[Sameer Ahmed]]></dc:creator>
            <pubDate>Sun, 25 Jan 2026 19:45:25 GMT</pubDate>
            <atom:updated>2026-01-27T07:49:19.630Z</atom:updated>
            <content:encoded><![CDATA[<p>How each flaws lead to evolution.</p><p>Here is a detailed article about <a href="https://sameerahmed56.medium.com/http-mechanics-methods-headers-and-codes-23da48764c2b?postPublishedType=initial"><strong>HTTP 1.0</strong></a><strong>.</strong></p><p>To understand the modern web, you must understand the specific flaws of the past. Each version of HTTP was designed to fix a specific bottleneck in the version before it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/686/1*dkLv9CM_JWOWLJAMoc0Dmw.jpeg" /></figure><h3>HTTP/1.1: The Serial Queue</h3><p>HTTP/1.1 introduced <strong>Keep-Alive</strong>, which allowed us to reuse a single TCP connection for multiple files. This was a huge improvement over HTTP/1.0.</p><p>But it had a fatal design flaw: <strong>It was serial.</strong></p><h4>The Flaw: Head-of-Line (HoL) Blocking</h4><p>Imagine you are at a grocery store with only one checkout lane (the TCP connection).</p><ul><li>Customer A has 1 item (a small CSS file).</li><li>Customer B has a cart full of 500 items (a huge HD image).</li><li>Customer C has 1 item (a small JS file).</li></ul><p>In HTTP/1.1, Customer A goes first. Fast. Then Customer B starts checking out. <strong>Customer C is stuck waiting.</strong> Even though Customer C’s transaction would take 1 second, they have to wait 10 seconds for Customer B to finish.</p><p>In technical terms: If you request script.js, image.jpg, and style.css on the same connection, the server must send them <strong>one at a time, in order</strong>.</p><h4>The 1.1 Era Hacks</h4><p>To fight this, frontend engineers invented clever (and painful) workarounds:</p><ol><li><strong>Domain Sharding:</strong> Browsers limit you to ~6 parallel connections per domain. So, we created static1.cdn.com, static2.cdn.com, static3.cdn.com to trick the browser into opening 18 connections instead of 6.</li><li><strong>Concatenation:</strong> We smashed 10 JavaScript files into one giant bundle.js so we only had to make 1 request (avoiding the queue).</li><li><strong>Spriting:</strong> We combined 50 icons into one giant image to save requests.</li></ol><h3>HTTP/2: The Multiplexing Revolution (2015)</h3><p>HTTP/2 was the biggest change to the web in 15 years. It didn’t change the <em>semantics</em> (verbs, status codes, headers are the same), but it completely changed the <em>transport</em>.</p><p><strong>It stopped being a text protocol.</strong> HTTP/2 is a <strong>Binary Protocol</strong>.</p><h4>Feature 1: The Fix Multiplexing</h4><p>HTTP/2 takes that single grocery checkout lane and turns it into a magical Star Trek transporter.</p><p>It breaks every request and response into tiny <strong>Binary Frames</strong>.</p><ul><li>Frame 1: Part of image.jpg</li><li>Frame 2: Part of script.js</li><li>Frame 3: Part of image.jpg</li><li>Frame 4: Part of style.css</li></ul><p>The server creates <strong>Streams</strong> (virtual channels) inside the single TCP connection. It interleaves the frames.</p><ul><li><strong>Result:</strong> Customer C (the small JS file) doesn’t wait for Customer B (the huge image). Its frames squeeze in between the image frames. The huge image downloads in the background while the critical scripts execute immediately.</li></ul><p><strong>Death of the Hacks:</strong> With HTTP/2, Domain Sharding became an anti-pattern. One connection is actually <em>faster</em> than many. Concatenation became less critical.</p><h4>Feature 2: Header Compression (HPACK)</h4><p>In HTTP/1.1, every request sent the same headers: User-Agent, Cookie, Accept. These are repetitive and bulky. HTTP/2 compresses headers. If you send User-Agent: Chrome in Request 1, Request 2 says &quot;Same as before,&quot; sending just a few bytes.</p><h4>Feature 3: Server Push (The Failed Experiment)</h4><p>The idea: The client asks for index.html. The server knows the client <em>will</em> need style.css, so it pushes style.css before the client even asks.</p><ul><li><strong>Reality:</strong> Hard to implement correctly. It messed with browser caching (pushing files the browser already had). Chrome has recently removed support for it.</li></ul><h3>The TCP Bottleneck : Why HTTP/2 Wasn’t Enough</h3><p>HTTP/2 was amazing. It solved the <strong>Application Layer</strong> Head-of-Line blocking. But it introduced a new, hidden risk.</p><p>Because HTTP/2 puts <em>everything</em> (100 parallel streams) onto <strong>ONE</strong> TCP connection, it became incredibly vulnerable to <strong>Packet Loss</strong>.</p><p><strong>The TCP Problem (Layer 4 HoL Blocking):</strong> Recall from Article 2 that TCP guarantees order.</p><ul><li>If <strong>one single packet</strong> is lost (belonging to Stream A/Image), TCP pauses <strong>the entire connection</strong>.</li><li>It waits to re-fetch that packet.</li><li>While waiting, Stream B (CSS) and Stream C (JS) — which didn’t lose any packets — are <strong>also stuck</strong>. TCP doesn’t know they are separate streams. It just sees one big pipe of bytes.</li></ul><p>On a perfect network (WiFi), HTTP/2 is fast. On a spotty network (4G/LTE), HTTP/2 can actually be <em>slower</em> than HTTP/1.1 because one drop stalls the entire page.</p><h3>HTTP/3: The UDP Revolution (2020+)</h3><p>o solve the TCP problem, we couldn’t fix TCP. We had to abandon it. <strong>HTTP/3 runs on QUIC.</strong> And QUIC runs on <strong>UDP</strong>.</p><h4>The Fix: Independent Streams</h4><p>QUIC moves the concept of “Streams” out of the HTTP layer and down into the Transport layer.</p><ul><li><strong>Scenario:</strong> Packet 50 is lost. Packet 50 belongs to Stream A (the Image).</li><li><strong>QUIC Logic:</strong> “Okay, Stream A is paused waiting for retransmission. But Stream B (CSS) and Stream C (JS) are totally fine. Let them through.”</li><li><strong>Result:</strong> No Head-of-Line blocking anywhere. One lost packet only affects the specific resource it belonged to.</li></ul><h4>The Killer Feature: Connection Migration</h4><p>This is magic for mobile phones. <strong>Scenario:</strong> You start downloading a video on WiFi. You walk out the door. Your phone switches to 4G LTE.</p><ul><li><strong>TCP (HTTP/1.1 &amp; 2):</strong> Your IP address changed. The connection is defined by {SrcIP, SrcPort, DestIP, DestPort}. The connection breaks. The download fails. You have to restart.</li><li><strong>QUIC (HTTP/3):</strong> The connection is defined by a <strong>Connection ID (UUID)</strong>, not your IP. When you switch to 4G, your phone sends a packet from the new IP saying “Hey, it’s still me (ID: abc-123).” The server says “Cool,” and continues the download exactly where it left off. <strong>Zero interruption.</strong></li></ul><h3>Summary</h3><p>Each evolution of HTTP came with necessity and We have now optimized the pipe to be as fast as physically possible.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*KVi4-vZvztKDl61ZwRAUqg.png" /></figure><p>Thanks for checking this out :)</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=076277ecf491" width="1" height="1" alt=""><hr><p><a href="https://blog.stackademic.com/http-evolution-1-1-vs-2-0-vs-3-0-076277ecf491">HTTP Evolution- 1.1 vs 2.0 vs 3.0</a> was originally published in <a href="https://blog.stackademic.com/">Stackademic</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>