<?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 RK Singh on Medium]]></title>
        <description><![CDATA[Stories by RK Singh on Medium]]></description>
        <link>https://medium.com/@rupeshksinghmit?source=rss-79569b8bdd24------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*FSqraKrVFM3QLJfO</url>
            <title>Stories by RK Singh on Medium</title>
            <link>https://medium.com/@rupeshksinghmit?source=rss-79569b8bdd24------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 28 Nov 2026 15:40:52 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@rupeshksinghmit/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[MongoDB Under the Hood: Documents, Indexes, Replication & Sharding]]></title>
            <link>https://medium.com/@rupeshksinghmit/mongodb-under-the-hood-documents-indexes-replication-sharding-29532dd07685?source=rss-79569b8bdd24------2</link>
            <guid isPermaLink="false">https://medium.com/p/29532dd07685</guid>
            <category><![CDATA[distributed-system-design]]></category>
            <category><![CDATA[nosql-database]]></category>
            <category><![CDATA[bson]]></category>
            <category><![CDATA[mongodb]]></category>
            <category><![CDATA[database]]></category>
            <dc:creator><![CDATA[RK Singh]]></dc:creator>
            <pubDate>Sun, 13 Sep 2026 02:16:01 GMT</pubDate>
            <atom:updated>2026-09-13T02:16:01.317Z</atom:updated>
            <content:encoded><![CDATA[<p>If you’ve used MongoDB, you know the pitch: throw JSON-like documents at it, don’t worry too much about schema, and it scales out when you need it to. But what’s actually happening beneath db.collection.insertOne()? How does a document become bytes on disk, and how does MongoDB survive a crashed server or a dataset too big for one machine?</p><figure><img alt="MongoDb Architecture Overview" src="https://cdn-images-1.medium.com/max/1024/1*pARcJcMGfrJhfcUvWUANxA.png" /></figure><p>This post walks through MongoDB’s internals layer by layer — the document format, the storage engine, indexing, replication, and sharding.</p><h3>1: A document is not a row</h3><p>Say you’re storing an order in a traditional SQL database. An order has items, and it has a shipping address. Those don’t fit in a single row, so you split them into three tables and join them back together whenever you need the full picture.</p><figure><img alt="SQL vs MongoDB" src="https://cdn-images-1.medium.com/max/1024/1*uLLhCWQOX_H38SRcwj1-dg.png" /></figure><p>MongoDB lets you keep the whole thing in one place:</p><p>Here’s the actual insert:</p><pre>db.orders.insertOne({<br>  total: 89.90,<br>  address: { city: &quot;Chicago&quot;, zip: &quot;60169&quot; },<br>  items: [<br>    { sku: &quot;A1&quot;, qty: 2 },<br>    { sku: &quot;B7&quot;, qty: 1 }<br>  ]<br>})</pre><p>Notice what’s happening: address is an object <em>inside</em> the document, and items is an array of objects <em>inside</em> the document. There is no join. Reading this order is one lookup.</p><p><strong>The simple rule for beginners:</strong> if you almost always read two pieces of data together, put them in the same document. If you often need one without the other, or one of them grows without limit (like comments on a popular post), keep them separate.</p><h3>2: What’s actually stored — BSON</h3><p>MongoDB never stores JSON, and never sends JSON over the network. It uses <strong>BSON</strong> — short for Binary JSON.</p><p>Let’s see why that matters with a real example. Take this simple document:</p><pre>{ name: &quot;Ada&quot;, age: 32 }</pre><p>As JSON text, that’s 25 characters that a computer has to read left-to-right, character by character, figuring out where the quotes end and whether 32 is a number or a string. As BSON, it looks like this:</p><figure><img alt="BSON Encoding" src="https://cdn-images-1.medium.com/max/1024/1*9UnPLJ6wWntXYQaRAQhnpA.png" /></figure><p>Read that byte strip from left to right and you’ll see the pattern:</p><ol><li><strong>Total length</strong> of the document, as a 4-byte number.</li><li>Then for each field: <strong>a type tag</strong>, <strong>the field name</strong>, <strong>the value</strong>.</li><li>A single zero byte to mark the end.</li></ol><p>Three practical benefits fall out of this design.</p><p><strong>Benefit 1 — MongoDB can skip whole documents without reading them.</strong> The first four bytes say “this document is 47 bytes long.” If MongoDB doesn’t need this one, it jumps forward 47 bytes. No parsing. With JSON text, you’d have to scan every character just to find where the document ends.</p><p><strong>Benefit 2 — types are known instantly.</strong> The byte 0x10 means &quot;the next value is a 32-bit integer.&quot; MongoDB doesn&#39;t guess or convert; it just reads four bytes as an int.</p><h4>What is an ObjectId?</h4><p>MongoDB’s driver will typically generate an ObjectId before sending the document to the server. An ObjectId is a <strong>12-byte BSON value</strong>.</p><pre>db.books.insertOne({ title: &quot;Dune&quot; })<br>// { _id: ObjectId(&quot;689a2f417b3c5d9e02001f3a&quot;), title: &quot;Dune&quot; }</pre><p>The first 4 bytes represent the ObjectId’s timestamp component and the rest 8 bytes contribute towards random/counter unique id generation.</p><p>That means you can approximately determine <strong>when the ObjectId was generated</strong>. The goal is to make it extremely unlikely that two independent clients generate the same ObjectId.</p><h3>3: Where the data lives — the storage engine</h3><p>So your BSON document arrives at the server. What happens to it?</p><p>MongoDB hands it to a component called <strong>WiredTiger</strong> — the storage engine. This is the piece that decides how data is cached, compressed, and written to disk. Here’s what happens to your write.</p><p><strong>It goes into memory first.</strong> WiredTiger keeps a cache of B-tree pages in RAM — by default, roughly half your available memory. Your insert modifies a page in that cache. It does <em>not</em> immediately go to the collection file on disk. If it did, every write would cost a random disk seek, and throughput would be terrible.</p><p><strong>It also goes into the journal.</strong> Simultaneously, the operation is appended to a <strong>write-ahead log</strong> (WAL), which is a sequential append — cheap, unlike a random write. The journal is flushed to disk on a short interval (roughly every 100ms by default, or immediately if the write asked for stronger durability). This is the safety net: if the process is killed right now, the data isn’t in the collection file yet, but it <em>is</em> in the journal, and MongoDB will replay the journal on restart.</p><figure><img alt="WiredTiger Storage Engine" src="https://cdn-images-1.medium.com/max/1024/1*0DLtnjwy1NIYbk4W6aEvkA.png" /></figure><p><strong>Later, a checkpoint makes it permanent.</strong> Roughly every 60 seconds, WiredTiger writes a <strong>checkpoint</strong> — a consistent, point-in-time snapshot of all its B-trees — to the actual collection and index files. Once a checkpoint completes, everything in it is durable on disk in its final home, and the journal ahead of it can be trimmed.</p><p>This three-part structure (cache → journal → checkpoint) is the answer to “how is MongoDB fast <em>and</em> durable at the same time?” Fast because writes land in memory and a sequential log. Durable because the log is enough to reconstruct anything the checkpoint hasn’t captured yet.</p><h3>4. Multiversion Concurrency Control</h3><p>WiredTiger uses <strong>MVCC</strong> — multiversion concurrency control. Instead of overwriting a document in place, a write creates a <em>new version</em> of it. Readers that started earlier keep seeing the old version, from a consistent snapshot, and they never block waiting on the writer.</p><pre>// User A, in one connection<br>db.books.updateOne({ _id: 1 }, { $set: { price: 12.99 } })</pre><pre>// User B, at the same moment, different document<br>db.books.updateOne({ _id: 2 }, { $set: { price: 15.99 } })</pre><p>This is why MongoDB advertises <strong>document-level concurrency</strong>. Two clients updating two different documents in the same collection don’t contend at all. <strong>Two clients updating the <em>same</em> document will serialize, and one of them may get a write conflict and retry internally</strong> — but that’s a much narrower bottleneck than a collection-level or database-level lock, which is what MongoDB actually had before WiredTiger became the default.</p><p><strong>Pages are compressed on disk.</strong> Snappy is the default (fast, moderate ratio); zstd and zlib are available if you’d rather trade CPU for space.</p><h3>5. Making queries fast — Indexes</h3><p>Every single-document insert is not a single write always. Every index on that collection also has to be updated, because each index is <em>its own separate B-tree</em> that has to stay in sync. Five indexes on a collection means one insert does six B-tree updates.</p><p>Without an index, MongoDB has exactly one strategy for finding your data: read every document in the collection and check each one. That’s a <strong>COLLSCAN</strong>, and it’s O(n).</p><p>With an index, MongoDB does a B-tree seek — a handful of page reads to descend the tree — lands on the index entry, follows a pointer to the document, and fetches it. That’s an <strong>IXSCAN</strong>, and it’s O(log n). At a thousand documents, nobody notices the difference. At ten million, it’s the difference between a query and an outage.</p><p>If you are performing sort operations: without the indexes, MongoDB has to collect results and sort them in memory, and there’s a hard 100MB limit on in-memory sorts before the query fails (unless you allow disk use). A sudden Sort exceeded memory limit error in production is almost always a missing index.</p><p><strong>Partial indexes deserve a special mention.</strong> If 98% of your orders are status: &quot;complete&quot; and you only ever query the incomplete ones, a partial index with {partialFilterExpression: {status: {$ne: &quot;complete&quot;}}} gives you an index that&#39;s 2% of the size, 2% of the write cost, and just as fast for the query you actually run. It&#39;s one of the highest-leverage, least-used features in MongoDB.</p><h3>6: How MongoDB picks an index</h3><p>If a collection has several usable indexes, which one does MongoDB choose?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*B0dKxNh1dw6-LkU3E9rIng.png" /></figure><p>The query planner enumerates candidate plans — one per index that could plausibly serve the query, plus a collection scan as the fallback. It runs them all, in parallel, for a small trial period (a limited number of documents or a work budget). Whichever plan produces the most results for the least work wins, and that plan gets <strong>cached</strong> for the query’s <em>shape</em> — the pattern of fields and operators, independent of the specific values.</p><p>This explains something you may have noticed: <strong>the first run of a new query is slower than the second.</strong> That’s the race happening.</p><pre>db.books.find({ author: &quot;Author 42&quot; }).explain(&quot;executionStats&quot;)</pre><p><strong>explain(&quot;executionStats&quot;) is the single most useful diagnostic tool in MongoDB.</strong> It shows you the winning plan, the plans that lost, the stages that ran, how many documents were examined versus returned, and whether a sort happened in memory. If totalDocsExamined is vastly larger than nReturned, you have an indexing problem — and now you know exactly what to do about it. If MongoDB examined 1,000,000 documents to return 3, you have a missing or badly-ordered index.</p><p>Also check winningPlan.stage:</p><ul><li>IXSCAN → good, it used an index</li><li>COLLSCAN → it read everything</li><li>SORT → it sorted in memory, which an index could have avoided</li></ul><h3>7: Replication</h3><p>One server is one power cable away from downtime. So in production MongoDB runs as a <strong>replica set</strong> — usually three servers holding the same data.</p><p>One server is the <strong>primary</strong> and takes all the writes. The others are <strong>secondaries</strong> that copy everything the primary does.</p><p>How does the copying work? Every write on the primary is recorded in a special collection called the <strong>oplog</strong>, and secondaries continuously read that oplog and replay the same operations. That’s it — replication is just one collection everyone reads from.</p><p>If the primary dies, the remaining servers hold a vote and promote one of the secondaries using Raft algorithm. This usually takes a few seconds, and modern drivers retry the failed write automatically.</p><h3>8. Write Concern vs Read Concern</h3><p><strong>Write concern</strong> is how many members must acknowledge a write before your driver returns success:</p><pre>// Fast, but riskier<br>db.orders.insertOne(doc, { writeConcern: { w: 1 } })</pre><pre>// Slightly slower, but safe<br>db.orders.insertOne(doc, { writeConcern: { w: &quot;majority&quot; } })</pre><p>With w: 1, MongoDB says &quot;success&quot; as soon as the <em>primary</em> has the write. If that primary crashes one millisecond later, before any secondary copied it.</p><p>With w: &quot;majority&quot;, MongoDB waits until most of the servers have it. That write cannot be lost to a failover.</p><p><strong>Read concern</strong> governs what you’re allowed to see:</p><ul><li>local — whatever this node has, including writes that might still be rolled back.</li><li>majority — only data acknowledged by a majority.</li><li>snapshot — a consistent point-in-time view across the whole operation, used with transactions.</li></ul><h3>9: Sharding</h3><p>Replication gives you copies. It doesn’t give you capacity — every member still holds the entire dataset. When the data or the write throughput outgrows a single machine, you <strong>shard</strong>.</p><p>You pick a field to split on — the <strong>shard key</strong>. MongoDB divides the range of values into <strong>chunks</strong>, and each chunk lives on one shard. A background <strong>balancer</strong> moves chunks around to keep things even.</p><h3>10. Targeted vs scatter-gather</h3><p>This is the thing to understand about sharded queries.</p><p>If your query <strong>includes the shard key</strong>, mongos looks up which chunk owns that value and routes the query to exactly one shard. Fast, and it scales linearly — twice the shards, twice the throughput.</p><p>If your query <strong>omits the shard key</strong>, mongos has no idea where the data lives. It must broadcast to <em>every</em> shard, wait for all of them, and merge the results. That’s a scatter-gather, and it scales badly: every shard does work for every query, so adding shards stops helping.</p><h3>Final Thoughts</h3><p>Here’s the whole path your document took:</p><p><strong>Write:</strong> driver serializes to BSON → server hands it to WiredTiger → lands in the in-memory cache and the write-ahead journal → every index B-tree is updated → a checkpoint eventually persists it → the oplog entry replicates to secondaries → (if sharded) it lives in whichever chunk its shard key falls into.</p><p><strong>Read:</strong> mongos routes to a shard (or all of them) → the query planner races candidate plans and caches the winner → an index scan seeks the B-tree → a FETCH pulls the document (unless the query is covered) → results merge and return.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=29532dd07685" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[What Really Happens Inside ZooKeeper? Leader Election, Znodes & Watches]]></title>
            <link>https://medium.com/@rupeshksinghmit/what-really-happens-inside-zookeeper-leader-election-znodes-watches-3b96a020613f?source=rss-79569b8bdd24------2</link>
            <guid isPermaLink="false">https://medium.com/p/3b96a020613f</guid>
            <category><![CDATA[design-systems]]></category>
            <category><![CDATA[apache-zookeeper]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[backend-development]]></category>
            <category><![CDATA[distributed-systems]]></category>
            <dc:creator><![CDATA[RK Singh]]></dc:creator>
            <pubDate>Sat, 05 Sep 2026 05:26:00 GMT</pubDate>
            <atom:updated>2026-09-05T05:26:00.891Z</atom:updated>
            <content:encoded><![CDATA[<p>ZooKeeper looks intimidating from the outside — “consensus,” “quorum,” “ZAB protocol” — but underneath, it’s built from a small number of simple ideas stacked on top of each other.</p><h3>1. What Problem Is ZooKeeper Actually Solving?</h3><p>Imagine you’re running 50 servers for a distributed application (like Kafka, HBase, or your own microservices). They all need to agree on things like:</p><ul><li>“Who is the leader right now?”</li><li>“What’s the current config value for max_connections?&quot;</li><li>“Is server #7 still alive?”</li><li>“Can I get an exclusive lock on this resource?”</li></ul><p><em>Any single server could answer these questions for itself, but the servers need to </em><strong><em>agree</em></strong><em> with each other — and machines crash, networks partition, and messages get delayed or lost. </em>Solving “how do a bunch of unreliable machines agree on one shared truth” from scratch is genuinely hard.</p><p>ZooKeeper is a small, dedicated cluster whose only job is to be that <strong>shared source of truth</strong>. Your application servers don’t solve coordination problems themselves — they just ask ZooKeeper.</p><h3>2. The Data Model: It’s Just a Tiny Filesystem</h3><p>ZooKeeper stores data in a tree, exactly like a filesystem’s directory structure. Each node in the tree is called a <strong>znode</strong>.</p><ul><li><strong>Every znode can hold data AND have children.</strong> It can store bytes <em>and</em> have sub-nodes.</li><li><strong>Data is small.</strong> Znodes are meant to hold small pieces of coordination data (a config value, a hostname, a lock marker) — typically under 1MB, ideally much smaller. It is <strong>not</strong> a database or a file store.</li><li><strong>Every znode has metadata</strong>: version numbers, timestamps, and the number of children. This metadata is what makes safe concurrent updates possible.</li></ul><figure><img alt="Znode Tree" src="https://cdn-images-1.medium.com/max/1024/1*r3d-YS1BEvRPuDClyGFUAQ.png" /></figure><h3>3. Types of znodes</h3><p>This is one of the most important things to understand, because almost every ZooKeeper “recipe” (lock, leader election, queue) is built entirely out of these four flavors:</p><p><strong>Persistent</strong> — Survives client disconnects and even ZooKeeper restarts (it’s written to disk). Used for anything that should outlive the process that created it, like /config/db.</p><p><strong>Ephemeral</strong> — Tied to the session, not the connection. A brief network blip won’t delete it (ZooKeeper has a session timeout), but if the client crashes or the session formally expires, it disappears. Good for “is this service alive” checks because cleanup is automatic — no orphaned entries to garbage-collect. One restriction: ephemeral nodes can’t have children.</p><p><strong>Persistent Sequential</strong> — ZooKeeper appends a monotonically increasing 10-digit counter to the name (e.g., task-0000000001), guaranteed unique and ordered even with concurrent creators. Great for FIFO task queues where you want strict processing order and durability.</p><p><strong>Ephemeral Sequential</strong> — The combo that makes distributed locks and leader election work cleanly:</p><ol><li>Each client creates /locks/lock- with the sequential+ephemeral flags.</li><li>Whoever gets the lowest sequence number holds the lock/is leader.</li><li>Everyone else watches the node just below their own number (not all of them — avoids the “herd effect” where every waiter wakes up on every change).</li><li>If the lock holder crashes, its ephemeral node vanishes automatically, triggering the next-in-line’s watch — no manual lock release needed, no deadlock from a dead holder.</li></ol><p><strong>Example:</strong> if three servers register themselves under /app1/workers as ephemeral sequential nodes, ZooKeeper names them:</p><pre>/app1/workers/worker-0000000001<br>/app1/workers/worker-0000000002<br>/app1/workers/worker-0000000003</pre><p>If the server that created worker-0000000002 crashes, its TCP connection drops, its <strong>session</strong> eventually expires, and ZooKeeper <strong>automatically deletes that znode</strong>. This single mechanic is the foundation for most of ZooKeeper&#39;s use cases.</p><h3>4. Sessions: The Heartbeat Underneath Everything</h3><p>When a client connects to ZooKeeper, it doesn’t just open a TCP socket — it establishes a <strong>session</strong>.</p><ul><li>The client picks a sessionTimeout (e.g., 10 seconds).</li><li>The client (or its library) sends periodic pings to keep the session alive.</li><li>If the ZooKeeper ensemble doesn’t hear from the client within the timeout, the session <strong>expires</strong>, and every ephemeral znode owned by that session is deleted.</li><li>Crucially: a session <strong>survives</strong> the client disconnecting from one server and reconnecting to another. ZooKeeper clients keep a list of all servers in the ensemble and silently fail over between them. The session ID stays the same.</li></ul><h3>5. Watches: “Tell Me When Something Changes”</h3><p>Polling ZooKeeper repeatedly to check “has this value changed yet?” would be wasteful and slow. Instead, clients set a <strong>watch</strong>.</p><p>A watch is a <strong>one-time trigger</strong>: “next time this znode changes, send me a notification.” It works like this:</p><ol><li>Client reads /app1/config and, in the same call, registers a watch on it.</li><li>Later, another client updates /app1/config.</li><li>ZooKeeper pushes a notification to the watching client: “this changed.”</li><li>The watch is now <strong>consumed</strong> — if the client wants to keep watching, it must re-register.</li></ol><p><strong>Why one-time and not continuous?</strong> Two reasons: it keeps the server’s bookkeeping simple (no need to track “still interested” state forever), and it forces clients to re-read the current state after being notified — which avoids a subtle race where a client assumes it knows the <em>new</em> value just because it got notified, when in reality several more changes might have already happened.</p><figure><img alt="Zookeeper Watch Mechanism" src="https://cdn-images-1.medium.com/max/1024/1*ofTmozeseUnrqe7INpK5xA.png" /></figure><p><strong><em>Watches are the mechanism behind “notify me when the leader changes” or “notify me when a new worker joins.”</em></strong></p><h3>6. The Ensemble: Why There Are Multiple Servers</h3><p>Running ZooKeeper as a single server would make it a single point of failure — exactly the kind of thing it’s supposed to protect <em>other</em> systems from. So ZooKeeper runs as a cluster of servers called an <strong>ensemble</strong>, typically 3, 5, or 7 machines.</p><p>Every server in the ensemble holds a <strong>full copy</strong> of the entire data tree in memory (backed by disk for durability). One server is elected <strong>Leader</strong>; the rest are <strong>Followers</strong>. All servers can serve <strong>reads</strong> directly from their own local copy, but only the Leader can process <strong>writes</strong> — followers forward write requests to the leader.</p><figure><img alt="Ensemble Quorum" src="https://cdn-images-1.medium.com/max/1024/1*sksZ3177OYNAK2jzRrYIrQ.png" /></figure><p><strong>Why an odd number of servers?</strong> Because ZooKeeper uses <strong>majority voting</strong> (quorum) to decide whether a write succeeded. With 5 servers, a majority is 3. That means the ensemble can tolerate <strong>2</strong> servers failing and keep working. With an even number like 6, you’d need 4 for a majority, but you could still only tolerate 2 failures — you’d be paying for an extra server without gaining any extra fault tolerance. <strong><em>Odd numbers give you the best fault-tolerance-per-server.</em></strong></p><h3>7. How a Write Actually Happens</h3><p>This is the heart of ZooKeeper. The protocol is called <strong>ZAB — ZooKeeper Atomic Broadcast</strong>. Don’t let the name scare you; the idea is straightforward once you walk through it.</p><p><strong>Goal:</strong> every server in the ensemble must apply writes in the <em>exact same order</em>, even if servers crash or messages arrive late.</p><p>Here’s what happens when a client writes data:</p><ol><li><strong>Every write goes through the Leader.</strong> Even if the client is connected to a Follower, that Follower just forwards the request.</li><li><strong>The Leader stamps it with a zxid</strong> (ZooKeeper transaction ID) — a strictly increasing number. This is what guarantees ordering: transaction 105 always happens before 106, everywhere, no exceptions.</li><li><strong>The Leader proposes the change to all Followers</strong> and waits for a <strong>majority</strong> to acknowledge they’ve written it to their own local log.</li><li><strong>Once a majority ACKs, the Leader commits</strong> — tells everyone (including itself) to actually apply the change to the in-memory tree, and confirms success to the client.</li></ol><figure><img alt="Zookeeper ZAB Write Path" src="https://cdn-images-1.medium.com/max/1024/1*aYIgOIOLCFQ-ZSbglsQRSQ.png" /></figure><p>Notice: the Leader does <strong>not</strong> need to hear back from <em>every</em> follower — just a majority. That’s the whole point of majority voting — a couple of slow or dead followers can’t block the entire system, and yet every committed transaction is guaranteed to survive on enough servers that it can never be “forgotten,” even if the Leader crashes immediately after committing.</p><h3>8. Why writes are slower than reads</h3><p>Because a write needs a network round-trip to a majority of servers before it’s considered durable, writes are inherently more expensive than reads. Reads are served instantly from a server’s local memory — which also means <strong>a read might be slightly stale</strong> if that server hasn’t yet received the latest commit. This is an intentional trade-off.</p><h3>9. Leader Election: What Happens When the Leader Dies</h3><p>If the Leader crashes, the ensemble can’t process writes until a new Leader is chosen. This happens automatically:</p><p>Every server enters the <strong>Looking</strong> state and starts exchanging votes with its peers. Each server votes based on two simple rules, checked in order:</p><ol><li><strong>Whoever has the highest zxid wins</strong> — that server has seen the most recent data, so it’s the safest choice to become leader (it can’t “lose” any committed transactions).</li><li><strong>If zxids are tied, whoever has the highest server ID wins</strong> — just a deterministic tie-breaker.</li></ol><p>Once a server collects votes from a <strong>majority</strong> of the ensemble for the same candidate, that candidate becomes the new Leader, and everyone else becomes a Follower reporting to it. This whole process (called <strong>Fast Leader Election</strong> in ZooKeeper’s implementation) typically takes a few hundred milliseconds to a couple of seconds — during which the cluster <strong>can’t accept writes</strong>, but can often still serve reads.</p><h3>10. Consistency Guarantees (What You Can and Can’t Rely On)</h3><p>ZooKeeper deliberately does not promise the strongest possible consistency by default, because that would make every read as slow as a write. Instead it promises something weaker but still very useful:</p><ul><li><strong>Sequential Consistency:</strong> all updates from a single client are applied in the order the client sent them.</li><li><strong>Atomicity:</strong> a write either fully succeeds or fully fails — no partial updates visible.</li><li><strong>Durability:</strong> once a write is acknowledged, it survives crashes (because it made it to a majority of servers’ logs).</li><li><strong>Timeliness (but not real-time guarantee):</strong> a client’s view will catch up to the latest state within a bounded time, but a read right after someone else’s write can, in rare cases, return slightly stale data — <em>unless</em> the client calls sync() first, which forces it to catch up to the leader before reading.</li></ul><p>The practical takeaway: <strong>treat ZooKeeper reads as “recent, not necessarily instantaneous.” </strong><em>For coordination tasks (locks, leader election), this is completely fine,</em> because those recipes are designed around watches and ordering rather than around every read being perfectly up-to-the-millisecond.</p><h3>11. Putting It Together</h3><p>All of ZooKeeper’s famous use cases are just combinations of the primitives above (znode types + watches + sequential ordering). No special server-side code is needed — it’s all client-side logic on top of a few basic operations.</p><h4>Distributed lock</h4><ul><li>The client creates an <strong>ephemeral sequential znode</strong> under /locks/mylock/lock-.</li><li>The client lists all child znodes under /locks/mylock/.</li><li>If its znode has the <strong>lowest sequence number</strong>, the client acquires the lock.</li><li>Otherwise, the client sets a <strong>watch on the immediately preceding znode</strong> in the sequence — not on every znode. This prevents the <strong>herd effect</strong>, where all waiting clients wake up whenever the lock is released.</li><li>When the watched znode is deleted — because its owner released the lock or crashed — the watch is triggered. The client then re-checks the list to determine whether its znode is now first in line.</li></ul><figure><img alt="Zookeeper Distributed Lock" src="https://cdn-images-1.medium.com/max/1024/1*hHRo-jaAgLiA18eX--SH8A.png" /></figure><h3>12. Common Mistakes Developers Make</h3><ul><li><strong>Storing large data in znodes.</strong> ZooKeeper is not a database. Every write goes through the full ZAB replication path across every server — big payloads make everyone slower.</li><li><strong>Using ZooKeeper for high-frequency data.</strong> If a value changes many times per second, ZooKeeper is the wrong tool — it’s built for coordination metadata that changes occasionally, not a fast-moving data stream.</li><li><strong>Forgetting that watches are one-shot.</strong> Code that sets a watch once and expects to be notified forever will silently stop getting updates after the first event.</li><li><strong>Assuming reads are always the absolute latest value.</strong> For most coordination use cases this doesn’t matter, but if you need a guaranteed up-to-date read, call sync() before reading.</li><li><strong>Setting session timeouts too short.</strong> A slow garbage-collection pause or network blip can cause a session to expire, deleting all of that client’s ephemeral nodes (e.g., dropping a held lock) even though the process is still alive and well.</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3b96a020613f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Apache Cassandra Internals: How Data Is Stored, Read, and Written]]></title>
            <link>https://medium.com/@rupeshksinghmit/apache-cassandra-internals-how-data-is-stored-read-and-written-6d00e7dcb695?source=rss-79569b8bdd24------2</link>
            <guid isPermaLink="false">https://medium.com/p/6d00e7dcb695</guid>
            <category><![CDATA[apache-cassandra]]></category>
            <category><![CDATA[backend-development]]></category>
            <category><![CDATA[nosql-database]]></category>
            <category><![CDATA[distributed-systems]]></category>
            <category><![CDATA[database]]></category>
            <dc:creator><![CDATA[RK Singh]]></dc:creator>
            <pubDate>Tue, 01 Sep 2026 04:19:01 GMT</pubDate>
            <atom:updated>2026-09-01T04:19:01.027Z</atom:updated>
            <content:encoded><![CDATA[<p>If you’ve only used relational databases, Cassandra can feel backwards at first. You don’t design tables around your data — you design them around your <em>queries</em>. There’s no JOIN. There&#39;s no single &quot;correct&quot; normalized schema. And the things that make Cassandra fast (no master, sequential writes, immutable files) are the same things that make it behave differently from Postgres or MySQL under the hood.</p><h3>1. The Big Idea: Query-First Design</h3><p>In a relational database, you model your entities and relationships first, then write whatever query you need — the database figures out how to join things efficiently.</p><p>In Cassandra, there are no joins and no expensive ad-hoc queries. So the rule is:</p><blockquote><strong><em>Design your tables around the exact queries your application will run — not around the shape of your data.</em></strong></blockquote><p>If you have three different ways you need to look up a user (by ID, by email, by signup date), you’ll likely end up with three tables, each holding a copy of the same data, organized differently. That’s normal in Cassandra. Storage is cheap; scatter-gather queries across a distributed cluster are not.</p><h3>2. Keyspaces, Tables, and Keys</h3><p>A <strong>keyspace</strong> is roughly like a “database” in MySQL — a namespace for tables, with its own replication settings.</p><pre>CREATE KEYSPACE blog_app<br>WITH replication = {<br>  &#39;class&#39;: &#39;NetworkTopologyStrategy&#39;,<br>  &#39;datacenter1&#39;: 3<br>};</pre><p>This says: “In datacenter1, keep 3 copies of every row in this keyspace.&quot; That 3 is the <strong>replication factor (RF)</strong> — it&#39;s set per keyspace, not per table.</p><h4>Tables and the primary key</h4><p>Every Cassandra table has a <strong>primary key</strong>, and that primary key has two conceptually different parts:</p><pre>CREATE TABLE blog_app.posts_by_user (<br>  user_id     UUID,<br>  post_time   TIMESTAMP,<br>  post_id     UUID,<br>  title       TEXT,<br>  body        TEXT,<br>  PRIMARY KEY (user_id, post_time)<br>);</pre><ul><li><strong>Partition key</strong> — user_id. This decides <em>which node(s)</em> store the row. Cassandra hashes it to a token and places it on the ring (more on that in a minute).</li><li><strong>Clustering key(s)</strong> — post_time. This decides the <em>sort order of rows within a partition</em> on disk.</li></ul><p>This single distinction — partition key vs. clustering key — is the most important thing to understand about Cassandra data modeling.</p><figure><img alt="Cassandra Good Query vs Bad Query" src="https://cdn-images-1.medium.com/max/1024/1*xo3uKyBycKFC0wGIX4PbAg.png" /></figure><p><strong>Rule of thumb:</strong> everything in the WHERE clause of your main query should map to the partition key (for equality) and clustering columns (for equality or ranges). If it doesn&#39;t, you probably need a different table.</p><h3>3. What Actually Happens on the Ring</h3><p>Nodes in a Cassandra cluster are arranged in a logical <strong>ring</strong>. Every partition key hashes to a <strong>token</strong>, and the node owning that token range stores the data — plus, based on the replication factor, the next couple of nodes going clockwise store copies too.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PXSX1XuXPTNYrsCk4Uh1pg.png" /></figure><p>There’s no master node deciding this — any node can compute where a key lives just from hashing it, and any node can act as the <strong>coordinator</strong> for a client’s request, forwarding it to the right replicas.</p><p>This is <em>why</em> the partition key matters so much for queries: WHERE user_id = ? lets the coordinator go straight to the 1–3 nodes that own that partition.</p><h3>4. What Happens When You Write</h3><p>Cassandra writes are sequential — that’s what makes them fast.</p><p>When you run an INSERT or UPDATE:</p><ol><li>The coordinator node appends the write to its <strong>commit log</strong> (a sequential file on disk, purely for crash recovery).</li><li>It also applies the write to the <strong>memtable</strong> (an in-memory, sorted structure).</li><li>The coordinator forwards the write to the other replica nodes, and waits for however many acknowledgements your <strong>consistency level</strong> requires (more on this below).</li><li>Later, when the memtable fills up, it’s <strong>flushed</strong> to disk as an immutable file called an <strong>SSTable</strong>.</li></ol><figure><img alt="Cassandra Write Path" src="https://cdn-images-1.medium.com/max/1024/1*q0GrGczxsizWjQubq7NPuA.png" /></figure><p>Because steps 1 and 2 are just appends — no seeking around a file to update a row in place — writes in Cassandra are cheap even under heavy load. This is also why Cassandra doesn’t do “real” updates or deletes: an UPDATE is really just a new write with a newer timestamp, and a DELETE writes a <strong>tombstone</strong> (a marker saying &quot;ignore anything older for this row&quot;). The old data doesn&#39;t disappear until compaction cleans it up later.</p><pre>-- This isn&#39;t a true &quot;update&quot; under the hood — it&#39;s a new, timestamped write<br>UPDATE blog_app.posts_by_user<br>SET title = &#39;Updated title&#39;<br>WHERE user_id = 3f2504e0-4f89-11d3-9a0c-0305e82c3301<br>  AND post_time = &#39;2026-08-01 10:00:00&#39;;</pre><h3>5. What Happens When You Read</h3><p>Reads are more work than writes, because the data for one partition might be spread across the memtable <em>and</em> several SSTables on disk.</p><figure><img alt="Cassandra Read Path" src="https://cdn-images-1.medium.com/max/1024/1*-ewqeDxRd8JUh9JEBuNO-Q.png" /></figure><ol><li><strong>Memtable</strong> — is there unflushed data for this key?</li><li><strong>Bloom filters</strong> — for each SSTable, a small in-memory structure can say “this key is <em>definitely not</em> in this file” almost for free, so most SSTables get skipped without touching disk.</li><li><strong>SSTables</strong> that survive the Bloom filter check get read from disk (using an index to jump straight to the right spot).</li></ol><p>Everything found gets merged by timestamp — the newest write for each column wins.</p><h3>6. Storage Engine: Why It’s Called an LSM-Tree</h3><p><strong>Log-Structured Merge-tree</strong>: writes always land in memory and a log first, and only get turned into optimized on-disk files later.</p><p>Because SSTables are immutable and just keep accumulating, Cassandra periodically runs <strong>compaction</strong>: merging several SSTables into fewer, larger ones, dropping obsolete versions and expired tombstones along the way. This keeps read performance from degrading as more data (and more updates/deletes) pile up.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*R0wLL_IlBL-k3AFZpu3DjA.png" /></figure><p>You don’t need to manage this by hand day-to-day, but picking the right strategy for a table (WITH compaction = {&#39;class&#39;: &#39;TimeWindowCompactionStrategy&#39;, ...}) matters a lot for performance at scale.</p><h3>7. Consistency Levels: Choosing Your Trade-off Per Query</h3><p>Because data is replicated, every read and write in Cassandra can specify how many replicas need to respond before it’s considered successful — this is the <strong>consistency level (CL)</strong>.</p><pre>SELECT * FROM blog_app.posts_by_user WHERE user_id = 3f2504e0-4f89-11d3-9a0c-0305e82c3301;</pre><p>Common levels:</p><ul><li>ONE — fastest, least safe. Only one replica needs to respond.</li><li>QUORUM — a majority of replicas (RF/2 + 1) must respond. Good default for most apps.</li><li>LOCAL_QUORUM — quorum within your local data center only (faster in multi-DC setups).</li><li>ALL — every replica must respond. Strongest consistency, worst availability — if one replica is down, the query fails.</li></ul><p>A very common pattern: use QUORUM for both reads and writes. Since a majority always overlaps with another majority, you&#39;re guaranteed to read the latest write, without ever needing ALL.</p><h3>9. Secondary Indexes and Materialized Views</h3><p>Sometimes you really do need to search by a column that isn’t part of your primary key. Cassandra gives you two ways to do this — but both come with trade-offs, so use them carefully.</p><p><strong>Secondary index</strong> — lets you search by a column that isn’t a key:</p><pre>CREATE INDEX ON blog_app.posts_by_user (post_id);<br>SELECT * FROM blog_app.posts_by_user WHERE post_id = &lt;some-uuid&gt;;</pre><p>This works, but here’s the catch: Cassandra has to check <em>every node</em> in the cluster to answer it, because the index only knows about the data stored on its own node. That’s fine for a small cluster or a column with only a few possible values, but it gets slow fast on a big cluster.</p><p><strong>Materialized view</strong> — this is like asking Cassandra to automatically keep a second copy of your table, organized around a different query:</p><pre>CREATE MATERIALIZED VIEW blog_app.posts_by_id AS<br>  SELECT * FROM blog_app.posts_by_user<br>  WHERE post_id IS NOT NULL AND user_id IS NOT NULL AND post_time IS NOT NULL<br>  PRIMARY KEY (post_id, user_id, post_time);</pre><p>It saves you from writing code to update two tables yourself — Cassandra does it for you in the background. The downside is extra write work behind the scenes, and in rare cases (like network issues), the view can fall out of sync with the original table. Because of this, many teams just create and update a second table themselves instead of relying on materialized views.</p><p><strong>Bottom line:</strong> don’t reach for these as your first option. If you find yourself needing to query by a different column, the simplest and safest fix is usually just making a new table built for that exact query.</p><h3>Final thoughts</h3><p>Cassandra works differently from the databases most developers grow up using, but once the basics click, it’s not complicated. The partition key decides where your data lives, and the clustering key decides the order it’s stored in — almost everything else follows from that. Writes are fast because they just get appended, and reads use smart tricks like Bloom filters to avoid wasted lookup. Instead of one big table with joins, you build a few small tables, each made for one specific query. Keep that idea in mind, and Cassandra starts to feel a lot more logical.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6d00e7dcb695" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How Kafka Actually Works: A Deep Dive Into Its Internals]]></title>
            <link>https://medium.com/@rupeshksinghmit/how-kafka-actually-works-a-deep-dive-into-its-internals-19d4ec738a19?source=rss-79569b8bdd24------2</link>
            <guid isPermaLink="false">https://medium.com/p/19d4ec738a19</guid>
            <category><![CDATA[design-systems]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[distributed-systems]]></category>
            <category><![CDATA[backend-development]]></category>
            <category><![CDATA[apache-kafka]]></category>
            <dc:creator><![CDATA[RK Singh]]></dc:creator>
            <pubDate>Sat, 22 Aug 2026 17:23:02 GMT</pubDate>
            <atom:updated>2026-08-22T17:23:02.458Z</atom:updated>
            <content:encoded><![CDATA[<p>The first time most engineers encounter Kafka, they learn that it’s a “distributed messaging system” or an “event streaming platform.” Both descriptions are technically accurate but they don’t tell you why Kafka handles a million messages per second while a traditional queue would have collapsed, or why a consumer crash loses no data, or why adding more brokers to a cluster linearly increases throughput.</p><p>By the end, you’ll know not just <em>what</em> Kafka does but <em>why</em> it’s built the way it is.</p><h3>The Commit Log or Append-Only Log</h3><p>Before Kafka has brokers, partitions, producers, or consumers, it has one idea: an <strong>append-only log</strong>.</p><p>The insight is simple: a log that only ever grows is the easiest possible thing to make durable, replicate, and reason about. Nothing is updated in place. Nothing is deleted on read. The past is immutable.</p><p>Every partition in Kafka is exactly this — an append-only file on disk. Each new record gets written to the end. Each record receives a monotonically increasing integer called an <strong>offset</strong> — its permanent address in that partition, forever. Offset 0 is always the first record. Offset 10,000 is always the 10,001st.</p><p>This immutability is not a constraint. It’s the source of most of Kafka’s best properties:</p><ul><li>Consumers can read independently because reading doesn’t remove data</li><li>Replication is straightforward because followers just append what the leader has</li><li>Failure recovery is clean because there are no partial updates to roll back</li><li>Multiple consumers reading the same data don’t need to coordinate</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*u84ZGmhhfjOa1hDVd5wmEA.png" /></figure><h4><strong>Segments, not one giant file</strong></h4><p>Kafka doesn’t write a partition as a single file that grows forever. It breaks each partition into <strong>segments</strong> — bounded chunks of the log, each with a corresponding index file. Only the active segment accepts new writes. When a segment reaches its configured size (log.segment.bytes, default 1 GB) or age, it&#39;s sealed and a new segment opens.</p><p>This matters for three reasons. First, retention becomes efficient: Kafka deletes whole segments rather than scanning records. Second, the index files make random reads fast — if a consumer asks for offset 50,000, Kafka uses the index to find the nearest segment file and seeks within it, rather than scanning from byte zero.</p><h4>Retention: three policies</h4><p>Kafka keeps data according to one of three cleanup policies, configured per topic:</p><p><strong>Time-based</strong> (retention.ms): segments older than the threshold are deleted. The default is seven days.</p><p><strong>Size-based</strong> (retention.bytes): the oldest segments are deleted when the total partition size exceeds the threshold. Useful as a secondary cap alongside time-based retention.</p><h3>Topics and partitions: where scaling lives</h3><p>A topic is a name. It’s a logical label for a category of events — orders, payments, user-signups. The actual data doesn&#39;t live in the topic. It lives in the topic&#39;s <strong>partitions</strong>.</p><p>When you create a topic with three partitions, you get three independent append-only logs. Each has its own offset sequence starting at zero. Each lives on a different broker. Each is independently readable and writable.</p><p>This is <strong>Kafka’s horizontal scaling mechanism</strong>. More partitions means:</p><ul><li>More producers writing in parallel (each producer can target a different partition)</li><li>More consumers reading in parallel (each consumer in a group owns a subset of partitions)</li><li>More brokers sharing the load (partitions are distributed across the cluster)</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vi7nXkgkTtGEzFN63GFtDA.png" /></figure><h3>How producers pick a partition</h3><p>When a producer sends a message, it must route it to a specific partition. The routing strategy depends on what the producer provides:</p><p><strong>With a message key</strong>: the key is hashed (murmur2 by default) and the result is taken modulo the partition count. The same key always lands on the same partition. This is the guarantee that makes ordering meaningful — all events for a given user ID, order ID, or device ID arrive in the sequence they were produced.</p><p><strong>Without a message key</strong>: the producer distributes records across partitions using a sticky partitioning strategy (introduced in Kafka 2.4). Rather than round-robin each individual record, it fills a batch for one partition before moving to the next. This improves batching efficiency significantly.</p><p>The critical implication of key-based routing: ordering is guaranteed <strong><em>within a partition</em>,</strong> not across partitions. If you publish events for order 42 with key order-42, all those events land on the same partition in sequence. If you have 100,000 different order IDs, they&#39;re spread across your partitions and each partition is independently ordered.</p><h4>Producers: two threads, one buffer</h4><p>A Kafka producer is deceptively simple from the outside. You call producer.send(record). The record appears in Kafka. Done.</p><p>Underneath, two threads are doing different things.</p><p>Your <strong>application thread</strong> calls send(). This doesn&#39;t put the record on the network. It puts it into an in-memory data structure called the RecordAccumulator — a per-partition queue of record batches. The call returns almost immediately.</p><p>The <strong>sender thread</strong> runs in the background, continuously checking whether any batches are ready to send. A batch becomes ready when either:</p><ul><li>It has accumulated batch.size bytes (default 16 KB), or</li><li>linger.ms milliseconds have elapsed since the first record was added</li></ul><p>When a batch is ready, the sender thread compresses it (if configured), constructs a network request, and sends it to the appropriate broker via the NetworkClient. The broker writes the batch, replicates it (depending on acks), and sends an acknowledgment back. If the ack doesn&#39;t arrive, the sender retries.</p><p><strong>This design has two important consequences</strong>. First, the producer never blocks your application code on I/O — send() always returns quickly. Second, it enables batching: if records arrive faster than they can be sent, they accumulate in the accumulator and leave in larger batches, which means fewer network round-trips and better compression ratios.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SGtexKyVFVB5PGXJYrEt1A.png" /></figure><h4>The acks tradeoff</h4><p>The acks configuration controls when the broker considers a write successful:</p><ul><li>acks=0: fire and forget. The producer doesn&#39;t wait for any confirmation. Fastest possible. Silent data loss on broker crash.</li><li>acks=1: the leader writes to its local log and acks immediately. Followers may not have the record yet. Data loss is possible if the leader crashes before followers replicate.</li><li>acks=all (or acks=-1): the leader waits for all in-sync replicas (ISR) to confirm before acking. No data loss as long as at least one ISR member is alive. Slower.</li></ul><p>For production, acks=all paired with min.insync.replicas=2 and replication.factor=3 is the safe combination. This means at least two brokers must confirm every write, and your data survives any single broker failure.</p><h3>Idempotent producers and ordering</h3><p>Retries create an ordering hazard. Suppose batch A fails, batch B succeeds, then batch A’s retry arrives. Partition ordering is violated.</p><p>The fix is enable.idempotence=true. The broker assigns the producer a <strong>producer ID</strong> (PID) and tracks a sequence number per partition. When a retried batch arrives, the broker checks the sequence number against what it already has — a duplicate is silently discarded, preserving exactly-once delivery within a session. With idempotence enabled, up to five batches can be in-flight simultaneously without ordering risk.</p><p>For exactly-once semantics across multiple partitions or across produce + consume + produce pipelines, Kafka adds <strong>transactions</strong>: an API that wraps multiple partition writes in an atomic commit, so consumers reading with isolation.level=read_committed see all of them or none.</p><h3>Replication — ISR: how Kafka avoids losing data</h3><p>Each partition has a configured replication factor — typically three in production. This means the partition’s data exists on three brokers simultaneously. One broker is the <strong>leader</strong>: all reads and writes go through it. The others are <strong>followers</strong>: they continuously fetch from the leader and replicate the data.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0MJUqiwVfre7dRFUEXjuug.png" /></figure><h4>The ISR</h4><p>Kafka tracks which followers are genuinely caught up in a set called the <strong>In-Sync Replicas (ISR)</strong>. A follower stays in the ISR as long as it has replicated up to the leader’s position within replica.lag.time.max.ms (default 30 seconds). If a follower falls behind — due to a GC pause, disk pressure, or network trouble — Kafka removes it from the ISR.</p><p>The <strong>high watermark (HW)</strong> is the offset up to which all ISR members have confirmed the data. Consumers can only read up to the high watermark. This prevents a consumer from reading data that might be rolled back if the leader fails before followers replicate it.</p><p>When the leader fails, the Kafka controller elects a new leader from the surviving ISR usually within seconds.</p><h4>Unclean leader election</h4><p>If the entire ISR goes down, no safe leader exists. By default (unclean.leader.election.enable=false), Kafka waits for an ISR member to come back rather than elect an out-of-sync replica. This prioritizes consistency over availability.</p><p>Setting unclean.leader.election.enable=true allows an out-of-sync replica to become leader, restoring availability at the cost of potential data loss — you explicitly acknowledge that some committed records may vanish.</p><h3>Consumers: pull, offsets, and the group protocol</h3><p>Kafka consumers pull records from the broker on their own schedule, calling poll() in a loop. The broker never pushes. This is a deliberate design choice: a slow consumer doesn&#39;t get overwhelmed, it just falls behind and processes at its own pace.</p><h4>Offset tracking</h4><p>A consumer’s position in a partition is tracked by its <strong>committed offset</strong> — the last offset it successfully processed and acknowledged. This is stored in an internal Kafka topic called __consumer_offsets, which is itself a replicated, durable log. When a consumer crashes and restarts, it reads __consumer_offsets to find where it left off and resumes from there.</p><p>The danger of enable.auto.commit=true (the default): Kafka commits the current offset every five seconds, regardless of whether your code has finished processing those records. A crash between the auto-commit and the completion of your processing means those records are marked done but were never fully handled. No error is raised. No alert fires. Data is silently skipped.</p><p>The safe pattern is manual commit: call commitSync() after your processing is complete for each batch. This gives you at-least-once delivery.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*H6j4K8Fc1ndqgjbe47twRw.png" /></figure><h4>Consumer groups and partition assignment</h4><p>Multiple instances of the same service form a <strong>consumer group</strong>, identified by a shared group.id. Kafka assigns each partition to exactly one member of the group at a time. With three partitions and three consumer instances, each instance owns one partition. Add a fourth instance and it sits idle — it can&#39;t own a partition that&#39;s already owned.</p><p>When group membership changes (a consumer joins, leaves, or fails a heartbeat), Kafka triggers a <strong>rebalance</strong> — a reassignment of partitions among surviving members. During a rebalance, all consumers stop reading. This is called a <strong>stop-the-world pause</strong>.</p><p>The modern <strong>cooperative sticky rebalancing</strong> protocol (enabled with partition.assignment.strategy=CooperativeStickyAssignor) only revokes the partitions that actually need to move. Consumers that keep their partitions never stop reading.</p><h3>KRaft: Kafka without ZooKeeper</h3><p>For the first decade of its existence, every Kafka cluster required a separate ZooKeeper ensemble to manage cluster metadata: which brokers exist, which broker is the controller, which topics and partitions exist, which replicas are in sync, and ACLs. This created four real problems:</p><ol><li><strong>Operational complexity</strong>: two separate systems to deploy, monitor, and upgrade. ZooKeeper expertise is a different skill set than Kafka expertise.</li><li><strong>Partition count ceiling</strong>: every ISR change, topic creation, or leader election was written to ZooKeeper synchronously. At roughly 200,000 partitions, ZooKeeper write latency became a real bottleneck.</li><li><strong>Slow controller failover</strong>: when the controller broker failed, the new controller had to load all cluster metadata from ZooKeeper — a cold start that could take seconds or minutes for large clusters.</li></ol><p><strong>KRaft</strong> (Kafka Raft, introduced via KIP-500) eliminates ZooKeeper entirely. Kafka now stores its own metadata in a special internal topic called __cluster_metadata, replicated via a built-in Raft consensus algorithm. A small subset of brokers form a <strong>controller quorum</strong> — typically three or five — one of which is elected the active controller. All metadata changes are written as records to the metadata log, committed via Raft, and pushed to every broker as incremental updates.</p><p>The key improvement: every broker maintains a local copy of the full metadata log. When the active controller fails, a new one is elected from the quorum and it already has all metadata in memory. Failover goes from seconds or minutes to milliseconds.</p><h3>Putting it all together: a message’s journey</h3><p>Here’s what actually happens when a producer sends a single record and a consumer receives it.</p><p><strong>Producer side:</strong></p><ol><li>Your code calls producer.send(record), specifying a topic and optionally a key.</li><li>The serializer converts the record to bytes (with Schema Registry: a 5-byte header prepended containing a magic byte and schema ID).</li><li>The partitioner hashes the key (or round-robins) to select a partition.</li><li>The record lands in the RecordAccumulator for that partition.</li><li>The sender thread detects the batch is ready (linger elapsed or batch full).</li><li>The batch is compressed, framed as a ProduceRequest, and sent over TCP to the partition leader.</li><li>The leader writes the batch to its segment file. The OS page cache absorbs the write.</li><li>Followers fetch and replicate the batch. When enough ISR members confirm, the leader advances the high watermark.</li><li>With acks=all, the leader sends an ack back to the producer.</li><li>The producer marks the batch complete and invokes any registered callback.</li></ol><p><strong>Consumer side:</strong></p><ol><li>Your consumer loop calls poll(Duration.ofMillis(500)).</li><li>Kafka’s fetch coordinator sends a FetchRequest to the partition leaders for each assigned partition, asking for records after the last committed offset.</li><li>The leader finds the relevant segment file using the partition index and uses sendfile() to transfer bytes from the page cache to the network socket.</li><li>The consumer’s deserializer reads the 5-byte header, looks up the schema ID in its local cache (or fetches from Schema Registry on a miss), and decodes the remaining bytes using Avro (or Protobuf or JSON) schema resolution.</li><li>poll() returns a ConsumerRecords iterable.</li><li>Your code processes each record.</li><li>You call commitSync() to write the new committed offset to __consumer_offsets.</li></ol><p>The entire path from producer send() to consumer poll() returning takes 5–15ms under typical conditions for small messages.</p><h3>Final Thoughts</h3><p>Kafka excels when many services need the same events, when you can’t afford to lose data, when your producer and consumer run at different speeds, when you need a durable audit trail, and when throughput matters more than millisecond latency.</p><p>The architectural choices described here — the commit log, the partition model, the pull-based consumer, ISR-based replication — are not arbitrary. Each one is a specific answer to a specific problem. Knowing the problems helps you know when Kafka is the answer and when it isn’t.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=19d4ec738a19" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Kubernetes Explained: The One Loop That Runs Everything]]></title>
            <link>https://medium.com/@rupeshksinghmit/kubernetes-explained-the-one-loop-that-runs-everything-5087d5790d9e?source=rss-79569b8bdd24------2</link>
            <guid isPermaLink="false">https://medium.com/p/5087d5790d9e</guid>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[cloud-native]]></category>
            <category><![CDATA[containers]]></category>
            <category><![CDATA[kubernetes]]></category>
            <category><![CDATA[devops]]></category>
            <dc:creator><![CDATA[RK Singh]]></dc:creator>
            <pubDate>Sun, 16 Aug 2026 03:51:12 GMT</pubDate>
            <atom:updated>2026-08-16T03:51:12.657Z</atom:updated>
            <content:encoded><![CDATA[<p>Containers solved the packaging problem: a single image runs the same on a laptop, in CI, and in production. But the moment you run more than a handful of containers across more than one machine, multiple questions appear:</p><p><strong>Which host should run which container</strong>? What happens when a host dies? <strong>How does one container find another when their IP addresses change every time they restart</strong>? How do you push a new version without a moment of downtime, and how do you undo it if the new version is broken? They have <em>a common </em>answer, and <strong>Kubernetes</strong> is the one.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*d7WXg3sxM-SBwbsgG8LmkQ.png" /><figcaption><em>One container is a program. A fleet of them is an operations problem.</em></figcaption></figure><p>The main idea behind the approach is simple: you describe the <strong>desired state</strong> of your workloads in YAML (“I want three replicas of this image behind a load balancer”) and Kubernetes runs a set of <strong>controllers</strong> that continuously drive the actual state of the cluster toward that desired state.</p><h3><strong>The reconciliation loop</strong></h3><p>A controller is a small program with a single obsession. It watches for a particular kind of object in the cluster — Deployments, or Nodes, or PersistentVolumeClaims. On every change (and periodically anyway), it asks itself two questions: <em>what should the world look like for this object?</em> and <em>what does it actually look like?</em> If the two answers disagree, it takes one step to close the gap, and then it does the whole thing again.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5jgzDOzw5TtiNIl5ecg8uA.png" /><figcaption><em>Every controller in Kubernetes runs this loop, forever.</em></figcaption></figure><p>That is the entire trick. Kubernetes ships with dozens of these controller loops running in parallel — one to keep the right number of Pods alive, one to attach cloud disks, one to update endpoint lists when Pods come and go, one to garbage-collect finished jobs.</p><p>This is the reconciliation loop.</p><h3>Cluster Architecture</h3><p>A cluster is a collection of machines (physical or virtual) partitioned into two roles. The <strong>control plan</strong>e makes global decisions and stores cluster state. The <strong>worker nodes</strong> run your application containers. All communication flows through a single well-known door: the API server.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/594/1*SW-zoeT9BepLoyPjPwSUfQ.png" /></figure><h4><strong>kube-apiserver:</strong></h4><p>The <strong>API server</strong> is the <strong>receptionist</strong>. Every request — from your kubectl, from a controller, from a kubelet on a worker node — goes through it. It authenticates, authorises, validates, and either writes to etcd or reads from it. It exposes a mechanism called a <em>watch</em>: <strong>any client can open a long-lived connection</strong> and receive a stream of changes to a given resource type. This is how the reconciliation loops stay current without polling.</p><h4><strong>etcd:</strong></h4><p>It is a <strong>distributed, strongly-consistent key-value store</strong> based on the Raft consensus protocol. It holds the entire state of the cluster: every object you have ever created, plus its current status. It is the single source of truth; lose etcd and you lose the cluster’s memory.</p><h4><strong>scheduler</strong>:</h4><p>The <strong>scheduler</strong> is the <strong>matchmaker</strong>. It watches for Pods that have been created but have no assigned node, and for each one it picks a host. It filters out nodes that cannot possibly run the Pod (not enough CPU, wrong labels) and scores the survivors on things like spread and image locality. The winner gets written back to the Pod object as a nodeName.</p><p>Notice: the scheduler does not start anything. It just changes one field. Someone else will notice.</p><h4><strong>kubelet:</strong></h4><p>That someone else is the kubelet on each worker node. It is watching for Pods assigned to <em>its</em> node. When it sees one appear, it pulls the container image, hands the container specification to the <strong>local container runtime</strong>, mounts volumes, wires up networking, and starts running <strong>liveness</strong> and <strong>readiness probes</strong>. Then it <strong><em>reports status back to the API server</em></strong>, which persists it, which every other controller in the cluster can now see.</p><h4><strong>kube-proxy:</strong></h4><p>the layer<strong> </strong>implements the Service abstraction on each node by programming iptables or IPVS rules so that traffic sent to a Service’s virtual IP is transparently <strong>load-balanced</strong>.</p><h4><strong>Pod</strong>:</h4><p>A Pod is a group of one or more containers that <strong>share a network namespace</strong> (same IP, same port space, can talk over localhost) and can share volumes. In practice, most Pods contain a single container.</p><p>Pods are intentionally <strong>ephemeral</strong>. They are given a fresh IP when created and that IP is released when they die. You never rely on a Pod’s identity directly — you address groups of Pods through Services.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*h6-QsqfpQyQ7FolQGD7LQA.png" /></figure><h3><strong>A day in the life of `kubectl apply`</strong></h3><p>Let’s put those actors on the stage. You write a Deployment YAML declaring that you want three replicas of an nginx:1.27 image, save it as web.yaml, and run:</p><pre>$ kubectl apply -f web.yaml</pre><ol><li>Your <strong>kubectl</strong> reads its local kubeconfig, translates the YAML to JSON, and sends a POST to the API server over TLS.</li><li>The <strong>API server</strong> verifies your identity, checks your RBAC permissions and moves forward or reject it outright (say, because the image is from an untrusted registry).</li><li>If it survives, the Deployment is written to <strong>etcd</strong>. Your kubectl gets a 201 Created back. From your perspective, you are done but this is just the begining.</li><li>The <strong>Deployment controller</strong>, which has an open watch, sees the new object. Its reconciliation loop notices that this Deployment has no ReplicaSet yet, so it creates one.</li><li>The <strong>ReplicaSet controller</strong> sees the new ReplicaSet, notices that it should have three Pods but currently has zero, and creates three Pod objects. Each one is written to etcd with no nodeName.</li><li>The <strong>scheduler</strong> sees three unscheduled Pods, does its filter-and-score dance for each, and patches them with node assignments.</li><li>Three different <strong>kubelets</strong>, on three different nodes, notice that a Pod has been assigned to them. The kubelet on that node sees a Pod assigned to it, asks the container runtime to pull the image and start the container, then continuously reports status back to the API server</li></ol><h3><strong>When node/pod dies or some network issue (which is always)</strong></h3><p>Imagine one of those three nodes catches fire. The kubelet stops reporting status. After a grace period, the <strong>node controller</strong> marks it <strong>NotReady</strong>. Not long after, it marks the Pods on that node as lost.</p><p>The <strong>ReplicaSet controller</strong>, staring at its object as it always does, notices something new: it wanted three Pods, and now there are only two. It creates a third. The <strong>scheduler</strong> sees a Pod without a node and places it on a surviving host. A <strong>kubelet</strong> there pulls the image and starts it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Gv6ovQdqKgauufd8839O8A.png" /><figcaption><em>Nobody paged anyone. The count was wrong, and then it wasn’t.</em></figcaption></figure><p>Every step is the same <strong>watch-diff-act cycle</strong> you have already seen. That is why understanding the reconciliation loop is worth the effort.</p><h3><strong>How Pods find each other</strong></h3><p>Now we have healthy Pods running somewhere. But you cannot address them by IP, because their IPs are ephemeral — a Pod that dies and is replaced comes back with a fresh one. You need a stable name and a stable address for the whole group.</p><p>That is a <strong>Service</strong>. A Service is, honestly, a very thin object: it holds a label selector (“anything with app=web”) and a virtual IP. The <strong>Endpoints controller</strong> (yet another reconciliation loop) watches for Pods matching the selector and maintains an up-to-date list of their IPs and ports as an <strong>EndpointSlice</strong> object.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OqK6V1_TAn8kwwKRkW7ePA.png" /><figcaption><em>The Service IP is virtual. No interface holds it; the kernel just knows what to do when it sees it.</em></figcaption></figure><p>On every node, <strong>kube-proxy</strong> watches those <strong>EndpointSlices</strong> and programs the local kernel — via iptables or IPVS rules — so that packets addressed to the Service’s virtual IP get directed to one of the live Pod IPs.</p><h3><strong>How new versions land without downtime</strong></h3><p>Once you can address a group of Pods without caring about individual identities, rolling updates become almost identical. You change the image tag in your Deployment from nginx:1.27 to nginx:1.27.1 and apply.</p><p>The Deployment controller notices that its current ReplicaSet no longer matches the desired template, and creates a new ReplicaSet alongside the old one. Then it slowly scales the new one up and the old one down, respecting two knobs: <strong>maxSurge</strong> (how many extra Pods above the desired count are allowed during the switch) and <strong>maxUnavailable</strong> (how many Pods below the desired count are tolerated).</p><p>A new Pod is not added to the Service’s endpoint list until its readiness probe returns success. If the new version is broken and never becomes ready, the rollout stalls; no traffic ever reaches it, and kubectl rollout undo reverses everything in seconds.</p><h3>Final Thoughts</h3><p>Every advanced Kubernetes topic — operators, service meshes— is a variation on the same core pattern you have now seen end to end: declare desired state to the API server, let controllers reconcile it, let the kubelet realize it on a node.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5087d5790d9e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[PostgreSQL Architecture Explained: From Browser to Disk]]></title>
            <link>https://medium.com/@rupeshksinghmit/what-really-happens-when-your-run-sql-query-in-postgresql-646049e0ec46?source=rss-79569b8bdd24------2</link>
            <guid isPermaLink="false">https://medium.com/p/646049e0ec46</guid>
            <category><![CDATA[database-internals]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[postgresql]]></category>
            <category><![CDATA[sql]]></category>
            <category><![CDATA[backend-engineering]]></category>
            <dc:creator><![CDATA[RK Singh]]></dc:creator>
            <pubDate>Wed, 12 Aug 2026 03:50:00 GMT</pubDate>
            <atom:updated>2026-08-16T03:42:04.478Z</atom:updated>
            <content:encoded><![CDATA[<p>You click a button. A second later, fresh data shows up on the screen. It feels instant and a little bit magic — but there’s a whole assembly line running underneath that click. It’s a handful of processes, a shared chunk of memory, and some very disciplined bookkeeping.</p><p>Let’s walk through it, one layer at a time.</p><h3>First: your browser never touches the database</h3><p>A browser speaks HTTP. PostgreSQL speaks its own binary protocol over a TCP connection, usually on port 5432. Those are two different languages, and your browser doesn’t have a dictionary for the second one — it also doesn’t have your database credentials, and honestly, it shouldn’t.</p><p>What actually happens is a relay. Your browser sends a request to an application server — a Django, Rails, Node, or Go backend you or your team wrote. <em>That</em> server is the real database client. It holds the connection, sends the SQL, and hands back JSON your browser can render.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*u3rBX7uHikSBxWNX1-2x4w.png" /></figure><p>Keep that picture in mind. Everything from here on is what happens <em>after</em> the app server sends its query — inside PostgreSQL itself.</p><h3>PostgreSQL in simple language</h3><p>Once you strip away the intimidating vocabulary — postmaster, WAL writer, checkpointer, autovacuum — PostgreSQL is really just three things working together:</p><ul><li><strong>Processes</strong> — the workers that actually do things.</li><li><strong>Shared memory</strong> — a common storage where workers use to coordinate and cache data.</li><li><strong>Files on disk</strong> — the permanent storage for data.</li></ul><p>Almost every concept below is one of those three, or the relationship between them.</p><h3>Postmaster</h3><p>The postmaster is the very first PostgreSQL process to start, and it has one job at any given moment: <strong>listen at the door.</strong> It opens a socket on port 5432 and waits for a new connection to arrive.</p><p>Here’s the part that surprises people: <strong>the postmaster doesn’t actually run your queries</strong>. When a new connection comes in and passes authentication, the postmaster <strong>forks</strong> — <strong>it spins up a brand-new, dedicated process just for that one session</strong> — and then immediately goes back to listening for the next connection. From that point on, your session talks directly to its own private backend process. The postmaster is out of the loop entirely.</p><p>Every session gets its own isolated process, so if one connection crashes, it doesn’t take the others down with it. This process <strong>parses, plans, and executes</strong> the query.<strong> </strong>The trade-off is that a process is heavier than a thread — spinning one up costs real memory and setup time, which is exactly why busy applications sit a connection pool (like <strong>PgBouncer</strong>) in front of PostgreSQL instead of opening a fresh connection per request.</p><p>The postmaster also launches and <strong>supervises a small crew of background processes</strong> at startup, and it keeps watch over the whole family — if anything dies unexpectedly, it steps in to clean up and protect the data.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*c5l1DZiG6ADcsgvNXlELuw.png" /></figure><p>You can actually watch this happen from inside a running database. pg_stat_activity lists every live backend, one row per session:</p><pre>SELECT pid, usename, state, query<br>FROM pg_stat_activity<br>WHERE state &lt;&gt; &#39;idle&#39;;</pre><p>Every pid in that result is a real operating-system process that the postmaster forked, doing real work on someone&#39;s behalf right now.</p><h3>Why processes need a shared workspace</h3><p>Isolated processes are great for stability, but they create an obvious problem: if 200 backends are all reading and writing the same table, how do they avoid stepping on each other? How does a page one backend just loaded from disk become instantly available to everyone else, instead of each session re-reading the file separately?</p><p>The answer is a single large region of <strong>shared memory</strong>, set up once when the postmaster starts. Every background process can read and write it. It’s the common ground that turns a crowd of separate processes into one coherent database.</p><p>The most important resident of that shared memory is <strong>shared_buffers</strong> — <strong>PostgreSQL’s in-RAM cache of table and index pages</strong>. It’s one of the first settings anyone tunes, because a cache that’s too small means constant, expensive trips back to disk.</p><h3>Everything is an 8 KB page</h3><p>PostgreSQL doesn’t shuffle data around one row at a time. It works in fixed 8 KB chunks called <em>pages</em>. A page is the unit that gets read from disk, the unit that fills a slot in shared buffers, and the unit that eventually gets written back out. One page typically holds many rows.</p><p>The <strong>Buffer Manager</strong> is the component that governs all of this traffic. In the normal, hot-path case, PostgreSQL <em>never</em> touches a table file on disk directly — every read and write passes through a cached page in shared buffers first. Disk is where data rests; RAM is where it actually gets worked on.</p><p>When a backend changes a row like a UPDATE operation, it edits the in-memory copy of the page — and at that instant, memory and disk disagree. That page is now <strong>dirty</strong>, and PostgreSQL deliberately doesn’t rush to fix the disagreement.<strong> Flushing dirty pages is handled later, in batches, by a background process</strong>, which keeps your query fast right now.</p><p><strong>Shared buffers is finite</strong>, of course, so when it fills up, something has to be evicted to make room for a new page. PostgreSQL uses an algorithm called <em>clock-sweep</em> — a simple usage counter and a sweeping pointer — to pick a good candidate for eviction without the overhead of tracking exact access times for every page.</p><h3>The write-ahead log: durability comes first</h3><p>Here’s a real risk: if a dirty page only lives in RAM and the server loses power, that change vanishes. PostgreSQL’s answer is the <strong>Write-Ahead Log (WAL)</strong> — and the name says exactly what it does. Before a change is considered final, a record of it is written to the log first.</p><p><strong>Walk through a single UPDATE</strong>:</p><ol><li>The backend sql query modifies the row in its cached page. The page is dirty.</li><li>A compact record describing the change is appended to the WAL buffer, in shared memory.</li><li>When you COMMIT, PostgreSQL forces that WAL data out to disk — a call that only returns once the operating system confirms the bytes are truly, physically saved. The moment that succeeds, your transaction is officially durable.</li><li>Sometime after that, a background process quietly writes the actual dirty data page out to its table file.</li></ol><p>Notice what’s <em>not</em> required for a commit to succeed: the data page itself doesn’t need to be on disk yet. The WAL record alone is enough, because if the server crashes, PostgreSQL can rebuild the page by replaying the log.</p><figure><img alt="WAL Flow Diagram" src="https://cdn-images-1.medium.com/max/1024/1*-ap72n9CoQqhAlqXxN8xYg.png" /></figure><p>This one mechanism quietly powers two other major features. <strong>Replication</strong> works by streaming that same WAL to a standby server, which replays it to stay in sync. <strong>Point-in-time recovery</strong> works by archiving the WAL continuously, so you can restore a backup and replay changes up to any exact moment — say, one second before someone ran a DELETE they didn&#39;t mean to.</p><h3>The background crew</h3><p>A handful of processes run continuously behind every PostgreSQL database, and you never talk to them directly — but without them, things would slowly grind down.</p><ul><li><strong>Background writer</strong> — writes dirty pages out to disk in a a batch, so backends rarely get stuck waiting on a disk write during eviction.</li><li><strong>Checkpointer</strong> — periodically flushes <em>all</em> dirty pages at once and drops a checkpoint marker in the WAL. This is what keeps crash recovery fast (only WAL written since the last checkpoint needs replaying) and lets old WAL segments be recycled.</li><li><strong>Autovacuum</strong> — PostgreSQL uses <strong>MVCC</strong> — Multi-Version Concurrency Control — so that readers don’t block writers and writers don’t block readers. <strong>PostgreSQL never overwrites a row in place</strong> — an UPDATE writes a new version and marks the old one expired, a DELETE just marks it expired — those old &quot;dead tuples&quot; pile up. Autovacuum reclaims that space. PostgreSQL transaction IDs (<strong>XIDs</strong>) have a finite range which is to determine if the tuple is visible. It freezes old transaction IDs to prevent XID wraparound, and automatically updates table statistics so the query planner can make better execution-plan decisions</li></ul><h3>Conclusion: Putting the whole trip together</h3><p>So, from click to pixels:</p><ol><li>Your browser sends an HTTP request to the app server.</li><li>The app server, acting as the real database client, opens or reuses a connection and sends SQL over TCP.</li><li>The postmaster hands that session its own backend process from the connection pool.</li><li>The backend process parses, plans, and executes the query, <strong>reading and modifying pages in shared buffers</strong>.</li><li>Any change is written to the WAL first, and confirmed durable on COMMIT.</li><li>Results stream back through the app server to your browser.</li><li>Quietly, in the background, dirty pages get flushed, checkpoints happen, and autovacuum tidies up after everyone.</li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=646049e0ec46" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Choosing the Right Database — A Simple Guide: SQL, Document, Wide Column & Key-Value]]></title>
            <link>https://medium.com/@rupeshksinghmit/choosing-the-right-database-sql-document-wide-column-key-value-5a083113a348?source=rss-79569b8bdd24------2</link>
            <guid isPermaLink="false">https://medium.com/p/5a083113a348</guid>
            <category><![CDATA[sql-vs-nosql]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[system-design-concepts]]></category>
            <category><![CDATA[postgresql]]></category>
            <category><![CDATA[database]]></category>
            <dc:creator><![CDATA[RK Singh]]></dc:creator>
            <pubDate>Mon, 06 Jul 2026 03:42:34 GMT</pubDate>
            <atom:updated>2026-08-12T04:17:10.601Z</atom:updated>
            <content:encoded><![CDATA[<p>Picking a database is one of those decisions that’s easy to get wrong quietly. It won’t blow up on day one — it’ll just make everything a little harder for the next three years.</p><p>The most common mistake? Choosing a database because it’s popular, or because it’s what you used on your last project — not because it fits the job. And unlike swapping out a library or a framework, changing databases later is painful. It touches your schema, your application logic, your deployments, and sometimes the business itself.</p><p>So before you reach for the same database out of habit, it’s worth answering a few honest questions first.</p><figure><img alt="Choosing a Database" src="https://cdn-images-1.medium.com/max/1024/1*TV6T0LiNi7NVwMnmswh65Q.png" /></figure><p>Once you’ve answered those, the right <em>category</em> of database usually becomes obvious. Let’s walk through the four most common types you’ll run into.</p><h3>SQL — PostgreSQL</h3><p>Relational databases organize data into tables of rows and columns and enforce a strict schema. They’re exceptional at the one thing the NoSQL world deliberately gave up: <strong>joins</strong>.</p><p>PostgreSQL is fully ACID-compliant and is, frankly, the most feature-complete open-source database ever shipped. Every transaction either commits in full or rolls back in full. Every read sees a consistent snapshot. There’s no ambiguity about what state the data is in, which is exactly what you want when money is involved.</p><figure><img alt="PostgresSQL table" src="https://cdn-images-1.medium.com/max/1024/1*MyJHwAYNAuz66Jo1PNKZ2Q.png" /></figure><h4>Real-World Example: E-Commerce Platform</h4><p>Consider what happens when a customer places an order. A single purchase may involve:</p><ul><li>Creating an order record</li><li>Reserving inventory</li><li>Processing payment</li><li>Updating account balances</li><li>Generating shipment records</li></ul><p>If any step fails, everything must roll back. This is exactly what ACID transactions were designed for. PostgreSQL guarantees that either the entire transaction succeeds or none of it does.</p><h4>More Than Just a Relational Database</h4><p>PostgreSQL is also more than “just” a relational database. Out of the box it supports JSONB, full-text search, and partitioning — and its extensions (<strong>PostGIS for geospatial data, pgvector for AI embeddings, TimescaleDB for time-series, Citus for distributed scale</strong>) stretch it into places people don’t expect.</p><h4>Scaling Characteristics</h4><p>Modern Postgres deployments comfortably handle billions of rows and thousands of writes per second.</p><p>Write scaling does eventually hit a ceiling, though, since every write has to go through the primary node — at extreme scale you’ll need partitioning, sharding, or a distributed setup.</p><h4>Avoid PostgreSQL When</h4><ul><li>Schema changes constantly</li><li>You need millions of writes per second</li><li>Horizontal scaling across dozens of nodes is a primary requirement</li><li>Your workload is primarily append-only event ingestion</li></ul><h3>Document — MongoDB</h3><p>A document database stores data as self-contained <strong>JSON/BSON</strong> documents inside <strong>collections</strong>, rather than rows in normalized tables. Each document is a complete entity — a user, an order, a product — and can carry nested arrays, embedded sub-objects, and fields that differ from one document to the next.</p><figure><img alt="One products collection holding two differently-shaped JSON documents — a painting with medium and originalAvailable fields, and a download with fileFormats and licenseType fields — sharing no common columns" src="https://cdn-images-1.medium.com/max/1024/1*iuPMaZeQXLYIunGEr0pWZQ.png" /></figure><h4>Real-World Example: Product Catalogs and CMS Platforms</h4><p>Think of a marketplace like Etsy or a publishing platform like Medium. Every product listing is fundamentally different: a handmade painting has medium, dimensions, and originalAvailable; a digital download has fileFormats and licenseType. With a document store, each record carries exactly the fields it needs. You never end up with a 200-column table where 190 columns are NULL for any given row in SQL.</p><figure><img alt="MongoDB Collection" src="https://cdn-images-1.medium.com/max/1024/1*UDvpKKCm8e0CvLjWLxd5vw.png" /></figure><h4>Avoid MongoDB When</h4><ul><li>Data is highly relational or ACID compliance</li><li>Complex joins are common</li></ul><h3>Wide Column — Cassandra</h3><p>Wide column stores organize data into rows identified by a <strong>partition key</strong>, where each row can hold a huge number of columns — and, critically, different rows can hold entirely different columns. The partition key decides which node in the cluster owns the row, and that single design choice is the <strong>entire basis for linear horizontal scalability</strong>.</p><p>Handling enormous volumes of distributed writes without a single point of failure.</p><h4>Real-World Example: IoT Telemetry</h4><p>Picture a factory floor with 10,000 sensors each emitting a reading every 100ms: 100,000 writes per second. Cassandra handles that trivially.</p><p>Set device_id as the partition key and timestamp as the clustering key, and a query like <em>&quot;all readings from sensor A9C4 in the last five minutes&quot;</em> becomes a single efficient range scan inside one partition.</p><figure><img alt="Cassandra database" src="https://cdn-images-1.medium.com/max/1024/1*dpnDAKlYa4iZB554uz5TrA.png" /></figure><h4>The Biggest Mindset Shift</h4><p>Relational databases model data first and queries second.</p><p>Cassandra does the opposite. You model tables around your queries. <strong>Design your schema around your queries, not around your data.</strong></p><p>Before creating a schema, you should already know:</p><ul><li>Every major query pattern</li><li>Access frequency</li><li>Partition strategy</li></ul><p>If you discover new query requirements later, you may need entirely new tables. This is the price paid for extreme scalability.</p><h4>Avoid Cassandra When</h4><ul><li>Ad-hoc queries are required</li><li>Transactional consistency is important</li><li>Data relationships are complex</li><li>Your workload does not justify its operational cost</li></ul><h3>Key-Value — DynamoDB</h3><p>DynamoDB is AWS’s fully managed, serverless NoSQL database. At its core it’s a key-value store, but the <strong>single-table design</strong> pattern — packing multiple entity types into one table using a compound key. Instead of creating separate tables for users, orders, and products, multiple entity types are often stored in the same table.</p><figure><img alt="DynamoDB Table" src="https://cdn-images-1.medium.com/max/1024/1*0o3hIVRjo742wvRYOf9QSQ.png" /></figure><p>Its design philosophy is simple:</p><p><strong>Sacrifice query flexibility to guarantee predictable performance.</strong></p><p>Whether a table contains one thousand rows or ten trillion rows, DynamoDB aims to deliver consistent <strong>single-digit millisecond</strong> latency.</p><p>The design revolves around access patterns rather than entities.</p><p>When designed correctly:</p><ul><li>Reads are extremely fast</li><li>Costs remain predictable</li><li>Scaling becomes effortless</li></ul><h4>Real-World Example: User Sessions and Gaming Platforms</h4><p>Imagine a mobile game with 50 million users, constant profile lookups, inventory updates and leaderboard reads.</p><p>Traffic fluctuates dramatically. A viral event could increase load tenfold overnight.</p><p>DynamoDB automatically scales without requiring operators to rebalance clusters or provision additional nodes. This is one of its biggest advantages.</p><h4>Avoid DynamoDB When</h4><ul><li>Access patterns are unknown</li><li>Cross-entity relationships are important or ACID Compliance</li><li>Vendor lock-in is a concern</li></ul><h3>Final Thoughts</h3><p>None of these databases is “the best” in any absolute sense — they’re each optimized for a different kind of problem. In practice, the strongest systems don’t pick just one. A typical setup might use <strong>PostgreSQL</strong> for core transactional data, <strong>MongoDB</strong> for a flexible product catalog, <strong>Cassandra</strong> for high-volume event streams, and <strong>DynamoDB</strong> for session management and real-time lookups — each doing the part it’s actually good at.</p><figure><img alt="Database comparisons" src="https://cdn-images-1.medium.com/max/1024/1*pi-ImHkiMVAqUpD7QfwWew.png" /></figure><p>The real skill isn’t memorizing which database is “best.” It’s being honest about your data shape, your access patterns, and your consistency needs <em>before</em> you commit — because that’s the decision that’s hard to walk back.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5a083113a348" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>