<?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 Jainal Gosaliya on Medium]]></title>
        <description><![CDATA[Stories by Jainal Gosaliya on Medium]]></description>
        <link>https://medium.com/@jainal?source=rss-f011d9c738f4------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*dzUcm37HBCkNsvI635-I3Q.png</url>
            <title>Stories by Jainal Gosaliya on Medium</title>
            <link>https://medium.com/@jainal?source=rss-f011d9c738f4------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 05 Dec 2026 07:34:35 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@jainal/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[System Design Estimates That Actually Change Your Design]]></title>
            <link>https://medium.com/@jainal/system-design-estimates-that-actually-change-your-design-df802a2d6c64?source=rss-f011d9c738f4------2</link>
            <guid isPermaLink="false">https://medium.com/p/df802a2d6c64</guid>
            <category><![CDATA[scalability]]></category>
            <dc:creator><![CDATA[Jainal Gosaliya]]></dc:creator>
            <pubDate>Mon, 14 Sep 2026 03:55:50 GMT</pubDate>
            <atom:updated>2026-09-14T03:55:50.076Z</atom:updated>
            <content:encoded><![CDATA[<p>A few numbers can tell you which box to remove, which promise to question, and why your queue is quietly becoming a waiting room.</p><figure><img alt="" src="https://cdn-images-1.medium.com/proxy/0*or-Cov7yyddBSIHj" /></figure><p><em>Photo by </em><a href="https://unsplash.com/@hermanm?utm_source=medium&amp;utm_medium=referral"><em>Herman Mahal</em></a><em> on </em><a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral"><em>Unsplash</em></a></p><p>So, you are designing a file upload service. You draw a client, an API server, a database, and some object storage. Then comes the calculator cameo.</p><p>Ten million users. Twenty requests each. Divide by seconds in a day. Write a very specific number next to the API server.</p><p><strong>Okay. What changed?</strong></p><p>The useful part of capacity planning is connecting the arithmetic to an actual decision. A useful estimate should help explain what the design can support, where it needs more evidence, or which assumption is about to ruin everybody’s afternoon.</p><p>Here are three examples using hypothetical numbers. <strong>All storage and network units below are decimal:</strong> one GB is one billion bytes.</p><h3>1. Your API server has become a very expensive pipe</h3><p>Imagine 10,000 uploads per second, averaging 5 MB each. The proposed path is client → application server → object storage.</p><pre>10,000 uploads/s × 5 MB/upload<br>= 50,000 MB/s<br>= 50 GB/s<br>= 400 Gbit/s</pre><p>That last conversion matters. Network links usually advertise bits per second. Our files were measured in bytes. Forgetting the factor of eight is a surprisingly efficient way to design a bottleneck.</p><p>The application tier <strong>receives roughly 400 Gbit/s</strong> of payload and <strong>forwards roughly 400 Gbit/s</strong>. Count the two directions separately against the relevant network limits. Protocol overhead, retries, and bursts come on top.</p><p>Could a sufficiently large fleet proxy this? Yes. The number does not prove that proxying is impossible. It gives us a cost and capacity question: why should these application servers carry every byte?</p><p>If the API primarily checks permission and creates metadata, I would consider direct uploads. The client asks the API for permission, receives a scoped upload URL, then sends the file to object storage. <a href="https://docs.aws.amazon.com/AmazonS3/latest/userguide/using-presigned-url.html">S3 presigned URLs</a> support this, with access bounded by the signing permissions and expiration.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Sa_CElb6R6ZiMSK-FvQaXw.png" /></figure><p><em>Two data paths, then the chosen direct-upload design. Architecture drawn in draw.io.</em></p><p>Our API still owns authorization and upload state. It should verify completion before treating the file as available. A URL being issued does not mean any bytes arrived.</p><p>Inline inspection might justify a different path, or an asynchronous quarantine workflow. The estimate helped expose that tradeoff. It did not personally ban proxies from the building.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/200/0*luk3JAZBx_H7ETZQ.gif" /></figure><p><em>Me realizing 50 GB/s also has to travel through an actual network. | </em><a href="https://giphy.com/gifs/1wnZt7VY9yPDZRZ9M6"><em>cjergl / GIPHY</em></a></p><h3>2. It fits on disk. Great. Does it run?</h3><p>Now estimate metadata for that file service. Suppose we keep 100 million file records and an average of ten chunk references per file.</p><pre>100 million file records × 500 bytes = 50 GB<br>1 billion chunk references × 200 bytes = 200 GB<br>Raw metadata estimate = 250 GB</pre><p>This makes a database without application-level sharding worth considering. But <strong>250 GB is a raw estimate</strong>, not the full storage bill.</p><p>Indexes, row overhead, transaction logs, retained versions, and operating headroom need space too. Replicas and backups add more copies. We have also said nothing about the working set that needs fast access.</p><p>Most importantly, fitting the dataset does not prove that one primary can handle the workload. Ten thousand uploads per second could mean substantially more than ten thousand row writes once chunk references and indexes enter the chat.</p><p>Before deciding, check:</p><ul><li><strong>Workload:</strong> write throughput, query patterns, and hot rows.</li><li><strong>Resources:</strong> CPU, I/O, working set, and growth.</li><li><strong>Operations:</strong> recovery time, replication, and failover.</li></ul><p>Then measure a representative workload. Availability may require replication and failover even if the data fits comfortably on one machine.</p><p>So my conclusion is: start by evaluating a transactional database with one primary, and identify its limits. Storage size alone has not justified sharding, or proved we will never need it. Also, transactions are not exclusive to single-machine databases.</p><h3>3. The queue is durable. Your deadline isn’t.</h3><p>Suppose an event processor has these rates. Assume an empty starting queue, uniform work per event, FIFO processing, and a consumer fleet that sustains the stated completion rate.</p><pre>Normal arrivals: 5,000 events/s<br>Burst arrivals: 50,000 events/s for 60 seconds<br>Consumer capacity: 10,000 events/s<br>Backlog added: (50,000 - 10,000) × 60<br>             = 2,400,000 events</pre><p>When the burst ends, events keep arriving. The net drain rate is only 10,000 minus 5,000, or 5,000 events per second.</p><pre>Time until the queue is empty again<br>= 2,400,000 / 5,000<br>= 480 seconds, or 8 minutes</pre><blockquote><em>Eight minutes is recovery time, not the waiting time of every event.</em></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/proxy/1*XR3_VxOtfvGavIQUWCezCQ.png" /></figure><p><em>From my system design notes, redrawn in Excalidraw. Queue recovery time and an individual event’s wait use different denominators.</em></p><p>For an event arriving just as the burst ends, roughly 2.4 million events are ahead of it. Under our FIFO assumptions, later arrivals join behind it. Its approximate queueing delay is 2.4 million divided by 10,000, or <strong>240 seconds</strong>. Add its own processing time.</p><p>If the requirement is completion within 30 seconds, this simplified design already fails for some events. We do not need to confuse recovery time with latency to show the problem.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/480/0*SlOfqsIPjWoIDtma.gif" /><figcaption>The event is durable. Its user is still waiting. | <a href="https://giphy.com/gifs/bombaysoftwares-waiting-mr-bean-still-um2kBnfo55iW4ZH1Fa">Bombay Softwares / GIPHY</a></figcaption></figure><p>Adding consumers can help if partitions, downstream capacity, and available parallelism allow it. Autoscaling also takes time. A fleet that becomes large enough after the burst has already built the queue has a different outcome from one that was ready beforehand.</p><p>We could reserve capacity, prioritize urgent work, reduce per-event cost, or apply admission control. Each changes either the arrival curve or the service curve. This operational concern is also explored in the Amazon Builders’ Library article on <a href="https://aws.amazon.com/builders-library/avoiding-insurmountable-queue-backlogs/">avoiding queue backlogs</a>.</p><p>Burst shape matters too. The same daily event count spread evenly across a day creates a different queue from a synchronized one-minute spike. A daily average cannot tell us which world we live in.</p><h3>A Little law, with a big asterisk</h3><p>There is another useful check: Little’s law. For a stable system with well-defined long-run averages, average items in the system equal throughput multiplied by average time in the system. Keep the boundary consistent: a queue-only measurement uses queue waiting time. A whole-service measurement includes processing. <a href="https://web.mit.edu/urban_or_book/www/book/chapter4/4.4.html">MIT’s queueing text derives the relationship</a>.</p><pre>1,000 requests/s × 0.2 seconds average time<br>= 200 requests in the system on average</pre><p>This is useful for checking average concurrency. <strong>It does not say p99 latency is 200 ms.</strong> It does not prove 200 worker slots are sufficient. Requests can overlap, work can be uneven, and the tail can be much worse than the mean.</p><h3>Averages are helpful. They are also excellent at keeping awkward details out of the family photo.</h3><h3>Turning the numbers into a design decision</h3><p>When discussing estimates, explain what they inform. Before calculating, state the assumptions and the decision being examined. After calculating, say what follows and what still needs measurement.</p><blockquote><em>At this upload volume, proxying carries 400 Gbit/s in each direction. I’ll separate authorization from file transfer, unless inline processing requires that path.</em></blockquote><p>Or: “The metadata size makes one primary plausible, but we still need to validate write throughput and recovery requirements.”</p><p>Then change an uncertain assumption. What if files average 20 MB? What if the burst lasts five minutes? Does the architecture still make sense?</p><p>The point is to leave the conversation with a better design and a clearer list of unknowns. The calculator has done its job when a number changes the next sentence.</p><h3>Ready to level up 🚀 your backend engineering game?</h3><p>If this walkthrough helped, subscribe to <strong>Scale Bites</strong> for more system design breakdowns, practical backend ideas, and the awkward failure cases that make the diagrams interesting.</p><p>You can <a href="https://scalebites.substack.com/">subscribe on Substack</a> or <a href="https://www.linkedin.com/newsletters/scale-bites-7169831353377619968/">follow the LinkedIn newsletter</a>, whichever fits your reading routine.</p><p>Next time you estimate capacity, make every number earn an architectural decision. See you in the next breakdown!</p><p>#SystemDesign #BackendEngineering #CapacityPlanning #Scalability #SoftwareArchitecture</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=df802a2d6c64" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[B-Trees vs LSM Trees: Your Workload Gets the Final Vote]]></title>
            <link>https://medium.com/@jainal/b-trees-vs-lsm-trees-your-workload-gets-the-final-vote-fe2bbdbe5b73?source=rss-f011d9c738f4------2</link>
            <guid isPermaLink="false">https://medium.com/p/fe2bbdbe5b73</guid>
            <category><![CDATA[system-design-concepts]]></category>
            <category><![CDATA[database]]></category>
            <dc:creator><![CDATA[Jainal Gosaliya]]></dc:creator>
            <pubDate>Sun, 13 Sep 2026 03:52:33 GMT</pubDate>
            <atom:updated>2026-09-13T03:52:33.588Z</atom:updated>
            <content:encoded><![CDATA[<p>Following one update from memory to disk, then asking who pays for the cleanup.</p><figure><img alt="" src="https://cdn-images-1.medium.com/proxy/0*oDYhoR1h29bNoL9f" /></figure><p><em>Photo by </em><a href="https://unsplash.com/@jay_5?utm_source=medium&amp;utm_medium=referral"><em>Jayanth Muppaneni</em></a><em> on </em><a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral"><em>Unsplash</em></a></p><p>It is tempting to reduce storage engines to a slogan: B-trees for reads, LSM trees for writes.</p><p>Cool. Database chosen. We can all go home.</p><p>Except our imaginary application now needs fast writes, range queries, predictable latency, and a storage bill that does not require its own fundraising round.</p><p>So let us follow one workload instead. Imagine a service storing device readings. It receives frequent updates and serves two requests: “What is device 42’s latest reading?” and “Show device 42’s readings for the last hour.” This is an illustrative design, not a benchmark.</p><h3>First, choose what the key means</h3><p>For history, we could use a key ordered by device ID and timestamp:</p><pre>device:0042:2026-09-10T12:00:00Z = 28.1<br>device:0042:2026-09-10T12:00:01Z = 28.3<br>device:0042:2026-09-10T12:00:02Z = 28.2</pre><p>Use an encoding whose byte order matches the intended order. Fixed-width IDs and normalized timestamps keep this example simple. Add a sequence if multiple readings can share a timestamp.</p><p>Now one device’s readings sit together logically. A latest-value view might instead overwrite device:0042:latest. Those are different workloads: mostly new keys versus repeated updates to a smaller working set.</p><p>Already, “write-heavy” is hiding useful information.</p><h3>The B-tree approach: find the page</h3><p>A B-tree uses pages containing many keys and references, so one step can eliminate a large portion of the search space. It is not restricted to two separator keys. In the B+ tree arrangement commonly used for database indexes, internal pages guide the search and leaf pages contain index entries. The exact representation depends on the engine. <a href="https://www.postgresql.org/docs/current/btree.html">PostgreSQL’s B-tree documentation</a> is a useful concrete reference.</p><p>For an insertion, find the appropriate leaf and make room. A full page can split, requiring a parent update and occasionally further splits. PostgreSQL supports concurrent B-tree operations; there is no universal rule that only one leaf in the entire tree may change at once. Its <a href="https://github.com/postgres/postgres/blob/master/src/backend/access/nbtree/README">implementation notes</a> explain the coordination involved.</p><p>Also, page size is an engine choice, not a law of nature. SQLite permits several page sizes. Memorizing “B-tree equals 4 KB” turns an implementation detail into folklore. <a href="https://www.sqlite.org/fileformat.html">SQLite file format</a>.</p><p>Updating a page in memory does not necessarily mean immediately writing that page to disk. PostgreSQL’s WAL protocol makes log records durable before the corresponding data pages; recovery can replay logged changes. Whether a commit waits for durability also depends on configuration. <a href="https://www.postgresql.org/docs/current/wal-intro.html">PostgreSQL WAL</a>.</p><h3>The LSM approach: collect now, organize later</h3><p>A typical LSM write path combines a memory buffer, a write-ahead log, immutable sorted files, and compaction. The memory buffer is the <strong>memtable</strong>. <strong>It is one component, not the entire LSM tree.</strong></p><p>It does not even have to be a balanced binary tree. RocksDB’s default memtable uses a skip list and supports other representations. <a href="https://github.com/facebook/rocksdb/wiki/Memtable">RocksDB memtables</a>.</p><p>With the WAL enabled, a write is recorded in the log and added to memory. When a memtable is flushed, its sorted contents become an SST file. New writes go into another memtable. We do not keep inserting arbitrary incoming keys into an already completed SST file. <a href="https://github.com/facebook/rocksdb/wiki/RocksDB-Overview">RocksDB architecture</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/proxy/1*6u9LekIn8MYBRBHtCgOgnA.png" /></figure><p><em>From my system design notes, redrawn in Excalidraw. Both paths support ordered reads; the work happens in different places.</em></p><p>The distinction between “written to a log” and “durable through a machine failure” matters. RocksDB exposes synchronization options, and disabling the WAL changes recovery guarantees. Compare engines with equivalent durability requirements, or the faster contestant may simply be doing less work. <a href="https://github.com/facebook/rocksdb/wiki/Write-Ahead-Log-(WAL)">RocksDB WAL behavior</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/500/0*ClrX3W9I0H1OwM-h.gif" /><figcaption>Just one more write. Surely the cleanup can wait five minutes.</figcaption></figure><p><em>| </em><a href="https://giphy.com/gifs/l10yGFKGnvSgkwrdAE"><em>Jim_Carrey / GIPHY</em></a></p><h3>The cleanup has entered the chat</h3><p>Suppose our latest-reading key changes from 28.1 to 28.3. Older and newer versions can exist in different sorted files. Reads must resolve the visible version. Compaction merges files and can remove obsolete versions when they are no longer needed.</p><p>A delete usually introduces a tombstone. Removing the tombstone too early could expose an older value again, so cleanup has to respect what still exists elsewhere and what snapshots need. <strong>Deleting a key logically does not promise immediate disk reclamation.</strong> <a href="https://github.com/facebook/rocksdb/wiki/RocksDB-Overview">RocksDB snapshots and compaction</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/870/1*fdqM3T9kR-AI2EiEuaNGpg.png" /></figure><p><em>Follow the versions: 42 changes, 43 is deleted, and 44 stays. This simplified compaction retains the deletion marker; safely discarding it requires proving older values and snapshots no longer need it.</em></p><p>And compaction consumes resources. If background work cannot keep up, RocksDB can slow or stop incoming writes. A burst that fits in memory and a sustained workload are very different tests. <a href="https://github.com/facebook/rocksdb/wiki/Write-Stalls">RocksDB write stalls</a>.</p><p>“We will clean it up later” is a storage strategy. It is also how my browser ends up with 47 tabs.</p><h3>Reads did not leave the building</h3><p><strong>Both approaches support range queries.</strong> PostgreSQL B-tree indexes support equality and ordered comparisons. RocksDB supports ordered iterators and range scans. An LSM engine may need to merge multiple sorted streams while respecting versions and deletions. Support and cost are different questions. <a href="https://www.postgresql.org/docs/current/indexes-types.html">PostgreSQL index types</a>, <a href="https://github.com/facebook/rocksdb/wiki/RocksDB-Overview">RocksDB reads and iterators</a>.</p><p>For point lookups, Bloom filters can avoid probing files that definitely lack a key. A positive answer means “maybe,” so an actual lookup is still necessary. Filters also consume memory and CPU; they are useful, not free. <a href="https://github.com/facebook/rocksdb/wiki/RocksDB-Bloom-Filter">RocksDB Bloom filters</a>.</p><h3>Who pays, and how much?</h3><p><strong>Write amplification</strong> asks how many bytes the storage engine writes relative to the application’s logical writes. Compaction can rewrite data repeatedly. Page-based engines also incur overhead from page writes and logging.</p><p><strong>Read amplification</strong> asks how much extra work a lookup requires. <strong>Space amplification</strong> asks how much storage is occupied beyond the live logical data. Define the measurement boundary before comparing numbers, especially whether WAL and temporary files count. <a href="https://github.com/facebook/rocksdb/wiki/RocksDB-Tuning-Guide">RocksDB tuning guide</a>.</p><p>Compaction policy moves these costs around. RocksDB’s universal compaction generally trades lower write amplification for higher read and space amplification than leveled compaction. That is a policy tradeoff inside one engine, before we even compare it with a B-tree. <a href="https://github.com/facebook/rocksdb/wiki/Compaction">RocksDB compaction styles</a>.</p><h3>Back to our devices</h3><p>I would test the history workload with realistic record sizes, retention, and per-device scans. Then I would separately test the latest-value workload, including its hot keys. An LSM engine is a reasonable candidate for sustained ingestion, but that is a hypothesis to measure.</p><p>Here is what I would keep on the benchmark checklist:</p><ul><li><strong>Compare the same guarantees:</strong> keep memory budgets, durability, hardware, and dataset sizes comparable.</li><li><strong>Include the cleanup:</strong> run long enough to include compaction and cleanup.</li><li><strong>Measure the uncomfortable numbers:</strong> p95 and p99 latency alongside throughput, disk growth, and recovery time.</li><li><strong>Change the cache conditions:</strong> repeat with warm and cold caches.</li></ul><p>An average can look lovely while the unlucky request is growing a beard.</p><p>A B-tree-based database may already meet the application’s needs and provide the transactions, indexes, and operational tools the team wants. RocksDB is a storage library, so choosing it also means considering the surrounding database or application.</p><p>Before choosing an engine, I want to explain where the work happens, what can fall behind, and which experiment would change my choice.</p><p>The workload gets the final vote. The tree just has to live with it.</p><h3>Ready to level up 🚀 your backend engineering game?</h3><p>If this walkthrough helped, subscribe to <strong>Scale Bites</strong> for more system design breakdowns, practical backend ideas, and the awkward failure cases that make the diagrams interesting.</p><p>You can <a href="https://scalebites.substack.com/">subscribe on Substack</a> or <a href="https://www.linkedin.com/newsletters/scale-bites-7169831353377619968/">follow the LinkedIn newsletter</a>, whichever fits your reading routine.</p><p>Next time you compare storage engines, bring your workload to the discussion. See you in the next breakdown!</p><p>#SystemDesign #BackendEngineering #Databases #StorageEngines #Performance</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fe2bbdbe5b73" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Designing Ticketmaster: One Seat, Two Buyers, Zero Excuses]]></title>
            <link>https://medium.com/@jainal/designing-ticketmaster-one-seat-two-buyers-zero-excuses-8ed28a4d3c96?source=rss-f011d9c738f4------2</link>
            <guid isPermaLink="false">https://medium.com/p/8ed28a4d3c96</guid>
            <category><![CDATA[distributed-systems]]></category>
            <dc:creator><![CDATA[Jainal Gosaliya]]></dc:creator>
            <pubDate>Sun, 13 Sep 2026 03:51:31 GMT</pubDate>
            <atom:updated>2026-09-13T03:51:31.294Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/proxy/0*gDZVrN5l7w5w4rT9" /></figure><p><em>Photo by </em><a href="https://unsplash.com/@anthonydelanoix?utm_source=medium&amp;utm_medium=referral"><em>Anthony DELANOIX</em></a><em> on </em><a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral"><em>Unsplash</em></a></p><p>Two people click the same seat. Both reach checkout. Both have excellent internet and terrible luck.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/500/0*T2zzGs7Rv1z6oX97.gif" /><figcaption>Both buyers, approximately half a second after tickets go live. | <a href="https://giphy.com/gifs/futurama-fry-shut-up-and-take-my-money-xTiTntNs0aqQAZtyFy">Dark Zone Store / GIPHY</a></figcaption></figure><p>Only one should receive the ticket.</p><p>I keep coming back to this problem because the architecture looks friendly until money enters the chat. Search, cache, queue, payment service. Nice boxes. Now tell me which box stops two people from owning seat A12.</p><p>Let’s design a Ticketmaster-like service around that question. This is an illustrative design, not a description of Ticketmaster’s internals.</p><h3>First, decide what we are promising</h3><p>Users can discover events, browse seats, hold a seat briefly, and buy it. I would separate assigned seats from general admission because their inventory rules differ. For this walkthrough, every event has individually numbered seats.</p><blockquote><em>One event-seat can have at most one confirmed booking.</em></blockquote><p>Search can lag. A seat map can briefly show a seat that someone just reserved. <strong>Checkout must verify the authoritative state and reject the second buyer.</strong> A fast, beautifully cached lie is still a lie when you charge for it.</p><p>So the browsing path uses a search index, cached availability, and a CDN for static venue maps. The booking path goes to the database responsible for that event’s inventory.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tI4LbuzvrhQrxnHHslAm4g.png" /></figure><p><em>The browsing path can serve cached answers. Only the authoritative booking path grants a hold. Architecture drawn in draw.io.</em></p><h3>A hold is a row, not a ten-minute transaction</h3><p>Use a seats table keyed by (event_id, seat_id), with status, hold_id, held_by, held_until, and booking_id. A fresh, unguessable hold_id identifies this particular attempt. The authenticated session supplies the buyer identity; a user ID sent by the browser is not proof of ownership.</p><p>Here is the core operation. The placeholders are bound parameters, and the database owns the clock:</p><pre>UPDATE seats<br>SET status = &#39;HELD&#39;,<br>    hold_id = :new_hold_id,<br>    held_by = :authenticated_user,<br>    held_until = clock_timestamp() + interval &#39;10 minutes&#39;<br>WHERE event_id = :event_id AND seat_id = :seat_id<br>  AND (status = &#39;AVAILABLE&#39;<br>       OR (status = &#39;HELD&#39;<br>           AND held_until &lt;= clock_timestamp()))<br>RETURNING hold_id, held_until;</pre><p><strong>One returned row means this attempt acquired the hold. Zero means it did not.</strong> Return success only after commit. A lost response requires checking the recorded attempt, not assuming the hold failed.</p><p>Under PostgreSQL Read Committed, competing updates wait for the row updater and recheck their condition against its committed version. The losing buyer sees the new, unexpired hold and cannot replace it. This argument is for this simple, single-row predicate, not every transaction at that isolation level. <a href="https://www.postgresql.org/docs/current/transaction-iso.html">PostgreSQL explains the behavior here.</a></p><p><strong>The UPDATE does take a database row lock.</strong> We commit promptly and release that lock; the durable HELD state remains while the person pays. Keeping a transaction open while someone finds their credit card would turn checkout into a connection-pool endurance sport. <a href="https://www.postgresql.org/docs/current/explicit-locking.html">PostgreSQL’s locking documentation</a> covers lock lifetimes.</p><p>This assumes one authoritative write path and a failover policy that preserves acknowledged bookings. An application-level check cannot repair two independent primaries both accepting sales. Redis can reduce unnecessary traffic, but cached availability never grants ownership.</p><p>Expiry makes an old hold eligible for replacement. A cleanup job can tidy old rows, but acquiring a seat does not depend on that job running on time.</p><figure><img alt="" src="https://cdn-images-1.medium.com/proxy/1*zbKxTUPkt7aoUoKklNaTPg.png" /></figure><p><em>From my system design notes, redrawn in Excalidraw. A payment callback must still prove it owns a valid hold.</em></p><h3>Give the client something it can recover</h3><p>Keep the API small enough that the client can recover from a lost response:</p><ul><li><strong>POST /holds</strong>: send an Idempotency-Key header, event_id, and seat_id. Authentication supplies the buyer.</li><li><strong>GET /holds/{hold_id}</strong>: return the current hold state, including expiration.</li><li><strong>GET /bookings/{booking_id}</strong>: recover the result of a completed purchase.</li></ul><p>The server stores the request key’s input fingerprint so reusing it for a different seat is rejected instead of returning a surprising old result. Ownership checks apply to the reads too.</p><ul><li><strong>Success:</strong> return hold_id, held_until, and status: HELD.</li><li><strong>Conflict:</strong> return 409 with a stable reason such as SEAT_UNAVAILABLE.</li></ul><p>The UI can offer another seat without pretending the user broke something.</p><p>If the response disappears, the client retries the same request with the same key. It does not generate another key on every network retry.</p><p><strong>The countdown is a convenience.</strong> Its display can drift because the browser clock differs from the server’s. The database’s decision wins, and the UI should handle expiration gracefully even when its timer still says one second.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/200/0*RKqsvG6HIlMOlSrW.gif" /></figure><p><em>The booking service when an expired hold asks for Bob’s seat. | </em><a href="https://giphy.com/gifs/lkibHaGO1xmJXapEdq"><em>The Office / GIPHY</em></a></p><h3>The payment succeeded. Now what?</h3><p>Well, payment and seat inventory live in different systems. We cannot wrap a card charge inside our PostgreSQL transaction and call the entire thing atomic.</p><p>For this version, accept the possibility of a successful payment that must be refunded. Create a payment attempt bound to the hold, buyer, amount, and currency. Record it durably before contacting the provider, with a stable provider idempotency key. A timeout triggers lookup or retry with that same key. <a href="https://docs.stripe.com/api/idempotent_requests">Stripe documents this retry mechanism.</a></p><p>When verified payment success arrives, run a short local transaction. Lock the seat first, then check ownership and time in a fresh statement:</p><pre>BEGIN;<br>SELECT seat_id FROM seats<br>WHERE event_id = :event_id AND seat_id = :seat_id<br>FOR UPDATE;<br>UPDATE seats<br>SET status = &#39;SOLD&#39;, booking_id = :booking_id<br>WHERE event_id = :event_id AND seat_id = :seat_id<br>  AND status = &#39;HELD&#39;<br>  AND hold_id = :hold_id<br>  AND held_by = :authenticated_user<br>  AND held_until &gt; clock_timestamp()<br>RETURNING seat_id;<br>-- Application checks the returned row before continuing.<br>-- Persist booking and fulfillment intent in this transaction.<br>COMMIT;</pre><p>This is the critical section, not a complete endpoint. Verify the provider payment belongs to this stored attempt and matches its expected amount and currency. The callback handler derives the buyer from that record. It does not accept identity from callback query parameters.</p><p><strong>Only create a new booking when the transition succeeds.</strong> Keep a unique constraint on the booking’s event-seat and on the payment reference. Store the fulfillment event in an outbox with the booking so ticket delivery can retry after commit.</p><p>Define the deadline precisely: this design checks eligibility under the row lock. It does not promise the commit becomes visible at an exact wall-clock millisecond.</p><h3>Expired holds have terrible timing</h3><p>Imagine Alice pays, but her callback arrives late. Her hold has expired and Bob has acquired the seat.</p><p>Alice’s old hold_id fails the confirmation check. <strong>Her money does not entitle the callback to overwrite Bob’s hold.</strong> Record Alice’s payment as requiring compensation and issue a refund through a retriable workflow. If only authorized, cancel the authorization where supported.</p><p>Put actual times on this race. Alice gets h-17 at 10:00, expiring at 10:10. Her payment succeeds at 10:09:59, but the notification is delayed. At 10:10:01 Bob’s conditional update replaces the expired hold with h-18. At 10:10:02 Alice’s notification arrives.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/855/1*CFZP5hYUCVPL1wf24SbCqg.png" /></figure><p><em>Alice paid before expiry, but her callback reached the booking service after Bob acquired the seat.</em></p><p>Our server verifies Alice’s payment, locks the seat, and finds h-18. It records the compensation work without selling the seat to Alice. Bob’s hold remains intact. If Alice’s notification repeats, the stored payment outcome points to the same compensation workflow, not a second refund request with a new identity. Refund retries reuse a stable provider idempotency key as well.</p><p>This is why “the payment happened before expiry” is insufficient. Our chosen rule requires confirmation while the hold is still valid. Customer messaging should explain that policy before payment, and operational monitoring should track late-payment refunds so the team can adjust the checkout window.</p><p>Even if nobody has taken the seat yet, this strict policy rejects an expired hold. Allowing late confirmation is another product policy, but it needs an explicit atomic reacquisition rule.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/480/0*_jtWh6jLT5BBdnWp.gif" /><figcaption>The payment callback finally arrives. The hold has already moved on. | <a href="https://giphy.com/gifs/titanicmovie-NO63FW6F9RwjKWssAb">Titanic / GIPHY</a></figcaption></figure><p>Authorization followed by capture can reduce some refund cases. It adds its own failure states: capture can fail or time out after inventory changes. Choose a policy and reconcile uncertain payments until each attempt has a terminal outcome. Distributed transactions do not disappear because the diagram ran out of space.</p><h3>Refresh is not a new purchase</h3><p>The hold request key and its result belong in the same transaction as the hold. Storing them afterward creates another crash window. A duplicate request returns the original outcome; it must not silently extend the timer.</p><p>Payment notifications also repeat and can arrive out of order. Verify webhook signatures, deduplicate processing atomically with local state changes, and look up an existing booking before interpreting a zero-row update as failure. Otherwise, the retry of a successful confirmation could accidentally trigger a refund. <a href="https://docs.stripe.com/webhooks">Stripe’s webhook guidance</a> covers duplicate delivery and ordering.</p><h3>The waiting room protects the part that matters</h3><p>A popular event is a concentration problem. <strong>More booking servers do not make one contested seat support more winners.</strong></p><p>Place admission control before checkout. Issue verifiable admission tokens, enforce them on booking APIs, limit purchase attempts, and tune entry rate against measured database and payment capacity. A waiting room needs a fairness policy and reconnect behavior, not merely a Kafka topic named queue.</p><p>As a concrete reference, Cloudflare Waiting Room exposes active-user and incoming-user thresholds. Those are useful controls to reason about, even if we build our own implementation. <a href="https://developers.cloudflare.com/waiting-room/about/">Cloudflare documents the settings here.</a></p><p>Partition inventory by event when scale requires it, recognizing that one blockbuster remains a hot partition. Publish batched availability updates for browsing; the hold response remains authoritative. For multiple seats, acquire them in a consistent order within one short transaction and roll back unless the entire requested set succeeds.</p><p>My design checkpoint is simple: trace one seat through a competing click, an expired hold, a delayed payment, and a repeated callback. If the design survives those, the boxes have earned their place.</p><p>Seat A12 can have two admirers. It still gets only one booking.</p><h3>Ready to level up 🚀 your backend engineering game?</h3><p>If this walkthrough helped, subscribe to <strong>Scale Bites</strong> for more system design breakdowns, practical backend ideas, and the awkward failure cases that make the diagrams interesting.</p><p>You can <a href="https://scalebites.substack.com/">subscribe on Substack</a> or <a href="https://www.linkedin.com/newsletters/scale-bites-7169831353377619968/">follow the LinkedIn newsletter</a>, whichever fits your reading routine.</p><p>Next time you sketch checkout, make two buyers compete for the same seat. See you in the next breakdown!</p><p>#SystemDesign #BackendEngineering #DatabaseDesign #Concurrency #SoftwareArchitecture</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8ed28a4d3c96" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Your Database Saved the Order. Your Event Never Made It.]]></title>
            <link>https://medium.com/@jainal/your-database-saved-the-order-your-event-never-made-it-739ef32b135f?source=rss-f011d9c738f4------2</link>
            <guid isPermaLink="false">https://medium.com/p/739ef32b135f</guid>
            <category><![CDATA[system-design-concepts]]></category>
            <category><![CDATA[distributed-systems]]></category>
            <dc:creator><![CDATA[Jainal Gosaliya]]></dc:creator>
            <pubDate>Thu, 10 Sep 2026 13:54:04 GMT</pubDate>
            <atom:updated>2026-09-10T21:04:01.195Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/proxy/0*vagoZU58ajerJNNz" /></figure><p><em>Photo by </em><a href="https://unsplash.com/@live_for_photo?utm_source=medium&amp;utm_medium=referral"><em>Teng Yuhong</em></a><em> on </em><a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral"><em>Unsplash</em></a></p><p>Outbox, CDC, sagas, and 2PC make more sense when we follow one order through the failure cases.</p><p>So, imagine we are building an ordering system. The order service saves an order in PostgreSQL, then publishes an OrderPlaced event to Kafka. Inventory picks it up and reserves the items.</p><p>Two steps. Seems reasonable. Our order is placed, everyone gets notified, and we can move on to the next box in the system design diagram.</p><p>Well, there is a tiny gap between those two steps. And our process has chosen that exact gap to crash.</p><h3>The order exists. The event does not.</h3><p>The database commit succeeds. Before publishing the event, the service dies. Inventory never hears about the order.</p><p>What if we publish first? Now the event can escape before the database commit fails. Inventory starts working on an order that was never saved.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/860/1*QOZC8bRnv-Mvz96KxORK0g.png" /></figure><p><em>Changing the order of two independent writes moves the failure window. It does not close it. Drawn in Excalidraw.</em></p><p>Wrapping only the database operation in a transaction cannot make the independent broker operation atomic with it. This is the dual-write problem described in the <a href="https://microservices.io/patterns/data/transactional-outbox.html">transactional outbox pattern</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/proxy/0*idKq-orEKczHLpYd.gif" /></figure><p><em>The order API looking at its successful database commit. Everything is fine, obviously. | </em><a href="https://giphy.com/gifs/sA8HUiA09PWtq"><em>GIF on GIPHY</em></a></p><h3>Put the event on the same receipt</h3><p>Instead of asking the request handler to complete two independent writes, <strong>save the order and an outbox record in one local transaction.</strong> The outbox record represents the event we intend to publish.</p><p>Here is a simplified example. Assume both tables already exist and event_id is unique:</p><pre>BEGIN;<br>INSERT INTO orders (id, status)<br>VALUES (123, &#39;PENDING&#39;);<br>INSERT INTO outbox<br>  (event_id, aggregate_id, event_type)<br>VALUES<br>  (&#39;e-456&#39;, 123, &#39;OrderPlaced&#39;);<br>COMMIT;</pre><p>A real event also needs its payload. We might include the items and quantities that inventory needs, plus an event schema version. The example keeps those out so the transaction boundary is easy to see.</p><p>After commit, a relay publishes the stored event. If the process crashes first, the committed outbox row remains available for recovery. The database transaction protects the order and the intent to publish together. It does not make Kafka receive the event instantly.</p><p>That delay is part of the design. In this example, I would return the order ID with a PENDING status. The client can check its progress instead of treating “order saved” as “inventory reserved.”</p><h3>But wait, did we just publish it twice?</h3><p>The relay publishes e-456 successfully, then crashes before recording progress. On restart, it cannot assume delivery happened. So it retries. The same event can now appear twice.</p><blockquote><em>Retries kept our event from getting lost, but they brought a friend.</em></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/480/0*36Wu_bwaLlr8IWl6.gif" /><figcaption>Same event ID. Different delivery. Very familiar face. | <a href="https://giphy.com/gifs/erichamlet-zRwA2JgARLVYgWtfgY">bigdog / GIPHY</a></figcaption></figure><p>The consumer can record processed event IDs. For inventory, record the ID and the reservation change in the same local transaction. Enforce uniqueness on something like (consumer_name, event_id). A duplicate must not apply the reservation again. This is the <a href="https://microservices.io/patterns/communication-style/idempotent-consumer.html">idempotent consumer pattern</a>.</p><p>That “same transaction” part matters. Recording the ID first and crashing before the reservation could make a retry skip unfinished work. Reserving first and recording the ID later leaves room to reserve twice.</p><p>A Kafka offset tracks a position in a partition. It does not, by itself, atomically commit an inventory database update. If a consumer commits that update and crashes before committing its offset, it may see the event again. If the effect is an external API call, the local transaction cannot cover that either; the receiving API needs an appropriate retry or idempotency contract.</p><h3>So where does CDC come in?</h3><p>CDC means change data capture. For PostgreSQL, Debezium uses logical decoding to capture database changes and stream change events. It also has snapshot and recovery behavior. It is more than a script opening a WAL file and reading some lines. The <a href="https://debezium.io/documentation/reference/stable/connectors/postgresql.html">connector documentation</a> explains that machinery.</p><p><strong>An outbox defines what application event we store.</strong> CDC can be the mechanism that relays it.</p><p>You can poll the outbox table. Or you can capture its inserts using CDC. Debezium even provides an <a href="https://debezium.io/documentation/reference/stable/transformations/outbox-event-router.html">Outbox Event Router</a>, with fields for an event ID, aggregate information, type, and payload.</p><p>Outbox and CDC can work together. Putting “versus” between them without explaining the use case makes the choice more confusing than it needs to be.</p><figure><img alt="" src="https://cdn-images-1.medium.com/proxy/1*91gVCJHIjuxPW3NXOUXlyg.png" /></figure><p><em>From my system design notes, redrawn in Excalidraw. Outbox stores the intent; polling or CDC delivers it.</em></p><h3>A changed row and a business event are different contracts</h3><p>Suppose an order moves from PENDING to CONFIRMED. Raw CDC can tell a consumer that a row changed. A deliberately written OrderConfirmed event can carry the business meaning and the data that consumer needs.</p><p>For a search index that mirrors selected order fields, row changes might be sufficient. For a workflow that needs a stable business event, I would lean toward an explicit event contract. That is a design choice, not a rule that every CDC pipeline needs an outbox.</p><p>Debezium’s router can use the aggregate ID as the Kafka message key. This helps route related events to the same partition. It does not remove the need to reason about ordering through your entire relay and consumer pipeline.</p><p>Neither approach is maintenance-free. A poller needs a safe claim/retry strategy and cleanup. With PostgreSQL CDC, watch connector lag and replication-slot WAL retention. If the connector falls behind, retained WAL can become a storage problem. The connector docs cover those operational details.</p><h3>Okay, then why do we need sagas?</h3><p>Because getting an event out is only one part of completing an order.</p><p>Imagine this workflow: create a pending order, reserve inventory, then authorize payment. If payment is declined after inventory was reserved, we need a business action that releases that reservation.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/860/1*Y4BY3fVd2PAxY3VZTlc1sg.png" /></figure><p><em>A declined payment starts new work: release inventory, retry if needed, then finish cancellation. Drawn in Excalidraw.</em></p><p>A saga coordinates local transactions and their compensating actions. An orchestrator can direct the steps, or services can react to events through choreography. The <a href="https://microservices.io/patterns/data/saga.html">saga pattern</a> describes both.</p><p>A compensation is another operation with its own failure handling. It is not a database rollback that erases everything that happened. Other services may already have observed the intermediate state, and a compensation may need retries.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/480/0*_pcdZ4qa4siK3OM6.gif" /><figcaption>Payment declined. Now everybody has to help move the order back out. | <a href="https://giphy.com/gifs/Friends-season-5-episode-113-the-one-with-cop-L2HCO7avkR5H9MvS9Y">Friends / GIPHY</a></figcaption></figure><p>In our example, the order could remain CANCEL_PENDING while release is retried, then become CANCELLED. Those states make the unfinished work visible. A saga step can use an outbox to reliably record its outgoing event. Again, these patterns can cooperate.</p><h3>And 2PC?</h3><p>Two-phase commit coordinates an atomic outcome across participants that support the protocol. Participants prepare, then resolve the transaction according to the coordinator’s decision.</p><p>PostgreSQL supports prepared transactions, but expects an external transaction manager to coordinate them. Prepared transactions retain locks, so unresolved ones can block other work. Read its <a href="https://www.postgresql.org/docs/current/sql-prepare-transaction.html">PREPARE TRANSACTION documentation</a> before treating this as a free upgrade to a normal transaction.</p><p>A participant cannot safely reinterpret a durable commit decision as an abort just because an acknowledgement was lost. Recovery has to resolve the agreed transaction outcome. Also, an arbitrary payment or email API cannot join merely because we would like it to.</p><h3>How I would explain the design</h3><p>For this ordering system, I would start with a pending order and an outbox record in one transaction. Then choose polling or CDC for delivery, make the inventory consumer handle duplicates, and describe the payment failure path as a saga.</p><ol><li>What happens after each commit if this process dies?</li><li>Can the next component retry safely?</li><li>How do we find orders that have been pending too long?</li></ol><p>That gives the boxes in the diagram something useful to do. Otherwise we have PostgreSQL, Kafka, Debezium, and a very well-distributed misunderstanding 😄</p><h3>Ready to level up 🚀 your backend engineering game?</h3><p>If this walkthrough helped, subscribe to <strong>Scale Bites</strong> for more system design breakdowns, practical backend ideas, and the awkward failure cases that make the diagrams interesting.</p><p>You can <a href="https://scalebites.substack.com/">subscribe on Substack</a> or <a href="https://www.linkedin.com/newsletters/scale-bites-7169831353377619968/">follow the LinkedIn newsletter</a>, whichever fits your reading routine.</p><p>Next time two systems must agree, follow the failure between their commits. See you in the next breakdown!</p><p>#SystemDesign #BackendEngineering #DistributedSystems #EventDrivenArchitecture #Databases</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=739ef32b135f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Your Distributed Lock Expired. Your Worker Didn’t.]]></title>
            <link>https://medium.com/@jainal/your-distributed-lock-expired-your-worker-didnt-c67a967032fb?source=rss-f011d9c738f4------2</link>
            <guid isPermaLink="false">https://medium.com/p/c67a967032fb</guid>
            <category><![CDATA[system-design-concepts]]></category>
            <category><![CDATA[distributed-systems]]></category>
            <dc:creator><![CDATA[Jainal Gosaliya]]></dc:creator>
            <pubDate>Thu, 10 Sep 2026 13:38:25 GMT</pubDate>
            <atom:updated>2026-09-10T21:02:41.944Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/proxy/0*j3Hzi9RvEoN7Zt5C" /></figure><p><em>Photo by </em><a href="https://unsplash.com/@calina?utm_source=medium&amp;utm_medium=referral"><em>Georg Bommeli</em></a><em> on </em><a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral"><em>Unsplash</em></a></p><p>A small system design rabbit hole: TTLs, sleepy workers, and why the database needs to check the ID.</p><p>So, distributed locks look simple until a worker pauses at exactly the wrong moment. Let’s walk through what happens next.</p><p>One topic worth slowing down for is distributed locks. The happy path looks quite reasonable. Get a lock, do the work, release it. Done!</p><p>Then we introduce a worker that takes an inconveniently long nap.</p><h3>First, what are we trying to protect?</h3><p>Imagine two workers updating the same shared document. We want to avoid an older update overwriting a newer one. We put a lock in front of that work.</p><p>But if a worker crashes while holding it, everyone else could wait forever. So we give the lock an expiry: a lease.</p><h3>A TTL enters the chat</h3><p>A simple Redis acquisition can look like this:</p><pre>SET document:123:lock unique_attempt_id NX PX 10000</pre><p>NX means set it only if the key does not exist. PX 10000 gives it a ten-second expiry. The value should be unique to this acquisition attempt.</p><p>When releasing it, atomically check that the stored value is still yours before deleting it. A plain DEL could remove a newer worker’s lock. That unique value protects release; it is not an ordered fencing token. See the <a href="https://redis.io/docs/latest/develop/clients/patterns/distributed-locks/">Redis locking documentation</a>.</p><p>Okay, crash problem handled by expiry. Now imagine the worker did not crash.</p><h3>Bro woke up and chose stale writes</h3><p>Worker A acquires the lease and pauses. Ten seconds pass. Worker B gets the next lease and writes its update. A resumes and sends its old write.</p><p><strong>A’s lease expired. Its program did not disappear.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/proxy/0*wEvhvGB2uDaL41FU.gif" /></figure><p><em>Worker A: wait, someone else works here now? | </em><a href="https://giphy.com/gifs/confused-john-travolta-l4KigdWQN5nzIrwA0"><em>GIPHY CAM / GIPHY</em></a></p><p>Checking the lease immediately before writing still leaves a gap: a pause can happen after that check. A request can also arrive late because of a network delay. Martin Kleppmann explains this failure in <a href="https://martin.kleppmann.com/2016/02/08/how-to-do-distributed-locking.html">How to do distributed locking</a>.</p><h3>So, check the ID at the door</h3><p>Each new owner gets an increasing fencing token. That ordering must survive failures; a counter that can reset or roll back is not enough. The worker passes it with its write. The resource remembers the highest token it has accepted and rejects older ones.</p><figure><img alt="" src="https://cdn-images-1.medium.com/proxy/1*6Y92npYMpN_OPcG4YngfdA.png" /></figure><p><em>From my system design notes, redrawn in Excalidraw for this walkthrough.</em></p><p>The lock service hands out the number. Storage enforces it. Both parts matter. <a href="https://docs.hazelcast.com/hazelcast/5.7/data-structures/fencedlock">Hazelcast’s FencedLock documentation</a> describes this cooperation with an external resource.</p><p>A fence still needs someone guarding it</p><p>Here is the detail worth keeping in mind: <strong>the token check and the protected update must be atomic.</strong> Otherwise, another write could slip between them.</p><p>Also, storage does not magically learn about lease expiry. If 41 arrives before storage has accepted 42, this check alone may still accept 41. The guarantee is that writes cannot go backwards to an older owner after a newer owner has been accepted.</p><p>Fencing also does not deduplicate retries from the same owner. If your operation needs that, handle it separately. And a service that ignores the token will not suddenly become protected because you added a number to the request.</p><h3>Okay, show me the write</h3><p>Let us make the storage side concrete. Suppose PostgreSQL owns a documents table with id as its primary key, a body column, and last_fence as a non-null bigint initialized to zero. A trusted coordinator issues positive, increasing tokens for this document.</p><p>For this deliberately small example, each lease performs one replacement of the document. The worker submits the new body and its token as bound parameters:</p><pre>UPDATE documents<br>SET body = $1, last_fence = $2<br>WHERE id = $3<br>  AND last_fence &lt; $2<br>RETURNING id, last_fence;</pre><p>With token 42 already stored, a request carrying 41 updates zero rows. The comparison and the body change happen in one database statement. There is no separate “check token, then hope nothing changes” window.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/860/1*GItlun-qCyWOxARyBzCcKw.png" /></figure><p><em>One atomic statement changes both the document and its fence. Token 41 cannot undo token 42. Drawn in Excalidraw.</em></p><p>Under PostgreSQL Read Committed, a competing updater waits when needed and rechecks the WHERE condition against the updated row. That behavior is described in the <a href="https://www.postgresql.org/docs/current/transaction-iso.html">transaction isolation documentation</a>. The <a href="https://www.postgresql.org/docs/current/sql-update.html">UPDATE documentation</a> explains RETURNING and affected rows.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/480/0*EzBHYV_pl5lzZYgQ.gif" /><figcaption>Storage after accepting token 42. Token 41 can take it up with Gandalf. | <a href="https://giphy.com/gifs/HBOMax-lord-of-the-rings-hbo-max-hbomax-WpD30tFjzosDn7amXq">HBO Max / GIPHY</a></figcaption></figure><p>The application still has work to do. Zero returned rows means the write was not accepted; it can mean an old token, a repeated token, or a missing document. Do not turn all three into “success.” Also, every writer must go through the guarded path. An admin script that updates body without checking the fence has found the side entrance.</p><h3>One token, one write? That was a choice</h3><p>I used a strict less-than check, so a token can make only one successful replacement. If the response disappears after commit, retrying the same token will not apply the update again. It also will not automatically recover the original response.</p><p>For a reliable retry contract, give the operation a stable request ID and store its outcome atomically with the document update. A retry can retrieve that outcome. This is especially useful when the operation does more than replace a value.</p><p>Some systems allow several writes within one ownership period and accept equal tokens. That needs additional ordering or version checks if those writes can arrive out of order. Fencing separates owners; it does not tell us which of one owner’s requests is newest.</p><h3>Do we actually need the lock?</h3><p>For a document already stored in PostgreSQL, I would first consider optimistic concurrency. Read version 7, then update only if the version is still 7, incrementing it on success. A conflict means reread, recompute, or reject. That can protect this database update without introducing a separate lease service.</p><p>A lease becomes more interesting when workers coordinate expensive work before the write. It can reduce duplicate computation, while the guarded write protects the result. The tradeoff is another dependency, renewal and recovery behavior, and work we may have to discard after losing ownership.</p><ul><li><strong>Longer TTL:</strong> more time for ordinary work, but slower crash recovery.</li><li><strong>Shorter TTL:</strong> faster recovery, but more chance of losing ownership during a pause.</li></ul><p>Neither setting can promise that a delayed process has stopped.</p><p>And if the protected effect is sending an email or calling an API that ignores tokens, this SQL example does not protect that effect. The receiver needs a suitable idempotency or conditional-operation contract. We cannot just attach token=42 and call it a day. Sadly, numbers are not security guards 😄</p><p>So before choosing a lock, ask what actually needs protecting. Is duplicate work merely wasteful, or can overlapping workers corrupt the result? That distinction changes how much correctness machinery you need.</p><blockquote><em>When the old worker comes back, which component says no?</em></blockquote><p>If the answer is “hopefully the worker remembers,” we still have some work to do 😄</p><h3>Ready to level up 🚀 your backend engineering game?</h3><p>If this walkthrough helped, subscribe to <strong>Scale Bites</strong> for more system design breakdowns, practical backend ideas, and the awkward failure cases that make the diagrams interesting.</p><p>You can <a href="https://scalebites.substack.com/">subscribe on Substack</a> or <a href="https://www.linkedin.com/newsletters/scale-bites-7169831353377619968/">follow the LinkedIn newsletter</a>, whichever fits your reading routine.</p><p>Next time you see a distributed lock, ask who rejects the stale worker. See you in the next breakdown!</p><p>#SystemDesign #BackendEngineering #DistributedSystems #Concurrency #Databases</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c67a967032fb" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[I Replaced Kafka, Redis, and RabbitMQ With One Tool. Here’s What I Learned.]]></title>
            <link>https://medium.com/@jainal/i-replaced-kafka-redis-and-rabbitmq-with-one-tool-heres-what-i-learned-b9f0b5ca94ed?source=rss-f011d9c738f4------2</link>
            <guid isPermaLink="false">https://medium.com/p/b9f0b5ca94ed</guid>
            <category><![CDATA[kafka]]></category>
            <category><![CDATA[backend-development]]></category>
            <category><![CDATA[distributed-systems]]></category>
            <category><![CDATA[nat]]></category>
            <category><![CDATA[nats-streaming]]></category>
            <dc:creator><![CDATA[Jainal Gosaliya]]></dc:creator>
            <pubDate>Mon, 06 Apr 2026 07:01:40 GMT</pubDate>
            <atom:updated>2026-04-10T07:14:43.968Z</atom:updated>
            <content:encoded><![CDATA[<h4><em>The one tool your backend stack has been missing</em></h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*V4M00uld6Ui163Td" /><figcaption>Photo by <a href="https://unsplash.com/@unstable_affliction?utm_source=medium&amp;utm_medium=referral">Ivan Bandura</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h4><strong>What This Post Is</strong></h4><blockquote>The guide I wish existed when I first encountered <a href="https://nats.io/">NATS</a>.If you’ve worked with Kafka you’ll feel at home — and then you’ll start noticing what you’ve been missing. If you’ve stitched together Kafka, Redis, and RabbitMQ — NATS does all three in a single binary.</blockquote><p><strong>A Note on This Post</strong></p><blockquote>Before we dive deep into this post, I want to make something clear. Yes, parts of this blog were written with AI assistance — the em dashes are a dead giveaway.</blockquote><blockquote><strong>But before you close the tab</strong>: this isn’t cheap AI slop dumped into a text box. Every concept here came from weeks of hands-on research — reading through the official NATS documentation, grinding through Synadia’s interactive NATS guide at <a href="https://nats.synadia.com/">nats.synadia.com</a>, watching hours of Synadia’s YouTube deep dives, and drawing from real production experience building and migrating queue processing systems at scale.</blockquote><blockquote>The AI didn’t do the learning. It helped me articulate what I already understood.</blockquote><blockquote>Think of it less as “AI wrote this” and more as “a backend engineer used AI as a rubber duck that could also type.” The insights, the Kafka comparisons, the architecture decisions — those came from actually working with these systems in production.</blockquote><blockquote>So yes, there are em dashes! Yes, Claude <a href="https://www.anthropic.com/claude/opus"><strong>Opus 4.6</strong></a> helped structure and write this. And honestly? I’d rather be upfront about it than pretend otherwise.</blockquote><p>Now — onto NATS.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*94cLECz4E3oGLdvW" /><figcaption>Stack of books and an open notebook beside a coffee cup — a deep dive into NATS messaging:- Photo by <a href="https://unsplash.com/@freestocks?utm_source=medium&amp;utm_medium=referral">freestocks</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3>Core</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/714/1*xy9z-HH12uPHv7Bs6wFgEg.png" /><figcaption>Screenshot from Synadia&#39;s Interactive NATS Guide at nats.synadia.com</figcaption></figure><p>Core NATS is the foundation layer — Basically the pub/sub model. Everything that follows — subjects, pub/sub, request/reply, queue groups, JetStream, KV stores — is built on top of Core. Any publisher can reach any subscriber through named subjects.</p><p><strong>Core NATS is fire and forget — no persistence, no disk, in-memory only.</strong></p><ul><li>Message exists just long enough to forward to connected subscribers</li><li>If no subscriber is listening, message is gone</li><li>Designed for use cases where <strong>stale data is worse than no data</strong> (real-time telemetry, live metrics, sensor readings)</li></ul><p><strong>Slow Consumer behavior:</strong></p><ul><li>If a consumer’s buffer fills up, NATS <strong>disconnects it</strong> rather than stalling everyone else — it disconnects it (explained below)</li><li>Messages queued for that consumer are lost</li><li>Consumer must reconnect and re-subscribe itself</li><li>This is a <strong>circuit breaker / self-protection mechanism</strong> — not a recovery mechanism like Kafka rebalancing</li><li>Kafka rebalancing = redistribute work so nothing is lost. NATS disconnect = protect the broker, consumer is on its own.</li></ul><h4><strong>Core NATS — Slow Consumer Behavior</strong></h4><p>Core NATS allocates a <strong>per-connection outbound buffer in server RAM</strong> for each subscriber.</p><p>Chronology:</p><ol><li>Subscriber connects → server allocates outbound buffer for it</li><li>Publisher sends → server writes into that buffer</li><li>Subscriber reads fast → buffer drains → fine</li><li>Subscriber reads slow → buffer fills up faster than it drains</li><li>Buffer hits limit (64MB default) → <strong>server disconnects that subscriber</strong></li><li>Everything in that buffer is gone — permanently</li><li>Publisher and other subscribers never knew anything happened</li></ol><p><strong>Why it disconnects instead of waiting</strong> — Core NATS has no disk log. The only options are stall everyone or cut the slow subscriber. It cuts.</p><p><strong>Most common cause in Python</strong> — accidentally blocking the asyncio event loop inside your handler. <a href="http://nats.py/">nats.py</a> can’t drain the TCP socket while the loop is blocked, server buffer fills up, disconnect.</p><p><strong>JetStream fixes this</strong> — message is already on disk before delivery. Slow consumer just builds lag like Kafka. No disconnect, no loss.</p><h4>Wildcards</h4><p>NATS subjects are dot-separated tokens:</p><pre>payments.created<br>payments.failed<br>orders.payment.processed<br>orders.payment.failed</pre><p>Two wildcard characters:</p><p><strong>* — matches exactly one token</strong></p><pre>payments.*     → matches payments.created, payments.failed<br>                 does NOT match payments.card.created (two tokens)<br><br>orders.*.processed → matches orders.payment.processed<br>                       matches orders.refund.processed<br>                       does NOT match orders.payment.card.processed</pre><p><strong>&gt; — matches everything after, one or more tokens</strong></p><pre>orders.&gt;  → matches orders.payment.processed<br>                matches orders.payment.failed<br>                matches orders.shipping.tracking.updated<br>                matches anything starting with orders.</pre><p><strong>Key rules:</strong></p><ul><li>&gt; can only appear at the end — orders.&gt; valid, orders.&gt;.created.invalid</li><li>*can appear anywhere in the middle</li><li>Publishers cannot use wildcards — only subscribers can</li><li>JetStream stream subjects can use wildcards to capture multiple subjects into one stream</li></ul><h4>Subjects</h4><p>This thing is important to understand, as it is the fundamental differentiating factor when working with NATS.</p><ul><li>Like Kafka has partitions, NATS does NOT have partitions</li><li>The mental model is: subscribers are like attachment nodes that can attach to subjects with patterns</li><li>Unlike fixed number of consumers and partitions in Kafka, you can attach any number of subscribers</li></ul><p><strong>Messages are addressed by subjects</strong> — meaning instead of “send to partition 3”, you “publish to payments.created” and anyone subscribed to that subject gets it. The subject is the address, not a queue slot.</p><p><strong>Many-to-many relationship</strong> — any publisher can reach any number of subscribers.</p><h4>Subject Naming Conventions</h4><p><strong>Core rule — general to specific, left to right</strong></p><pre>domain.entity.action          ✓<br>domain.entity.identifier.measurement  ✓<br>action.entity.domain          ✗ — wildcards become useless</pre><p>Wildcards only work left to right. Putting specific things first kills your filtering ability.</p><p><strong>Identifier placement — critical</strong></p><pre># Bad — identifier too early<br>orders.{order_id}.status<br>orders.{order_id}.alert<br><br># Good - identifier late, action last<br>orders.payment.{order_id}.reading<br>orders.payment.{order_id}.alert</pre><p>With the good pattern:</p><ul><li>orders.payment.*.status — all payment statuses across all orders</li><li>orders.payment.{order_id}.&gt; — everything for one order</li><li><em>orders.</em>*.{order_id}.&gt; — all event types for one order</li></ul><p>With the bad pattern — orders.*.status matches order IDs, not types</p><p><strong>Rule — put identifiers as late as possible, actions last.</strong></p><p><strong>Implications on streams<br></strong>Your naming determines stream boundaries:</p><pre>Stream bound to: orders.&gt;<br>    → captures everything in one stream<br>    → consumers filter by subject<br><br>Stream bound to: orders.payment.&gt;<br>Stream bound to: orders.shipping.&gt;<br>    → separate streams per measurement type<br>    → more operational overhead</pre><p>Too broad = one stream catches everything including things it shouldn’t. Too narrow = too many streams, hard to manage. Design subject hierarchy before creating streams.</p><p><strong>Implications on consumer filtering</strong></p><pre>Consumer filter: orders.*.{order_id}.status<br>    → all event types for one specific order<br><br>Consumer filter: orders.payment.*.status<br>    → all payment statuses across all orders<br><br>Consumer filter: orders.&gt;<br>    → everything - good for audit/monitoring consumer</pre><p>Your naming determines what filtering granularity is possible. Bad naming = can’t filter the way you need without creating separate streams.</p><p><strong>Avoid</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*0s_p8u5tP24d_ONGbYD-7A.png" /></figure><p><strong>Practical rules</strong></p><ul><li>Lowercase always</li><li>Dots as separators only</li><li>3–4 tokens is the sweet spot — deep enough for wildcards, shallow enough to reason about</li><li>Domain first, identifiers in the middle, action last</li><li>Design subject names for the consumer filters you’ll need, not just what the publisher wants to send</li><li>Never redesign subject naming after streams are in production — painful to migrate</li></ul><h4>TCP Foundation</h4><p>NATS protocol is human-readable text over TCP (you can literally telnet into it).</p><p>NATS keeps TCP’s reliability but fixes its weaknesses at scale:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/880/1*Xms3vXYx9jdV8-dEIzoA1w.png" /></figure><h4>Request &amp; Reply</h4><p>NATS doing RPC without the gRPC ceremony — no protobuf schemas, no generated stubs, no service mesh.</p><p>How it works:</p><ol><li>Requester creates a unique temporary inbox subject — _INBOX.abc123</li><li>Publishes to the service subject (e.g. payments.process) with the inbox as reply-to address</li><li>Responder receives it, sees the reply-to, publishes response back to _INBOX.abc123</li><li>Only the original requester receives it — they’re the only one subscribed to that inbox</li></ol><p><strong>Key insight — requester is both publisher and subscriber simultaneously:</strong></p><ul><li>Publisher → sends to payments.process</li><li>Subscriber → listens on _INBOX.abc123</li></ul><p>Responder flips too — subscriber to receive, publisher to respond. The line between publisher and subscriber disappears completely.</p><p><strong>Scatter-gather</strong> — send one request, collect responses from multiple responders. Useful for finding the fastest instance, aggregating from shards, or fan-out queries. gRPC needs a load balancer for this. NATS gets it for free.</p><p><strong>Timeout behavior</strong> — no response means clean timeout. Unlike HTTP hanging connections, failed downstream services don’t cascade into thread exhaustion on the caller side.</p><p><strong>The deeper insight</strong> — request/reply isn’t a special protocol. It’s just two pub/sub operations choreographed with an inbox trick. Same with queue groups, JetStream, KV store — everything in NATS is just subject-based pub/sub composing into higher-level patterns. One primitive, everything else built on top.</p><p><strong>Clarification — is this pattern unique to NATS?<br></strong>No. Kafka, RabbitMQ, Redis pub/sub can all do request/reply. The pattern isn’t new.</p><p>What makes NATS practical for it — subjects are pure routing addresses, zero cost, no disk, no partition assignment. A temporary inbox like _INBOX.abc123 spins up and disappears for free. In Kafka, creating topics is heavy — partitions, replication, disk — so request/reply is technically possible but an anti-pattern nobody actually does.</p><p>Redis pub/sub is the closest comparison — also in-memory, ephemeral, lightweight. Conceptually the same for this pattern. NATS wins over Redis when you need the full picture — fire and forget, durable streams, request/reply, queue groups — all from one system, one binary. Redis makes you stitch pub/sub + Streams + Cluster together separately.</p><h4>No Responders</h4><p>NATS knows its subscription table. If nobody is subscribed to a subject, the server tells you <strong>immediately</strong> with a “no responders” status — no waiting, no timeout, no hanging connection. Unlike HTTP where a dead service hangs your request for 30 seconds and blocks a thread.</p><p><strong>How it changes in JetStream<br></strong>“No responders” largely disappears for JetStream publishing. The stream itself catches the message and writes to disk regardless of whether any consumer is connected right now. Nobody home doesn’t matter — the stream is always there.</p><p>Failure modes shift to:</p><ul><li>Subject not bound to any stream → error</li><li>Stream full (hit limits) → error based on discard policy</li></ul><p><strong>Where “no responders” still applies<br></strong>Request/reply pattern — needs a live subscriber actively listening right now to respond to your inbox. If nobody is subscribed, “no responders” fires instantly. This is correct behavior because request/reply by definition requires someone home to answer.</p><p>“No responders” is a protocol-level feature, not an application pattern. The server sends it back. The distinction is just — JetStream publish looks for a stream to catch the message, request/reply looks for a live subscriber. Different targets, different behavior.</p><h4>publish() vs request()</h4><p>publish() — fire and forget. Send a message, don&#39;t expect a response. Nobody listening = silent drop, no error, publisher never knows.</p><p>request() — send and wait for a response. Automatically creates an inbox subject under the hood, waits for someone to reply. Nobody listening = instant &quot;no responders&quot; error. This is the request/reply pattern.</p><p>Same mechanism under the hood. Different intent. request() is just publish() with an inbox attached and a wait for reply on top.</p><blockquote><strong><em>The No Responder model only applies to the request() mechanism</em></strong></blockquote><h4>Queue Groups</h4><p>Subscribers join a named queue group. NATS distributes messages across all subscribers in that group — exactly one subscriber per message. No coordinator, no leader election, no partition rebalancing.</p><p><strong>vs Kafka Consumer Group</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4eypJa6e4frNaHhMaKSV_g.png" /></figure><p><strong>Message distribution</strong> — random. NATS picks one subscriber from the group per message. No strict round robin, no sticky routing.</p><p><strong>Fan-out — queue groups and regular subscribers coexisting<br></strong>Both can listen on the same subject simultaneously:</p><ul><li>Queue group → exactly one worker gets it</li><li>Regular subscribers → every one of them gets it</li></ul><p>Same message, one copy distributed among workers, one copy broadcast to all regular subscribers. Useful for workers processing while monitoring/analytics observe simultaneously.</p><p><strong>Two queue groups = message duplicated<br></strong>Each queue group gets its own copy. Within each group exactly one worker gets it. Use this when two completely separate pipelines need to consume the same messages independently.</p><p><strong>Slow consumer in a queue group<br></strong>That worker gets disconnected. NATS immediately routes its share to remaining workers — no pause, no rebalance delay. In Core NATS — messages in that worker’s buffer are lost. In JetStream — redelivered automatically.</p><p><strong>Core NATS vs JetStream queue groups<br></strong>Core NATS queue group — fire and forget. Worker dies mid-processing = message lost, no redelivery.</p><p>JetStream durable consumer — same load balancing behavior but message stays in stream until acked. Worker dies = redelivered. This is the right choice for production workloads.</p><h3>JetStream</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/704/1*Q4iZBTiWxHRVTAMVYI8ipg.png" /><figcaption>Screenshot from Synadia’s Interactive NATS Guide at <a href="http://nats.synadia.com/">nats.synadia.com</a></figcaption></figure><p>JetStream is NATS’s persistence layer — adds a durable log on top of Core NATS. Solves the message loss problem. This is the Kafka replacement layer.</p><h4>Retention Policies — this is important</h4><p>Controls when messages are removed from the stream.</p><p><strong>Limits-based</strong> — keep messages up to a cap, discard oldest when limit hit. Configure by:</p><ul><li>Max message count</li><li>Max bytes</li><li>Max age</li></ul><p>This is your Kafka-equivalent retention. Set it and forget it.</p><p><strong>Interest-based</strong> — message stays until every consumer that has registered interest has acked it. Once all consumers ack = deleted automatically. Nothing discarded while any consumer still hasn’t seen it. Useful when you have multiple independent pipelines all needing the same message.</p><p><strong>Work-queue</strong> — message deleted immediately on ack. Each message processed exactly once then gone. No keeping history, no replay. Closest to a traditional job queue.</p><p><strong>Which one for your architecture?</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/768/1*zyhMP3wuc5fkY-TqQrVl5A.png" /></figure><h4>Kafka → JetStream mapping</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/960/1*8Wn_gXwOt1dci0Fkf3miUg.png" /></figure><p><strong>What doesn’t map cleanly:</strong> Kafka scales via partitions → more partitions = more consumers. JetStream scales differently (multiple streams, subject sharding). This needs separate thought when migrating.</p><p><strong>Deliver Policy</strong> — when a new subscriber attaches, you explicitly tell it where to start:</p><ul><li>DeliverAll — from the very first stored message</li><li>DeliverNew — only future messages, ignore history</li><li>DeliverLast — only the most recent message, then new ones</li><li>DeliverByStartSequence — from a specific sequence number</li><li>DeliverByStartTime — from a specific timestamp</li></ul><h4>Push vs Pull consumers — JetStream only</h4><p><strong>Pull consumer</strong> — you ask the server for messages when you’re ready. You control batch size and pace. Server waits until you ask. If you’re slow, nothing bad happens — no buffer, no disconnect.</p><p><strong>Push consumer</strong> — server sends messages to you immediately without being asked. Server controls the pace. If you can’t keep up, buffer fills up, slow consumer problem kicks in. <strong>Push consumers are now considered legacy</strong> — new projects should use pull consumers.</p><p>In Short:-</p><ul><li>Push — server pushes messages to you (like core NATS feel)</li><li>Pull — you explicitly ask for next batch (like Kafka’s poll loop)</li><li>For Kafka replacement workloads → use <strong>Pull consumers</strong></li></ul><p><strong>Three ways to consume with a pull consumer<br></strong><strong>Fetch(n)</strong> — request exactly N messages, get them back, loop manually. You control exactly when the next batch arrives. Best for batch processing workloads. Direct equivalent of your Kafka batch consume pattern.</p><p><strong>FetchNoWait</strong> — same as Fetch but returns immediately if no messages available instead of blocking. No pause between fetches.</p><p><strong>Consume</strong> — continuous delivery via callback. Consolidates features from both push and pull. Messages arrive as fast as the server can send within flow control limits. Feels like push but pull under the hood — real-time delivery without managing a fetch loop. Best for event-driven processing.</p><p><strong>Which to use</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/822/1*oN9rDTsGr1t88GK9f_MKbw.png" /></figure><p><strong>Why pull replaced push<br></strong>Push consumers couldn’t scale horizontally cleanly. Pull consumers distribute naturally — whoever fetches first gets the messages. All new features (priority groups, pinning, overflow) only work on pull consumers. Legacy push API is not being removed but will not receive new features.</p><h4>How Consume Works Mechanically — JetStream only</h4><p><strong>Kafka poll — for reference<br></strong>You drive the loop explicitly. Every iteration is an explicit request to the broker. You control when to poll, batch size, and timeout. The broker just responds to your requests.</p><pre>while True:<br>    records = consumer.poll(timeout=1000)<br>    # process records<br>    # commit offset<br>    # repeat</pre><p><strong>Fetch(n) — direct Kafka poll equivalent<br></strong>Client sends a fetch request to NATS server. Server responds with up to N messages. You process and ack. You call fetch again when ready. One explicit request per iteration. You drive the loop. You control pace, batch size, and when the next fetch happens.</p><p>This is your existing Kafka batch consume pattern mapped 1:1 to JetStream.</p><p><strong>Consume — Kafka poll loop hidden inside the client<br></strong>You provide a callback. The client library internally runs the fetch loop — sends fetch request, server responds, callback fires per message, when batch drains the client automatically sends next fetch request. Repeat forever without your code doing anything.</p><p>Server behavior is identical to Fetch — still responding to fetch requests. The only difference is who is calling them — your code vs the client library background loop.</p><p><strong>Consume IS Kafka’s poll loop. Just hidden inside the client library instead of your application code.</strong></p><p><strong>Flow control difference — important</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Nwl6Nf9siBBybSk89t6eEw.png" /></figure><p><strong>What the server does in both cases<br></strong>Identical — responds to fetch requests with available messages. Server doesn’t know or care whether it’s your code calling Fetch or the client library calling it internally via Consume. The distinction is purely client-side.</p><h4>Ack system — JetStream’s equivalent of Kafka offset commit:</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/778/1*O071vNcsm8kJ2JoBl1lr6w.png" /></figure><p>Kafka has no native equivalent of Nak, InProgress, or Term — you&#39;d build all that yourself or rely on frameworks like Spring Kafka.</p><p><strong>If you never send an Ack:</strong></p><ul><li>AckWait timer expires → JetStream redelivers automatically</li><li>This is your at-least-once delivery guarantee</li><li>Always set MaxDeliver to something finite — without it, a poison pill loops forever</li></ul><p><strong>Dead letter behavior:</strong></p><ul><li>Term is a first-class protocol primitive in JetStream — one line of code</li><li>In Kafka, dead letter queues are application-level code you write yourself (or get from a framework)</li><li>JetStream designs it in. Kafka bolted it on.</li></ul><p><strong>InProgress vs Kafka heartbeat:</strong></p><ul><li>In the Kafka Python client (aiokafka), background heartbeat ran automatically</li><li>In JetStream, there is no background heartbeat — liveness is <strong>per message</strong></li><li>You must manually send InProgress to reset the AckWait timer while processing</li><li>Some NATS Python client (nats.py) has helpers for this — worth checking</li><li>This is more precise than Kafka — a stuck consumer is detected per message, not just per connection</li></ul><h4>MaxAckPending</h4><p>Limits how many messages can be delivered but not yet acked across ALL workers on a consumer at any given time. Server enforced — not application level.</p><pre>MaxAckPending = 100<br><br>Worker 1 pulls 50 → processing → not acked yet<br>Worker 2 pulls 50 → processing → not acked yet<br>Total unacked = 100 → limit hit<br>→ server suspends ALL delivery on this consumer<br>→ every worker&#39;s next pull returns empty<br>→ Worker 1 acks 10 → total = 90 → delivery resumes</pre><p>Not just new workers blocked — entire consumer pauses. Every worker stops getting messages until pending count drops.</p><p><strong>Critical sizing rule:</strong></p><pre>MaxAckPending must be &gt; batch size × number of workers<br>10 workers × 50 batch = 500 minimum in-flight<br>MaxAckPending = 100  ← too low, throughput tanks silently<br>MaxAckPending = 1000 ← safe headroom</pre><p>Undersizing is a common performance trap — workers keep pulling but get empty responses, no obvious error.</p><p><strong>Why it exists</strong> — without it workers pull millions of messages, crash, millions redeliver simultaneously, system overwhelmed. MaxAckPending keeps in-flight work bounded so crash recovery stays controlled.</p><p><strong>Kafka comparison</strong> — closest equivalent is max.in.flight.requests.per.connection but that&#39;s per producer connection. JetStream MaxAckPending is per consumer across all workers — broader scope, stronger guarantee.</p><h4>Dead Letter Queue — three primitives composed together</h4><p>No single DLQ config — you build it from MaxDeliver, Term, and advisory subjects.</p><p><strong>MaxDeliver</strong> — set on consumer config. After N delivery attempts with no ack → JetStream stops redelivering. Message stays in stream but no longer actively delivered.</p><p><strong>Term</strong> — sent from your code when you detect a poison pill. Immediately stops redelivery without waiting for MaxDeliver to exhaust. One line of code.</p><p><strong>Advisory subjects</strong> — JetStream automatically fires events when either condition hits:</p><ul><li>$JS.EVENT.ADVISORY.CONSUMER.MAX_DELIVERIES.{stream}.{consumer} — MaxDeliver exhausted</li><li>$JS.EVENT.ADVISORY.CONSUMER.MSG_TERMINATED.{stream}.{consumer} — Term received</li></ul><p>Advisory contains the sequence number of the dead message. You create a separate consumer subscribed to these subjects — on advisory received, fetch original message from stream by sequence number, write to a dedicated dead letter stream for inspection and manual reprocessing.</p><p><strong>Full flow:</strong></p><pre>Message delivered → worker processing<br>    → success → Ack → done<br>    → retryable failure → Nak → redelivered with backoff<br>    → MaxDeliver exhausted → advisory fired → DLQ consumer catches it<br>    → poison pill → Term → advisory fired → DLQ consumer catches it<br>DLQ stream → stored for inspection → fix → manually republish</pre><p><strong>Kafka comparison on DLQ:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LxpHJ5taA3Bcm4Y54JkMhg.png" /></figure><p>Kafka bolted DLQ on. JetStream designed it in — the primitives are there, you just wire them together.</p><h4>Ephemeral vs Durable Consumers — JetStream only clarification</h4><p><strong>Durable consumer</strong> — has a name, state persists on the server</p><pre>Consumer name: &quot;orders-processor&quot;<br>    → server remembers its position<br>    → tracks acks, pending, redeliveries<br>    → if all workers disconnect → consumer still exists on server<br>    → workers reconnect → pick up exactly where they left off</pre><p><em>This is what you want for production workloads. Your Kafka consumer group equivalent.</em></p><p><strong>Ephemeral consumer</strong> — no name, state lives only as long as someone is connected</p><pre>Consumer created with no name<br>    → server tracks state only while subscribed<br>    → all subscribers disconnect → consumer deleted automatically after inactivity threshold<br>    → reconnect → starts fresh, no memory of previous position</pre><h4>When to use which?</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/898/1*Vhi3CZh9EJglMal4b7fmww.png" /></figure><p><strong>Practical example</strong></p><pre># Your stream monitor workers → durable<br>consumer: &quot;events-processor&quot;<br>    → crashes → restarts → picks up from last acked message<br><br># You want to inspect what&#39;s in the stream right now → ephemeral<br>connect → read last 100 messages → disconnect → consumer cleaned up<br>automatically</pre><pre><strong>One gotcha</strong></pre><p>Durable consumers persist even when nobody is connected. If you forget to delete them, they accumulate on the server. Always clean up durable consumers you no longer need.</p><p><strong>The real difference between Kafka and JetStream — Ack granularity</strong>|<br>This is not about persistence. Both Kafka and JetStream are persistent durable logs. The fundamental difference is <strong>how you mark messages as done.</strong></p><p><strong>Kafka — watermark commit:</strong></p><pre>Messages: 1, 2, 3, 4, 5, 6, 7, 8, 9, 10<br>Commit offset 10 = everything up to 10 is done<br>You CANNOT say &quot;1,2,3,5 done but 4,6 failed&quot;<br>It&#39;s a watermark — all or nothing up to that point</pre><p><strong>JetStream — per message ack:</strong></p><pre>Messages: 1, 2, 3, 4, 5<br>Ack 1 ✓ → gone<br>Nak 2 → redelivered individually later<br>Ack 3 ✓ → gone<br>Term 4 → dead lettered<br>OOM kill before 5 → redelivered automatically</pre><p><em>Every message is completely independent of every other message.</em></p><h4>JetStream Message Distribution and Scaling</h4><p><strong>Unique distribution</strong> — each worker gets different messages. Same message never goes to two workers from the same consumer. Server tracks what’s in-flight to whom.</p><p><strong>How tracking works — sequence numbers</strong></p><p>JetStream uses sequence numbers, not offsets. Same concept, different name.</p><pre>Stream: [msg1(seq:1), msg2(seq:2), msg3(seq:3) ...]</pre><p>Consumer tracks:</p><ul><li>Last delivered sequence</li><li>Which sequences are acked (done)</li><li>Which sequences are pending (delivered but not acked yet)</li></ul><blockquote>Worker 1 pulls seq 1–50 → server marks in-flight to W1 <br>Worker 2 pulls seq 51–100 → server marks in-flight to W2 <br>Worker 1 acks → server marks done, moves cursor forward</blockquote><p>Server never sends the same sequence to two workers from the same consumer.</p><p><strong>NATS vs Kafka scaling philosophy<br></strong>Kafka — plan partitions upfront. Max consumers = partition count. More throughput = repartition = rebalance = disruption.</p><p>NATS — no partitions. Just start more workers pointing at the same consumer. Server distributes on demand — whoever asks first gets next batch. More throughput = start another worker. No repartition, no rebalance, no disruption.</p><p><strong>Ordering problem and solutions<br></strong>By default — any worker can get any message. No per-key ordering guarantee across parallel workers.</p><p><strong>Subject-per-entity pattern</strong> — give each entity its own subject. One consumer per subject means one worker always handles that entity’s messages. Ordering guaranteed. Only works for bounded known entities, doesn’t scale to millions of dynamic keys.</p><p><strong>Partitioned consumer group library (Orbit)</strong> — client-side library that mimics Kafka consumer groups. Splits stream into virtual partitions by key, assigns workers to partitions. New, not widely used, adds complexity. Only reach for it when you need strict per-key ordering AND parallel processing simultaneously.</p><p><strong>For most workloads </strong>— neither is needed. Multiple workers on the same consumer is enough. Handle any ordering requirements at the application level.</p><h4>Exactly-once — when you can’t tolerate duplicates</h4><p>Two parts work together:</p><p><strong>Publisher side — deduplication<br></strong>Publisher attaches a unique ID to every message (Nats-Msg-Id header). Server remembers IDs for a configurable time window. If publisher sends the same ID twice — server rejects the duplicate silently. Publisher can retry safely without creating duplicates.</p><p><strong>Consumer side — double ack<br></strong>Normal ack is one message: consumer → server. In exactly-once mode it becomes a handshake — server acks back to consumer confirming it received the ack. Eliminates the “ack lost in network” scenario.</p><p><strong>When do you actually need exactly-once?<br></strong>Financial transactions, inventory updates, anything where processing twice causes real damage. For telemetry, sensor data, metrics — at-least-once with idempotent processing is almost always enough and simpler.</p><p><strong>Idempotent processing — the practical shortcut!<br></strong>Instead of implementing full exactly-once machinery, most teams just make their message handler idempotent:</p><p>Message: &quot;set order status to fulfilled&quot; → idempotent, safe to repeat Message: &quot;increment counter by 1&quot; → NOT idempotent, dangerous to repeat Message: &quot;insert row with this ID&quot; → idempotent if you use upsert</p><p>Design your processing so running it twice = same result as running it once. Then at-least-once delivery is effectively exactly-once in practice.</p><h4>Atomic Batch Publishing (NATS 2.12+)</h4><p><strong>The problem it solves<br></strong>Without atomic batching, each publish is independent. Publish 5 related messages, connection drops after 3 → partial write → system in inconsistent state. No way to tie multiple publishes together as one unit.</p><p><strong>What it gives you<br></strong>All or nothing. Either every message in the batch commits together, or none do. Messages are staged invisibly on the server — consumers see nothing until the commit lands.</p><p><strong>How it works — three headers coordinate everything<br></strong>Every message in a batch carries:</p><ul><li>Nats-Batch-Id — unique identifier for the batch (max 64 chars)</li><li>Nats-Batch-Sequence — incrementing number per message, starting at 1</li><li>Nats-Batch-Commit — only on the last message, triggers atomic commit of everything staged</li></ul><p>Intermediate messages get zero-byte acks — lightweight, no data. Final message gets a full pub ack with batch metadata. All messages appear in the stream simultaneously on commit.</p><p><strong>Must be enabled on the stream:</strong>AllowAtomicPublish: true in stream config. Off by default.</p><p><strong>Optimistic locking<br></strong>Optional consistency check on the first message of a batch:<br>Nats-Expected-Last-Sequence — only commit if stream&#39;s last sequence matches this number. Someone else published while you were building your batch → sequence moved → batch fails → you retry with fresh data. Same optimistic concurrency control as KV store compare-and-swap.</p><p><strong>Limits</strong></p><ul><li>Max 1,000 messages per batch</li><li>50 concurrent batches in flight per stream</li><li>1,000 concurrent batches in flight per server</li><li>10 seconds inactivity → batch abandoned and discarded</li><li>Batches cannot cross streams — all messages must target the same stream</li><li>All limits are configurable in server config</li></ul><p><strong>Use cases<br></strong>Event sourcing — single command produces multiple events that must all land together or none. Fan-out — different messages to different subjects (e.g. orders.warehouse, orders.payment, orders.notification) committed atomically. All subscribers receive their message at the same time. If any message fails, none are delivered.</p><p><strong>vs Kafka producer transactions</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PxDxCoMNAK8R2HVmkGQIcQ.png" /></figure><p>The gap that remains — Kafka can atomically commit consumed offsets AND produced messages in one transaction (consume-transform-produce). JetStream atomic batching is publish side only. No equivalent for tying acks to publishes atomically. Handle at application level with idempotency keys.</p><p><strong>Atomic Batch — Subject vs Stream scope clarification<br></strong>Multiple subjects in one batch → ✓ works, as long as they belong to the same stream.</p><p>Multiple streams in one batch → ✗ not possible.</p><p><strong>What it CAN do</strong></p><pre>Stream &quot;ecommerce-events&quot; bound to: ecommerce.&gt;<br>One atomic batch:<br>    orders.payment.processed  → confirmed<br>    inventory.updated  → reserved<br>    notifications.sent   → queued</pre><p>All different subjects, one stream, one atomic commit. All land together or none do.</p><p><strong>What it CANNOT do</strong></p><pre>Stream &quot;ecommerce-events&quot; → ecommerce-events.&gt;<br>Stream &quot;ecommerce-audit&quot;  → audit.&gt;<br><br>Atomic batch across both:<br>    orders.payment.processed  → publish order event<br>    audit.orders.payment    → publish audit log<br>→ Impossible. Two streams = not atomic.</pre><p>Kafka producer transactions can span completely separate topics regardless of organization. NATS has no equivalent for cross-stream atomicity — handle consistency between streams at the application level with idempotency keys.</p><p><strong>Practical implication<br></strong>If your architecture separates concerns into different streams — telemetry in one, audit trail in another, dead letter in another — you cannot atomically write across them. Design your stream boundaries carefully with this in mind. If two things must always land together, they must live in the same stream.</p><p><strong>Language support</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/624/1*BIx4OQ9ok3Sa0tYIWcFs4Q.png" /></figure><p><strong>Manual construction</strong> — not complex, just boilerplate. Generate a batch UUID, set three headers per message, track sequence number yourself, add commit header on last message. What Orbit abstracts away for Go/Java/Rust is exactly this header management — the protocol itself is simple.</p><p><strong>Maturity note<br></strong>Very new. Current release focuses on correctness and atomicity — not performance. Future releases will optimize throughput. Foundation is solid but battle testing at scale is limited. Verify your NATS server version is 2.12+ before using.</p><h4><strong>JetStream Retention and Message Expiry</strong></h4><p>JetStream is a durable log with configurable retention — not a permanent database. Messages leaving the stream is intentional, not a bug.</p><p><strong>Ways a message can disappear:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1006/1*l4PPDNvPw1ruAMB2CF_wEg.png" /></figure><p><strong>No cron jobs needed</strong> — all of the above happen automatically. Just configure the limits and NATS handles cleanup.</p><p><strong>Retention — JetStream vs Kafka</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FnchYMt3-4sy9uUxWNc5Vw.png" /></figure><p><strong>The key philosophical difference<br></strong>Kafka retention is purely time/size based. Kafka doesn’t care whether messages were consumed — message sits for 7 days, gets deleted regardless. Consumer offset is the consumer’s problem.</p><p><strong>JetStream retention can be consumption-aware. Interest policy keeps messages until all consumers ack. WorkQueue deletes on ack. The stream reacts to what consumers are doing, not just a clock.</strong></p><p><strong>Important — at-least-once guarantee interaction</strong></p><p>If a message expires from the stream before your consumer processes it — it’s gone. No redelivery. The at-least-once guarantee only holds while the message exists in the stream.</p><p>Rule of thumb — MaxAge should always be orders of magnitude larger than your AckWait and MaxDeliver window. Never let retention expire a message that&#39;s still waiting to be processed.</p><h4>Pull Consumer Priority Groups (NATS 2.11+)</h4><p>New mechanism for controlling how multiple workers pull from the same consumer. Before 2.11 — random distribution only, no control. Now you can define priority and overflow behavior.</p><p><strong>Two mechanisms:<br></strong>Overflow — primary workers handle all messages. When overwhelmed, messages spill to secondary workers. Triggered by thresholds:</p><ul><li>min_pending — too many messages waiting → overflow kicks in</li><li>max_ack_pending — too many unacked messages → overflow kicks in</li></ul><p>Pinning — exactly one client receives all messages. Others on standby. Active client disconnects → standby takes over automatically. High availability without running multiple active consumers.</p><p><strong>Use cases:</strong></p><ul><li>Zone/region awareness — prefer local workers, overflow to remote only when local is overwhelmed. Reduces cross-AZ latency and cost.</li><li>Active-passive failover — one worker handles everything, others are hot standbys.</li><li>Tiered processing — fast workers handle normal load, slow/expensive workers only activated under pressure.</li></ul><p><strong>Important</strong> — only available on pull consumers. Not available on legacy JetStream API — requires the new consumer API. NATS 2.11+ server required.</p><h4>Consumer Pause (NATS 2.11+) — JetStream only</h4><p>Consumer pausing lets you temporarily halt message delivery to any consumer until a deadline you specify — without losing data, throwing errors, or disconnecting clients.</p><p><strong>How it works<br></strong>Set a PauseUntil deadline — either at consumer creation or via the pause API at runtime. Message delivery stops immediately. The stream still receives messages — they&#39;re just queued up waiting. When the deadline passes, delivery resumes automatically and the consumer catches up on everything published during the pause.</p><p>Clients keep receiving heartbeats the whole time — so your application doesn’t know it’s paused. No errors, no disconnects, no code changes needed.</p><p>One gotcha — if you have a pull consumer and you pull a large number of messages in one batch, the consumer won’t stop consuming messages from that batch. It will only stop after the entire batch has been consumed and it attempts to pull the next batch.</p><p>Pause state is persisted to Raft — server restart does not unpause a paused consumer.</p><p><strong>Use cases</strong></p><ul><li>Maintenance windows — pause before deploying, resume after</li><li>Database migrations — stop processing while schema changes run</li><li>Emergency debugging — freeze message flow while investigating production issue</li><li>Overwhelmed downstream — give a struggling dependency time to recover without killing your consumer</li></ul><p><strong>Notes</strong></p><ul><li>Works on both push and pull consumers</li><li>Can extend or shorten pause duration at any time by calling pause again with a new deadline</li><li>Must specify a deadline — pause is always time-bounded, not indefinite</li><li>Monitor paused consumers — easy to forget one is paused and wonder why processing stopped</li><li>NATS 2.11+ required</li></ul><h4>Stream Multi-Get (NATS 2.11+) — JetStream only</h4><p>Batch retrieval of messages directly from a stream without creating a consumer. One request, multiple messages back, in sequence order.</p><p><strong>How it’s invoked</strong> — direct API call to the JetStream server. One request/reply round trip. You send a request with your subject filters and optional bounds, server responds with matching messages. No subscription, no consumer, no ongoing connection. Closest mental model is a REST GET call — stateless, one shot, results returned immediately.</p><p>MultiLastFor — provide a list of subject filters, get the latest message per subject in one round trip.</p><p>Optional bounds:</p><ul><li>UpToSeq — only return messages up to this sequence number</li><li>UpToTime — only return messages up to this timestamp</li></ul><p><strong>No consumer created</strong> — no cursor, no ack tracking, no server state. Pure read. For inspection and snapshotting, not for processing workloads.</p><p><strong>Use cases</strong> — read latest state across multiple subjects in one call, dashboard snapshots, debugging stream contents without spinning up a consumer.</p><h4>Connection Resilience — Core NATS and JetStream</h4><p><strong>The problem<br></strong>Networks are unreliable. Clients lose connection to NATS server at any time — network blip, server restart, NAT timeout killing idle connections. What happens to your application when this occurs determines whether you lose data or recover silently.</p><p><strong>Auto-reconnect — built in, no code needed<br></strong>Every official NATS client including nats.py automatically reconnects on connection drop. Backoff strategy built in — retries with increasing delays. Your application keeps running during reconnect unless you register a disconnect callback.</p><p>On reconnect automatically:</p><ul><li>Subscriptions re-registered</li><li>Pending outbound publishes buffered and flushed</li><li>Application code unaware unless you hook disconnect callbacks</li></ul><p><strong>JetStream consumers on reconnect<br></strong>Consumer cursor lives on the <strong>server</strong>, not the client. So:</p><pre>Client disconnects mid-processing<br>    → unacked messages → AckWait expires<br>    → JetStream redelivers automatically<br>    → client reconnects → re-subscribes to same durable consumer<br>    → picks up exactly where it left off<br>    → zero messages lost, zero manual recovery</pre><p>Core NATS subscribers on reconnect — start fresh. Miss everything published during the disconnect. No recovery. This is another reason to use JetStream for anything that matters.</p><p><strong>Ping/Pong — dead connection detection<br></strong>Server pings client every N seconds. Client responds with pong. No pong within deadline → connection declared dead and closed. Detects failures in seconds not minutes — this is the fix for TCP’s slow failure detection problem covered in the TCP section.</p><p>Configurable:</p><ul><li>Ping interval — how often server pings</li><li>Max pings outstanding — how many missed pongs before declared dead</li></ul><p><strong>Connection event callbacks</strong></p><p>Hooks for your application code to react to connection events:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/828/1*TY10UiE-dfC9W4ZShTAdOw.png" /></figure><p>Useful for logging, metrics, updating circuit breaker state, alerting.</p><p><strong>Kafka comparison — connection resilience</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9ilaY0PtSeeju6WBZv-prQ.png" /></figure><p><strong>The key difference</strong> — Kafka reconnect triggers a consumer group rebalance. Other consumers pause while partitions are reassigned. NATS durable consumer reconnect is invisible to everyone else — no rebalance, no pause, no impact on other workers. The cursor is on the server, so the worker just picks up where it left off the moment it reconnects.</p><h4>Graceful Shutdown</h4><p><strong>Close vs Drain — the critical distinction</strong></p><p>close() — hard stop. Cuts connection immediately. Messages in outbound buffer, in-flight subscriptions, pending publishes — all lost. Equivalent of kill -9 on your connection.</p><p>drain() — graceful stop. Three phase process:</p><ol><li>Stop accepting new messages on all subscriptions</li><li>Finish processing everything already received</li><li>Flush all pending outbound publishes</li><li>Then close</li></ol><p>Nothing is lost. Everything in flight completes before the connection dies.</p><p><strong><em>Always drain in production. Never close directly.</em></strong></p><p><strong>Why this matters with Kubernetes</strong></p><p>Kubernetes sends SIGTERM before killing a pod. This is your signal to drain gracefully before the hard SIGKILL arrives (default 30 seconds later).</p><p>The pattern:</p><pre>Signal: SIGTERM received<br>    → stop pulling new messages from JetStream<br>    → finish processing in-flight batch<br>    → ack/nak all in-flight messages<br>    → drain NATS connection (flushes outbound)<br>    → exit cleanly<br><br>If SIGKILL arrives before drain completes:<br>    → unacked messages → AckWait expires<br>    → JetStream redelivers to next available worker<br>    → no data loss</pre><p>NATS drain + JetStream per-message ack = no permanent message loss on pod shutdown even if Kubernetes kills you before you finish. The two features combine perfectly — drain handles the network layer, JetStream handles the message layer.</p><p><strong>This is why JetStream + Kubernetes is a natural fit.</strong> You get graceful shutdown for free by combining two primitives that were designed independently but compose perfectly.</p><p><strong>Practical checklist for production</strong></p><ul><li>Always use drain() not close() on shutdown</li><li>Register SIGTERM handler that triggers drain</li><li>Set Kubernetes terminationGracePeriodSeconds longer than your worst-case processing time</li><li>Set NATS MaxPingsOutstanding and ping interval to detect dead connections fast</li><li>Log on disconnected_cb and reconnected_cb for visibility</li><li>Use durable consumers so reconnects are seamless</li></ul><h3>NATS 2.12 New Features — JetStream only</h3><h4>Prioritized Pull Consumer Policy</h4><p>Third policy added on top of 2.11’s overflow and pinning. All three exist to control which workers get messages when multiple workers pull from the same consumer.</p><p>The gap overflow had — it waits for a threshold before routing to secondary workers. If no local workers are actively pulling and the threshold isn’t hit quickly, messages sit waiting. Prioritized fixes this — higher priority workers get messages immediately without waiting for any threshold.</p><p>Trade-off: faster failover but work can bounce between workers if priorities keep changing — called flip-flopping. Overflow is more stable, prioritized is more responsive.</p><p>All three compared:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Cke_XLEMDP7aEp7eWIo8hg.png" /></figure><p>NATS 2.12+ required. Pull consumers only. New consumer API only.</p><h4>Distributed Counter CRDT (2.12+)</h4><p><strong>What is a CRDT first</strong> — Conflict-free Replicated Data Type. A data structure designed so that multiple nodes can update it independently and concurrently without coordination, and the results will always converge to the same value when merged. No locks, no leader needed. Math guarantees consistency.</p><p>In NATS — enable AllowMsgCounter on a stream. Each subject in the stream becomes an atomic distributed counter. Any worker anywhere can increment or decrement it. The server merges all updates correctly regardless of order or network partitions. Counters are implemented as big.Int — no size limit.</p><p>The powerful part — counter streams can be mirrored and sourced across clusters. You can aggregate counters from multiple regions into one global counter, or create verbatim copies per region. Aggregation behavior is configurable.</p><p>Use cases — distributed rate limiting, global tallying across services, aggregating counts across regions or clusters. No Redis needed for counters. No coordination code needed in your application.</p><h4>Delayed Message Scheduling (2.12+)</h4><p>Publish a message now, have it delivered to consumers after a specified delay. Enable AllowMsgSchedules on stream config, attach a delay header to the message. Server holds the message and makes it available to consumers only after the delay expires.</p><p>Before 2.12 — teams used Nak-with-delay as a workaround. That was always a hack. The native scheduler supersedes it entirely and is built on the per-message TTL infrastructure so it handles large numbers of scheduled messages efficiently.</p><p>Current limitation — single one-off delays only. Cron-style repeated scheduling is planned for future releases but not yet available. (<a href="https://github.com/nats-io/nats-server/discussions/7672#discussioncomment-15311571">https://github.com/nats-io/nats-server/discussions/7672#discussioncomment-15311571</a>)</p><p>Use cases — job scheduling, delayed notifications, retry-after patterns, deferred processing, anything where a message should not be acted on immediately after publishing.</p><h3>Data Stores — KV store &amp; Object Store</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/724/1*MqxD2PXFpjPd-9mw1ez-pg.png" /><figcaption>Screenshot from Synadia&#39;s Interactive NATS Guide at nats.synadia.com</figcaption></figure><h4>NATS KV Store</h4><p>Built on top of JetStream. Every bucket = a JetStream stream internally. Keys map to subjects, values map to message payloads, revisions map to sequence numbers.</p><p><strong>Operations</strong> — get, put, delete, purge, watch, history, keys</p><p><strong>Bucket config</strong> — max history per key, TTL, max bucket size, replication factor, storage type (file or memory)</p><p><strong>Watch</strong> — native reactive notifications on key changes. Subscribe to a pattern like user.123.&gt; and get notified instantly on any change. No polling. Just a JetStream consumer with a subject filter under the hood.</p><p><strong>TTL</strong> — configured per bucket and per key. Keys expire automatically.</p><p><strong>History</strong> — keeps N previous values per key. Every write increments a revision number (r1, r2, r3…).</p><p><strong>vs Redis</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*aRoG7Wc-2yjSzdjijiWuuQ.png" /></figure><p><strong>Durability</strong> — FileStorage + Raft replication across cluster nodes. Same guarantees as JetStream. Survives node failures and restarts.</p><p><strong>Optimistic concurrency control — Compare and Swap</strong></p><p>Every value has a revision number. Put with last known revision — if revision doesn’t match (someone else updated it), operation rejected. No locks, no blocking, just conflict detection. Your code re-reads and retries.</p><p>Worker A reads revision 5 → updates → becomes revision 6 ✓ Worker B reads revision 5 → tries update → revision is 6 now → rejected ✗ → re-read → retry</p><p><strong>Can you use it as a DB?</strong> — no. Good for config, feature flags, distributed state, coordination, service discovery. Bad for complex queries, large datasets, relational data. Think etcd, not PostgreSQL.</p><p><strong>Good for circuit breaker</strong> state shared across worker processes, configuration hot reload, and worker coordination.</p><h4>NATS Object Store</h4><p>Also built on JetStream. Designed for storing large binary files — documents, binaries, large configs.</p><p>Chunks files into small pieces, stores each chunk as a stream message. A 1GB file never travels as one payload — streamed in chunks transparently. Same concept as MongoDB GridFS.</p><p><strong>Versioning</strong> — no. One version per named object. Overwrite = old one gone. No revision history unlike KV store.</p><p><strong>Large files and performance</strong> — chunking means large files don’t block or slow down the messaging side. Each chunk is a normal JetStream message. NATS handles it the same way it handles any other stream data.</p><p><strong>Use cases</strong> — storing firmware binaries, config files, model weights, any large blob that needs to live alongside your messaging infrastructure without spinning up a separate file storage system.</p><p>The <strong>Kafka migration checklist</strong> — a clean mapping section at the end before the governance note. Something like:</p><h3><strong>Migrating from Kafka to NATS JetStream — Mental Model</strong></h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*YmuqjVv9eWzJwHVw" /><figcaption>Photo by <a href="https://unsplash.com/@jcraice?utm_source=medium&amp;utm_medium=referral">Julia Craice</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>The concepts map, but the philosophy shifts. Here’s what to rethink:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4HPtR6Xoivt2k_bw2TY6jw.png" /></figure><p><strong>What you gain:</strong></p><ul><li>No partition planning</li><li>No rebalancing pauses</li><li>Per-message ack granularity</li><li>DLQ built in</li><li>KV store and Object Store in the same system</li></ul><p><strong>What you need to rethink:</strong></p><ul><li>No consumer group concept — pull consumers scale by sharing same consumer name</li><li>Subject naming matters more than topic naming — design it upfront</li><li>Ordering per key requires explicit design — not guaranteed by default</li></ul><h3>Limitations and where Kafka still wins</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*0LZWXAKr1FZsozbO" /><figcaption>Photo by <a href="https://unsplash.com/@ric3b0wl?utm_source=medium&amp;utm_medium=referral">Sam Xu</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3>1. Partitioning, consumer assignment, and ordering</h3><p>NATS absolutely simplified a lot for me, but calling it a full Kafka replacement would be too broad. The biggest gap is that JetStream still does not map cleanly to Kafka’s partition-centric model. NATS’ own docs say that core queue groups and JetStream durable consumers are <strong>partition-less and non-deterministic</strong>, so if a workload depends on strict per-key ordering with horizontal scale, you usually end up building subject-based deterministic partitioning or other manual patterns rather than relying on built-in partition assignment the way you would in Kafka. Kafka, by contrast, treats partitions and offsets as first-class consumption units. (1)(2)(3)</p><h3>2. Batch publish is better now, but it is still not Kafka transactions</h3><p>Some older criticism of JetStream also needs updating. JetStream supports AckAll, which lets an acknowledgment for a later message acknowledge earlier pending messages in the same series, and NATS 2.12 introduced AllowAtomicPublish for atomically publishing a batch of messages into a stream. But that still is not the same thing as Kafka’s transactional model: Kafka producers can send consumer offsets into the same transaction, and those offsets are only committed if the transaction itself commits successfully. So if your architecture depends on atomic read-process-write flows or tighter stream-processing semantics, Kafka still has stronger built-in primitives. (4)(5)(6)</p><h3>3. Ecosystem and managed-service maturity</h3><p>The operational story has trade-offs too. Managed NATS does exist through Synadia Cloud, and Synadia also supports managing your own NATS systems through that platform. But Kafka currently has more obvious first-party major-cloud managed options, including Amazon MSK, Azure Event Hubs with Kafka protocol support, and Google Cloud Managed Service for Apache Kafka. There is also no Kafka API drop-in compatibility claim from NATS itself that I could verify; the official integration path I found is a NATS–Kafka bridge. And while Python is officially supported, the Python client story is still evolving: nats.py remains the main Python client, nats-core only had its initial release in February 2026, and there is an open nats.py issue around atomic batch publish. (7)(8)(9)(10)(11)(12)(13)(14)</p><h3>4. Durability depends heavily on version and configuration</h3><p>Finally, durability claims should be treated as version- and configuration-sensitive. Jepsen’s analysis of NATS 2.12.1 found scenarios involving acknowledged-write loss and persistent split-brain under certain failures. NATS’ own docs also say JetStream’s file-based streams do not immediately fsync by default; instead, the server uses a configurable sync_interval, with a default of two minutes, and sync_interval: always provides stronger durability at a throughput cost. So for business-critical durability, the right takeaway is not that JetStream is bad, but that you should validate the exact failure model, version, replication settings, and fsync strategy you plan to run in production. (15)(16)</p><h3>References</h3><p>(1) <a href="https://docs.nats.io/nats-concepts/subject_mapping?utm_source=chatgpt.com">NATS Docs, <strong>“Subject Mapping and Partitioning.”</strong> </a><br> (2) <a href="https://kafka.apache.org/42/design/design/?utm_source=chatgpt.com">Apache Kafka Docs, <strong>“Design.”</strong></a> <br> (3) <a href="https://kafka.apache.org/22/javadoc/org/apache/kafka/clients/consumer/KafkaConsumer.html?utm_source=chatgpt.com">Apache Kafka Docs, <strong>“KafkaConsumer — Offsets and Consumer Position.”</strong> </a><br> (4) <a href="https://docs.nats.io/nats-concepts/jetstream/consumers?utm_source=chatgpt.com">NATS Docs, <strong>“Consumers.”</strong> (</a><a href="https://docs.nats.io/nats-concepts/jetstream/consumers?utm_source=chatgpt.com">AckAll) </a><br> (5)<a href="https://docs.nats.io/release-notes/whats_new/whats_new_212?utm_source=chatgpt.com"> NATS Docs, <strong>“NATS 2.12.”</strong> (</a><a href="https://docs.nats.io/release-notes/whats_new/whats_new_212?utm_source=chatgpt.com">AllowAtomicPublish) </a><br> (6) <a href="https://kafka.apache.org/30/javadoc/org/apache/kafka/clients/producer/KafkaProducer.html?utm_source=chatgpt.com">Apache Kafka Docs, <strong>“KafkaProducer — sendOffsetsToTransaction.”</strong> </a><br> (7) <a href="https://docs.synadia.com/cloud?utm_source=chatgpt.com">Synadia Docs, <strong>“Synadia Cloud Overview.”</strong> </a><br> (8) <a href="https://docs.synadia.com/cloud/walkthrough">Synadia Docs, <strong>“Synadia Cloud Walkthrough.”</strong> </a><br> (9) <a href="https://docs.aws.amazon.com/msk/latest/developerguide/what-is-msk.html">AWS Docs, <strong>“What is Amazon MSK?”</strong> </a><br> (10) <a href="https://learn.microsoft.com/en-us/azure/event-hubs/azure-event-hubs-apache-kafka-overview">Microsoft Docs, <strong>“Apache Kafka Protocol Support in Azure Event Hubs.”</strong> </a><br> (11) <a href="https://docs.cloud.google.com/managed-service-for-apache-kafka/docs/overview?utm_source=chatgpt.com">Google Cloud Docs, <strong>“Managed Service for Apache Kafka Overview.”</strong> </a><br> (12) <a href="https://github.com/nats-io/nats-kafka">GitHub, <strong>“NATS-Kafka Bridge.”</strong> </a><br> (13) <a href="https://docs.nats.io/using-nats/developer">NATS Docs, <strong>“Developing With NATS.”</strong> (Python listed as Synadia-supported) </a><br> (14) <a href="https://github.com/nats-io/nats.py/releases">GitHub</a>, <strong>nats.py / </strong><strong>nats-core / </strong><a href="https://github.com/nats-io/nats.py/issues/811"><strong>Issue #811.</strong> </a><br> (15) <a href="https://jepsen.io/analyses/nats-2.12.1">Jepsen, <strong>“NATS 2.12.1.”</strong></a> <br> (16) NATS Docs, <strong>“</strong><a href="https://docs.nats.io/nats-concepts/jetstream"><strong>JetStream</strong></a><strong>”</strong> and <strong>“</strong><a href="https://docs.nats.io/running-a-nats-service/configuration"><strong>Configuring NATS Server.</strong></a><strong>”</strong> (sync_interval, fsync behavior)</p><h3>A Note on NATS Governance</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*5zEsdmvjV_dwaPbq" /><figcaption>Photo by <a href="https://unsplash.com/@charles_forerunner?utm_source=medium&amp;utm_medium=referral">Charles Forerunner</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>In April 2025, Synadia — the primary maintainer of NATS — attempted to withdraw the project from CNCF and move future releases to a Business Source License. It got messy fast. By May 1, 2025 it was resolved — Synadia confirmed no BSL fork, Apache 2.0 stays, and the trademark was formally transferred to the Linux Foundation. You can read the full story <a href="https://www.theregister.com/2025/05/02/cncf_synadia_nats/">here</a>.</p><p>As of April 2026 the project is actively maintained, shipping on a 6-month release cycle, and firmly under CNCF stewardship. The drama actually left things in a structurally better place than before — trademark locked with Linux Foundation, Apache 2.0 explicitly reconfirmed, community pressure demonstrated how widely adopted NATS actually is.</p><p>The residual risk worth knowing: Synadia is still essentially the only major contributor. If they fold, NATS loses its primary driver. But that’s true of most CNCF projects. For self-hosted Apache 2.0 deployments you’re fully insulated from whatever happens commercially with Synadia.</p><p><strong><em>Eyes open — but safe to bet on.</em></strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b9f0b5ca94ed" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[“Gracefully” Implementing Graceful Shutdowns]]></title>
            <link>https://medium.com/@jainal/gracefully-implementing-graceful-shutdowns-5da48ea48e43?source=rss-f011d9c738f4------2</link>
            <guid isPermaLink="false">https://medium.com/p/5da48ea48e43</guid>
            <category><![CDATA[websocket]]></category>
            <category><![CDATA[kubernetes]]></category>
            <category><![CDATA[fastapi]]></category>
            <category><![CDATA[graceful-shutdown]]></category>
            <dc:creator><![CDATA[Jainal Gosaliya]]></dc:creator>
            <pubDate>Wed, 10 Apr 2024 21:10:12 GMT</pubDate>
            <atom:updated>2024-04-10T21:10:12.349Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Gv3W0RsSOJo1QyNkN0JeLg.png" /></figure><blockquote>This is a followup article to my previous article on implementing an end-to-end graceful shutdown system. In my previous blog, I explained concepts behind the working of a system where graceful shutdown is implemented and also other details on describing the components of graceful shutdowns with Kubernetes. If you want to take a look at that article you can read that article below.</blockquote><p><a href="https://medium.com/@jainal/mastering-graceful-shutdown-in-distributed-systems-and-microservices-29c311e49660">Mastering Graceful Shutdown in Distributed Systems and Microservices</a></p><p>However, this article is independent and if you know what a graceful shutdown is and are just looking for ways to implement it, this blog is all you need. We will directly, dive deep into the code &amp; implementation part and not discuss the boring theory behind it.</p><pre>&quot;Talk is cheap. Show me the code.&quot; <br>- Linus Torvalds</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/200/0*lHeLfxmZtP3d1WnS" /></figure><p>In a hurry 🏃♀️ and want to just get the code? 🔽:</p><p><a href="https://github.com/jainal09/fastapi-gracefulshutdown-websockets">GitHub - jainal09/fastapi-gracefulshutdown-websockets: Gracefully shutdown Fastapi Servers with websocket clients connections</a></p><h3>Overview</h3><h3>What are we trying to achieve?</h3><p>Imagine a backend system where users can submit tasks such as orders, AI tasks, or any long-running tasks through a rest API. Whenever a task is created it is enqueued to a queue and is picked up by the worker when it is free to pick a task. Once, a user’s task is completed they are notified through push notification using web sockets if they are online and are still connected to the backend systems.</p><p>This seems like a reasonable assumption for lots of services and use cases out there in which such implementation running in production.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/999/0*hP9LLxp8Doewb8yg" /></figure><p>Now, imagine finding a huge vulnerability with P1 status or you just want to add some new awesome features and deploy a feature update.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*XHz-QU4XJFm5OKqm" /></figure><p>The question always remains on the strategy of deploying this in such a way that the user’s submitted tasks are not lost and they are notified before the new version is deployed while also ensuring no downtime,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*AfbxxUUs_8yGGLMB" /></figure><p>Now, that you got an idea of the problem in hand, let’s see what the implementation looks like.</p><h3>Overview</h3><h3>Tech Stack</h3><p>Programming Language — Python</p><p>Backend Framework — Fast API web server</p><p>Deployment — Kubernetes</p><p>However, I believe the language and frameworks are not important here, it just the way it is built and handled is that matters.</p><h3>Architecture</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*EzCCA8pz8ilXu3mH" /></figure><p>As seen in the above image we have a FastAPI server, deployed in a pod of Kubernetes with min-replicas set to 1 for simplicity. It has a rest API to send tasks, a WebSocket interface for sending task status events to the clients, and a signal listener that listens to pod termination signals sent by Kubernetes.</p><p>Through the rest API, a task is created and enqueued to the inbuilt FastApi background queue and is later processed by the worker. Once, the task is processed the client is notified via WebSocket.</p><p>The custom-implemented signal listener listens to all the <a href="https://www.ibm.com/docs/en/aix/7.2?topic=management-process-termination">SIGTERM</a> signals send by the Kubernetes controller when a pod termination happens. This is the watcher that steers the entire graceful shutdown part.</p><h3>Implementing</h3><p>First, let’s check out the custom signal handler. When you google FastAPI os signal or event listener it takes you to this doc: <a href="https://fastapi.tiangolo.com/advanced/events/">Lifespan Events</a>. Our, goal is to intercept a SIGTERM signal sent to our fast API server, if you use the Lifespan events it will first stop the server and execute your task binded to the event. This is bad for us as it will terminate the WebSocket client connections.</p><p>So, inorder to just intercept we can just register a signal register, that will register a SIGTERM signal and pass a handler that can be triggered when that SIGTERM signal is sent.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1f38cdfc297a43b8dd1dabbda2ec06c0/href">https://medium.com/media/1f38cdfc297a43b8dd1dabbda2ec06c0/href</a></iframe><p>As seen in the above code, when we invoke the register signal handler for SIGTERM and SIGINT. And in the handle exit, we will wait until all the remaining tasks in the background queue are complete, and then only, we will terminate our WebSocket connection and imitate a server shutdown.</p><p>This signal handler registered on server startup through the @app.on_event(“startup”)</p><pre>@app.on_event(&quot;startup&quot;)<br>def chain_signals():<br>    signal_handler.register_signal_handler()</pre><p>Believe me, this is all you need to do! I mean, sure you need some more tiny other stuff like the Kubernetes config etc, but this is the only main part.</p><h3>Read Flag and the Health API</h3><p>We have readFlag which is a boolean value and is set to true by default. When your signal handler intercepts the termination signal, the readFlag is set to false.</p><p>When anyone calls the health check endpoint, based on the readFlag value the status code 200 or 503 is sent.</p><p>In Kubernetes the readinessProbe will call the health check endpoint defined in the path and will check the status code as 200. Once, the application sends a non-200 signal, Kubernetes considers the probe as failed depending on the failureThreshold setting in the probe configuration. it will wait n times in a row, before considering the probe to have failed.</p><p>Once, it is determined as the probe to be failed, no new connections will be sent to this pod.</p><blockquote><em>This is important because, we want the existing clients to be connected until their published tasks are finished but, we also don’t want new clients to be connected to this terminating pod and post new tasks</em></blockquote><p>Also, in your application logic, always check the flag value before accepting a task or a connection, to ensure any race condition between Kubernetes pod termination and task creation. Like you see in the below snippets, the create_task and connect only allow if the readFlag is set to true.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/25d7d8eae9689d8d012dc9302d70bff4/href">https://medium.com/media/25d7d8eae9689d8d012dc9302d70bff4/href</a></iframe><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/09b021b6b53cee305b98692408720810/href">https://medium.com/media/09b021b6b53cee305b98692408720810/href</a></iframe><h4>Kubernetes Config</h4><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d0191f894a404ea4d97a7621f667efb7/href">https://medium.com/media/d0191f894a404ea4d97a7621f667efb7/href</a></iframe><p>This is just your normal-looking Kube manifest file. The only important part here is the readinessProbe as mentioned before and the terminationGracePeriodSeconds which is the max seconds to wait for a graceful shutdown before killing it forcefully.</p><p>Watching it all in action</p><p>So, now that we understand the bits and pieces of the system, it’s time to look at the big picture, watching the entire system handle graceful shutdowns.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/500/0*l96PanlS5urYK4t4" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*LjGbF9AyqnY_nEOW" /></figure><p>Demo 1</p><p>As you can see in the above image, first we publish some tasks to the service. Through another API endpoint, we can check the number of tasks in the queue.</p><p>As soon as we send the kubectl delete pod {pod_name} the SIGTERM is sent to the fast-api application and it prevents instant termination and waits for all tasks to be processed and sent to the web-socket clients.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*6Yqv3RE0cKUyhhCp" /></figure><p>Demo 2</p><p>In this above demo, we can see that 2 clients are connected to the pod and there are some tasks enqueued. As soon as we terminate the pod and we try to connect a new client, it gets connected to a new pod and not the previous pod as the read flag will start sending non 200 status code responses for the health check route. But, our initial clients are still connected and are kept connected until all the responses are delivered.</p><h3>Conclusion</h3><p>This summarizes what we want to achieve with a graceful shutdown in a Kubernetes environment. By implementing a custom signal handler in our FastAPI backend and leveraging Kubernetes’ readiness probes and terminationGracePeriodSeconds, we’ve ensured that:</p><p>1. User-submitted tasks are not lost during deployment or pod termination.</p><p>2. Existing clients remain connected until their tasks are completed, preventing new connections to a terminating pod.</p><p>3. The system provides feedback to clients about the status of their tasks through WebSocket notifications.</p><p>4. Race conditions between Kubernetes pod termination and task creation are mitigated using a readFlag mechanism.</p><p>5. The application gracefully shuts down by waiting for all pending tasks to be completed before terminating.</p><p>This approach ensures high availability, maintains user experience, and minimizes downtime during deployments or system updates. Remember, the key is not just in knowing what a graceful shutdown is, but in effectively implementing it to handle real-world scenarios seamlessly.</p><p>Ready to level up 🚀 your backend engineering game? Subscribe to <a href="https://www.linkedin.com/newsletters/scale-bites-7169831353377619968/">Scale Bites</a>, your ultimate guide to mastering the art of scalability. Dive into concise, actionable insights delivered straight to your inbox, tackling the toughest challenges in system design. Whether you’re a seasoned pro 👨💻 or just starting out 🎓, Scale Bites has something for everyone. Join the community 👫 on LinkedIn and embark on a journey to build robust, future-proof systems. Don’t miss out — subscribe now and scale new heights, one bite at a time.</p><p>#GracefulShutdown #SystemDesign #Microservices #DevOps #DistributedSystems #BackendEngineering #Kubernetes #Containerization #Scalability #TechBlog #SoftwareEngineering #SystemReliability #Coding #Programming #DataIntegrity #TechTips #ITInfrastructure #SoftwareDevelopment #CloudComputing #ContainerOrchestration #ContinuousIntegration #ScaleBites #Newsletter</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5da48ea48e43" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Mastering Graceful Shutdown in Distributed Systems and Microservices]]></title>
            <link>https://medium.com/@jainal/mastering-graceful-shutdown-in-distributed-systems-and-microservices-29c311e49660?source=rss-f011d9c738f4------2</link>
            <guid isPermaLink="false">https://medium.com/p/29c311e49660</guid>
            <category><![CDATA[devops]]></category>
            <category><![CDATA[kubernetes]]></category>
            <category><![CDATA[microservices]]></category>
            <category><![CDATA[distributed-systems]]></category>
            <category><![CDATA[graceful-shutdown]]></category>
            <dc:creator><![CDATA[Jainal Gosaliya]]></dc:creator>
            <pubDate>Sun, 17 Mar 2024 17:19:30 GMT</pubDate>
            <atom:updated>2024-03-17T17:19:30.324Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GoCH-2EAg4hSaFPU_zbOZg.png" /></figure><h3>Introduction</h3><p>In the intricate landscape of distributed systems and microservices, ensuring seamless transitions during shutdown procedures is paramount. Graceful shutdown, a concept pivotal to this endeavor, not only minimizes disruptions but also safeguards data integrity. This blog elucidates the intricacies of graceful shutdown and offers expert strategies for its seamless implementation.</p><h3>Understanding Graceful Shutdown</h3><p>In the intricate dance of distributed systems and microservices, graceful shutdown stands as a crucial choreography. It orchestrates the cessation of services with finesse, minimizing disruptions and upholding data integrity. From updating deployments to scaling down resources, its necessity in handling failures is indisputable. Yet, its execution is riddled with challenges, from managing in-flight requests to preserving data consistency amidst dependencies.</p><h3>Strategies for Graceful Shutdown</h3><p>1. Signal Handling: The initiation of graceful shutdown often hinges on signals like SIGTERM. Crafting robust signal handling mechanisms is essential, tailored to the idiosyncrasies of different programming languages and frameworks.</p><p>2. Connection Draining: As requests flow ceaselessly, connection draining techniques ease the burden of ongoing interactions. Load balancer configurations play a pivotal role, gradually diverting traffic away from services with finesse.</p><p>3. Dependency Management: In the intricate web of microservices, dependencies intertwine. Managing them during shutdown requires delicacy, preventing cascading failures by gracefully handling upstream and downstream services.</p><p>4. Data Integrity: As curtains draw close, preserving data integrity becomes paramount. Techniques ranging from flushing buffers to persisting state ensure the sanctity of information, even amidst long-running processes or background tasks.</p><h3>Context of Graceful Shutdown</h3><p>In the context of graceful shutdown, this script showcases several key aspects:</p><ul><li>Signal Handling: Termination signals (SIGINT, SIGTERM) trigger the graceful shutdown process, allowing the application to clean up resources.</li><li>Producer-Consumer Pattern: The script demonstrates how to gracefully stop a producer and wait for consumers to finish processing remaining tasks before exiting.</li><li>Asynchronous Programming: Asynchronous tasks are used to manage concurrent operations efficiently, ensuring responsiveness during shutdown procedures.</li><li>Containerization: The Dockerfile enables seamless deployment of the application in containerized environments, facilitating scalability and resource isolation.</li></ul><h3>Kubernetes Integration</h3><p>Kubernetes gives us a fine grain control for handling graceful shutdowns.</p><p>The Kubernetes deployment configuration ensures that the application gracefully handles pod termination, enhancing reliability and resilience in a distributed environment.</p><p>Well, in production the lifecycle of kubernetes pod termination is as follows:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*c7GYGObrOHcxMbRfAb5UAA.png" /><figcaption>Kubernetes Pod Termination</figcaption></figure><ol><li>User Initiates Pod Deletion: The process starts when a user submits a request to delete a Pod through the Kubernetes API.</li><li>Kubelet Receives Pod Deletion Event: The Kubernetes control plane (e.g., API server) sends a Pod deletion event to the Kubelet running on the node where the Pod is scheduled.</li><li>Kubelet Calls PreStop Hook (if defined): If a preStop hook is defined in the Pod specification, the Kubelet calls this hook before terminating the containers. The preStop hook allows containers to perform cleanup operations.</li><li>PreStop Hook Completes: After the preStop hook finishes executing, the Kubelet proceeds with the termination process.</li><li>Kubelet Sends SIGTERM Signal: The Kubelet sends a SIGTERM signal to the main process inside each container in the Pod, signaling it to gracefully terminate.</li><li>Graceful Shutdown Period: Kubernetes provides a configurable grace period (typically 30 seconds by default) for the containers to handle the SIGTERM signal, perform cleanup tasks, and shut down gracefully.</li><li>Application Shuts Down: During the graceful shutdown period, the application running inside the containers should handle the SIGTERM signal, flush any data to disk, and cleanly stop any running processes.</li><li>Kubelet Sends SIGKILL (if necessary): If the grace period expires and the containers have not terminated, the Kubelet sends a SIGKILL signal to forcibly terminate the remaining processes within the containers.</li><li>Kubelet Notifies API Server of Pod Termination: After all containers have been terminated, the Kubelet notifies the Kubernetes API server that the Pod has been terminated.</li><li>API Server Confirms Pod Deletion: The API server confirms the Pod deletion to the user who initiated the request.</li></ol><p>In terms of resource cleanup such as network, Storage &amp; pod itself following is the lifecycle for it:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SsQt-mPVI6gCqg0mZzijlw.png" /><figcaption>Kubernetes Pod Termination (cleanup)</figcaption></figure><ol><li>User Initiates Pod Deletion: The process begins when a user executes the kubectl delete pod command to delete a Pod.</li><li>Container Runtime Interface (CRI): The kubelet interacts with the Container Runtime Interface (CRI) to stop the Pod. The CRI sends a SIGTERM signal to the Pod to initiate a graceful shutdown.</li><li>Graceful Shutdown Period: The Pod has a configurable grace period (typically 30 seconds by default) to handle the SIGTERM signal, perform cleanup tasks, and shut down gracefully.</li><li>Container Network Interface (CNI): After the Pod has terminated, the Container Network Interface (CNI) is responsible for removing the network resources associated with the Pod, such as network interfaces and IP addresses.</li><li>Container Storage Interface (CSI): The Container Storage Interface (CSI) removes any persistent volumes or storage resources that were attached to the Pod.</li><li>Pod Removal: Once the network and storage resources have been cleaned up, the Pod object itself is removed from the Kubernetes cluster.</li><li>Cluster State Update: The Kubernetes control plane updates the cluster’s desired state to reflect the removal of the Pod.</li></ol><p>Important, thing to note here is that resources such as Network and Volumes are removed after the pod is removed. But, when we are gracefully terminating a pod we want all the pending jobs to complete and send the results to the existing connected clients. But, we also, dont want to accept new client connections and new jobs and those new connections should be redirected to the new pod that was started as soon as we send the pod termination to current pod. So, how do we restrict new client to connect to the pod during the pod-termination while also, actively maintain existing clients. By, allowing the pod to intercept, SIGTERM signals and set up readinessProbe</p><pre>readinessProbe:<br>  httpGet:<br>    path: /health<br>    port: 8080<br>  initialDelaySeconds: 5<br>  periodSeconds: 5</pre><p>Through the readinessProbe kubernetes will call the endpoint defined in the path and will check the status code as 200. The period duration of this is done through periodSeconds. Once, the application sends a non-200 signal. The duration Kubernetes waits before considering the probe as failed depends on the failureThreshold setting in the probe configuration. The failureThreshold specifies the number of consecutive failures that must occur before the probe is considered to have failed. By default, the failureThreshold is set to 3, meaning that if the probe fails 3 times in a row, Kubernetes will consider the probe to have failed.</p><p>Now for Graceful shutdowns and efficiently handle client connections, your application should intercepts a SIGTERM signal and start sending a non-200 status code. During a readiness probe, Kubernetes marks the pod as not ready. This means the pod will not receive new traffic from the service, but it does not immediately terminate existing connections. The existing connections are maintained until they are closed or a timeout is reached. This behavior is crucial for graceful shutdown, allowing the pod to finish processing current requests before being terminated.</p><p>However, it’s important to note that while the pod is marked as not ready and stops receiving new traffic, it can still make outbound requests if needed. This means that if your application has dependencies on external services or needs to complete processing for existing connections, it can do so without interruption. The pod’s ability to make outbound requests is not affected by its readiness status.</p><p>In summary, if your application intercepts a SIGTERM signal and starts sending a non-200 status code during a readiness probe, Kubernetes will mark the pod as not ready and stop sending new traffic to it. However, existing client connections are not immediately terminated and can continue to be processed until they are closed or a timeout occurs. This ensures that your application can gracefully shut down, completing any necessary processing before the pod is terminated.</p><p>By incorporating these elements, we can exemplifies best practices for implementing graceful shutdown in distributed systems and microservices, ensuring stability and data integrity even during transitions.</p><h3>Implementing Graceful Shutdown: A Code Walkthrough</h3><p>To understand how graceful shutdown is implemented in practice, let’s dissect the provided Python script along with its Dockerfile and Kubernetes deployment configuration.</p><p>The Python Script</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/81d427cb64f6327c45ec319571b3ae13/href">https://medium.com/media/81d427cb64f6327c45ec319571b3ae13/href</a></iframe><p>This Python script simulates a distributed system where there’s a producer adding events to a shared queue and multiple consumers processing these events concurrently. Here’s a breakdown of what’s happening:</p><ul><li>The producer function simulates adding events to the queue at regular intervals.</li><li>The heavy_task function simulates CPU-bound processing.</li><li>The consumer function dequeues events from the queue, processes them, and marks them as done.</li><li>The signal_handler function catches termination signals (SIGINT and SIGTERM) and sets the stop_event.</li><li>In the main function, the producer and consumers are started as asynchronous tasks. Upon receiving a termination signal, the script waits for the producer to stop and then waits for all consumers to finish processing remaining tasks before exiting.</li></ul><p>Dockerfile</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e830aad0020c32ffa0a0709222748974/href">https://medium.com/media/e830aad0020c32ffa0a0709222748974/href</a></iframe><p>This Dockerfile sets up the Python environment, copies the Python script (async.py) into the container, and sets it as the entrypoint.</p><p>Running the code in the docker container looks like this:-</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_4WA3Cz7A1HsPuHJ9woTHA.gif" /><figcaption>Graceful Shut Down as a Docker Container</figcaption></figure><p>As you can see the when the sigterm signal is sent from the docker cli, the producer script stops producing events to the queue and the consumer processes events from the queue, when all the remaining tasks are completed then only the container stops as compared to abruptly killing the container on docker container stop.</p><h4>Kubernetes Deployment Configuration</h4><p>Having the same image running in the container yields the same result as seen in the below gif.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/615a4187388daa62b795c49c2b273e19/href">https://medium.com/media/615a4187388daa62b795c49c2b273e19/href</a></iframe><p>This Kubernetes Deployment configuration deploys the containerized application (`jainal09/graceful-shutdown`) with one replica. It specifies a termination grace period of 300 seconds, allowing time for graceful shutdown when a termination signal is received.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wpyIrrNF-nYV1VaMgOqsww.gif" /><figcaption>Graceful shut down in kubernetes</figcaption></figure><h3>Testing and Validation</h3><p>In the crucible of reliability, testing shutdown procedures is non-negotiable. Through chaos engineering or integration testing, the efficacy of graceful shutdown mechanisms is validated, fortifying systems against potential disruptions.</p><h3>Monitoring and Observability</h3><p>As the symphony of shutdown unfolds, monitoring and observability serve as vigilant guardians. Detecting and diagnosing issues in real-time, they ensure the harmony of services amidst transitions. Key metrics and monitoring tools provide a compass for navigating these turbulent waters.</p><h3>Conclusion</h3><p>Graceful shutdown isn’t merely a technical maneuver; it’s the backbone of system stability and reliability. By mastering its intricacies, experts in distributed systems and microservices fortify their infrastructure against disruptions, ensuring seamless transitions even in the face of uncertainty.</p><p>#GracefulShutdown #DistributedSystems #Microservices #DevOps #Kubernetes #SystemReliability #TechBlog</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=29c311e49660" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Competitive Coding using Travis-CI]]></title>
            <link>https://medium.com/club-devbytes/competitive-coding-using-travis-ci-d2c1e2b0042f?source=rss-f011d9c738f4------2</link>
            <guid isPermaLink="false">https://medium.com/p/d2c1e2b0042f</guid>
            <category><![CDATA[github]]></category>
            <category><![CDATA[competitive-coding]]></category>
            <category><![CDATA[travis-ci]]></category>
            <category><![CDATA[hackerearth]]></category>
            <category><![CDATA[continuous-integration]]></category>
            <dc:creator><![CDATA[Jainal Gosaliya]]></dc:creator>
            <pubDate>Sat, 06 Jul 2019 21:23:11 GMT</pubDate>
            <atom:updated>2019-07-06T21:28:33.611Z</atom:updated>
            <content:encoded><![CDATA[<p>We all have used Continuous Integration with our Version Control System but ever wondered we can also host a Competetive Coding Competition on Travis-CI and use it like Hackerearth or Hackerrank!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-EytWOc_rUlt2px454Sj5A.png" /></figure><p><strong>So How Does it work?</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*AOnakSb2KMDiC6D3poTETg.png" /></figure><p>So the Above Flow Gives you a Basic Info of the whole Workflow. But wait this ain’t any informant Blog Post, consider this a step by step guide to deploy your Own Custom Competetive Coding Event on Travis and GitHub!</p><h3>Step- 1</h3><p>For Reference, I have already Created a GitHub repository with all the necessary codes and Travis-Config File. Don’t worry at the end of the Blog Post you will be able to Deploy Your own.</p><ul><li>Git Clone this Repository</li></ul><p><a href="https://github.com/Club-DevBytes/Clash-of-Coders-in-C-Lang">Club-DevBytes/Clash-of-Coders-in-C-Lang</a></p><ul><li>You will see <strong>.travis.yml file.</strong></li><li>You will see a <strong>scripts folder</strong></li><li>These 2 Things are the Heart Here ❤</li></ul><h4>Prerequisites:</h4><ul><li>Create a DropBox App from the Following</li></ul><blockquote><a href="https://www.dropbox.com/developers/apps?_tk=pilot_lp&amp;_ad=topbar4&amp;_camp=myapps">https://www.dropbox.com/developers/apps_tk=pilot_lp&amp;_ad=topbar4&amp;_camp=myapps</a></blockquote><p>After you Create your Dropbox App click on Generate Access token and Copy it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/782/1*vLvuPuX5n-klKMConAXQug.png" /></figure><p>Open The Scripts Folder and open dropbox_uploader.sh file and move to the <strong>line number- 1548 </strong>and add your access token there.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/612/1*7JR2qVbrTlAx3JI6UZvwNg.png" /><figcaption>Add your access token here.</figcaption></figure><p>Open DropBox and Create a Cases folder and upload 6 files</p><ul><li>input.txt, input1.txt, input2.txt</li><li>output.txt, output1.txt, output2.txt</li></ul><p>These will be the Test case that you upload on Hackerearth or any other coding platforms (Here I considered 3 test cases you can change that if you want)</p><p>I recommend you look at this repository where I got the dropbox_uploader.sh code for reference and Usage.</p><p><a href="https://github.com/andreafabrizi/Dropbox-Uploader">andreafabrizi/Dropbox-Uploader</a></p><p>Once all these setups are done we can write our program of Competetive Coding Coding. Here I have taken a Sample mid-level question — Question can be found in the repository README.md and the solution is in main.c.</p><h3>Step-2</h3><p>Lets Head in understanding the Code!!</p><p>This is our Travis build file and is quite simple and self-explanatory.</p><ul><li>First I am making our dropbox_uploader.sh file executable using <br><strong>chmod +x </strong>command.</li><li>Then I am downloading my Input files with our dropbox uploader</li><li>And compiling our main.c with clang</li><li>And then I am doing this :<br> ./sample_program &lt; input.txt &gt; stored_output.txt</li><li>What it does is it takes input from input.txt and stores output in output.txt It’s that simple 😉</li><li>After that, I am uploading the stored_output.txt to Dropbox</li><li>In the Python section basically, I am downloading output.txt and stored_output.txt files.</li><li>Now before we move forward let’s open our <strong><em>scripts folder</em></strong><em> and</em> inside it open<em> </em><strong><em>test_cases_checker.py</em></strong></li><li>So if you are familiar with python than you will find this quite easy to understand that what I am doing is opening output.txt files and adding it to python list and also adding stored_ouput.txt and adding it to a python list</li><li>Then I am basically checking if each element of both these lists are same or not</li><li>If they are same then I will print</li><li>Test case 0: Passed<br>Test case 1: Passed<br>Test case 2: Passed</li><li>If any of the Test Cases fail then I will raise an error and hence build will fail on Travis</li><li>And After that in our travis.yml file, I am Basically deleting our stored_output.txt files from Dropbox for non-test case duplicity reasons for future assessments.</li><li>That’s all this is all that is required for our building a Competetive Code Checker System for using it with Travis and GitHub.</li></ul><h3>Step 3:</h3><ul><li>So let’s start using this Project you can either Fork my repository or you can create your own and push all the code to GitHub.</li><li>After that Open Travis CI Website: <a href="https://travis-ci.org/">https://travis-ci.org</a> and sign in with GitHub.</li><li>After that hover on profile Icon and click on settings.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/693/1*ju5tc3jRuJcVjWXqEqfKFw.png" /></figure><ul><li>After that, you will see your GitHub Repository list and find the one you pushed all your code and turn on the switch beside the repository name.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/890/1*401IxOLcHvkQalna3-mdjw.png" /></figure><ul><li>Click in more option- trigger build and trigger custom build and this is what you will see.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Ol07UDYLKsbthE-n-jT5qw.png" /></figure><ul><li>Now speedily click on cancel job of python because we need to run python file after we compile our main.c program.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*oAFYXb1hEzfN2DmJJao9lg.png" /></figure><ul><li>Once The C job of Travis is compiled perfectly then restart the python job and see that if all the test cases are compiled or not?</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bI8vKjiK0EhaZjQwJgLMYg.png" /><figcaption>You can see that all test cases were passed by the code!</figcaption></figure><p>And done 😎😊that&#39;s how you just made your own competitive coding platform and isn&#39;t it awesome 🤷‍♂️ ?</p><p>If you loved or liked my small experiment make sure you hit that <br>👏 Clap Button and also don&#39;t forget to follow me on twitter.</p><p><a href="https://twitter.com/jainal_gosaliya">Jainal Gosaliya (@jainal_gosaliya) | Twitter</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d2c1e2b0042f" width="1" height="1" alt=""><hr><p><a href="https://medium.com/club-devbytes/competitive-coding-using-travis-ci-d2c1e2b0042f">Competitive Coding using Travis-CI</a> was originally published in <a href="https://medium.com/club-devbytes">Club DevBytes</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to use V.S Code like a pro?]]></title>
            <link>https://medium.com/club-devbytes/how-to-use-v-s-code-like-a-pro-fb030dfc9a72?source=rss-f011d9c738f4------2</link>
            <guid isPermaLink="false">https://medium.com/p/fb030dfc9a72</guid>
            <category><![CDATA[microsoft]]></category>
            <category><![CDATA[vscode]]></category>
            <category><![CDATA[coding]]></category>
            <category><![CDATA[editor]]></category>
            <category><![CDATA[productivity]]></category>
            <dc:creator><![CDATA[Jainal Gosaliya]]></dc:creator>
            <pubDate>Thu, 03 Jan 2019 11:38:26 GMT</pubDate>
            <atom:updated>2023-04-02T01:23:51.035Z</atom:updated>
            <content:encoded><![CDATA[<h3>How to use VS Code like a pro?</h3><p>This is a Kick Starter for all the newbies who would like to use V.S Code like a pro, also to all those experienced developers to increase their productivity.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/850/1*P7lknJxmmKQc6b_VkCATtQ.jpeg" /></figure><p>So I will divide this post into what I call segments, continue reading down to get more info.</p><h4>1. How to open vs code easily and managing efficient workflow?</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*p-Cd19fvR_fhgb1szTjLaA.gif" /><figcaption>As u can see the easiest way to open VS Code to your projects’ directory is via terminal.</figcaption></figure><p>Just go to the projects directory via<em> </em><strong><em>cd</em></strong><em> command</em> and type in<strong> code .<br></strong>So this will open up the project folder inside V.S code.</p><pre>$ code .</pre><p>Another ninja technique is for all the terminal lovers like me who like to open files via terminal. So there is a way to open files directly inside vs code all via terminal and here is how u do it!</p><pre>$ code file_name.extension</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*9CEqcmRUqQCboDHEkkdwUw.gif" /><figcaption>By this, u can directly open files via command line.</figcaption></figure><p>Another hack is to compare the code of 2 files directly and all via command line.<br>Here is how u do it…..</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*5dWCXMEE318arCDnNAp3QQ.gif" /><figcaption>This Compares the code of both files and shows u whats different in both of them.</figcaption></figure><pre>$ code folder_name file1_name.extension file2_name.extension</pre><p><em>So this was all about terminal hacks for vs code. Now let’s move on sailor!!</em></p><h4>2. Extensions + VS Code = ❤️</h4><p>So what are the extensions which u should start using now and boost your code workflow?</p><p>So here is a curated list of all the productive extension to boost your coding performance.</p><h4>1. Code Snippets and Boilerplate</h4><ol><li><strong>Angular 7 Snippets</strong></li></ol><p>There are snippets extensions for say for each Framework and language out there! Here are quite a few notables.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cNp51FImj-ppSPfVHTfBkw.png" /><figcaption>Angular 7 Snippets</figcaption></figure><p>Here is how it works -:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/480/1*625Ph1KOfknU-YEGhkoEqg.gif" /></figure><blockquote>Launch VS Code Quick Open (<em>Ctrl+P</em>), paste the following command, and press enter.</blockquote><pre>ext install Mikael.Angular-BeastCode</pre><p>2. <strong>ES7 React/Redux/GraphQL/React-Native snippets</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HzboQ6ZWdq6wO5fTqwJ_sA.png" /><figcaption>All the code snippets for React, Redux , GraphQL,React-Native</figcaption></figure><p>For the usage, u can get the details from their extension page.</p><blockquote>Launch VS Code Quick Open (<em>Ctrl+P</em>), paste the following command, and press enter.</blockquote><pre>ext install dsznajder.es7-react-js-snippets</pre><p><strong>3. React js Snippet</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NuYVr4JwQg2R4slD7_rqaQ.png" /></figure><p>The demo is here.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8ckPS0i2rzBvhhdQr8QHCQ.gif" /></figure><blockquote>Launch VS Code Quick Open (<em>Ctrl+P</em>), paste the following command, and press enter.</blockquote><pre>ext install xabikos.ReactSnippets</pre><p><strong>4. Html Snippets</strong></p><p>Easy code snippets for HTML.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Yxisnzi4SN5Z_SxVbCboFA.png" /></figure><p>The demo is here.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/862/1*FQeHHN7E5eDgRuq9Jc3uyg.gif" /></figure><blockquote>Launch VS Code Quick Open (<em>Ctrl+P</em>), paste the following command, and press enter.</blockquote><pre>ext install abusaidm.html-snippets</pre><p><strong>5. C/C++ Code Snippets</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BICcXoo12q7BF5TPGH7Uqg.png" /></figure><blockquote>Launch VS Code Quick Open (<em>Ctrl+P</em>), paste the following command, and press enter.</blockquote><pre>ext install hars.CppSnippets</pre><p>So those were some few notables code snippets but u can find snippets for any language or framework out there, JUST SEARCH IT ON!</p><h4>2. Code Runner</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OihFwE8o9iQHYZkEcc_y4Q.png" /></figure><blockquote>Code runner allows u to run code of many popular languages such as <strong>C, C++, Java, JavaScript, PHP, Python, Perl, Perl 6, Ruby, Go, Lua, Groovy, PowerShell, BAT/CMD, BASH/SH, F# Script, F# (.NET Core), C# Script, C# (.NET Core), VBScript, TypeScript, CoffeeScript, Scala, Swift, Julia, Crystal, OCaml Script, R, AppleScript, Elixir, Visual Basic .NET, Clojure, Haxe, Objective-C, Rust, Racket, AutoHotkey, AutoIt, Kotlin, Dart, Free Pascal, Haskell, Nim, D.<br>U can run code by clicking here </strong>👇</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*IQnOHN6S8VqSG1DC8ULOBg.png" /><figcaption>Clicking here will compile your code and will run the program.</figcaption></figure><p>Or u can try to add a hotkey for the same but I will come to that part later in my hotkeys segment.</p><blockquote>Launch VS Code Quick Open (<em>Ctrl+P</em>), paste the following command, and press enter.</blockquote><pre>ext install formulahendry.code-runner</pre><h4>3. Firebase Explorer</h4><p>So here is a quite handy extension to open your firebase projects right in V.S code.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*l_5GrH4GdevAMAz-PuOn3Q.png" /></figure><p>Here is how it looks.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/435/1*FM5NV1oUnzNBBXevaHpx3g.png" /></figure><blockquote>Launch VS Code Quick Open (<em>Ctrl+P</em>), paste the following command, and press enter</blockquote><pre>ext install jsayol.firebase-explorer</pre><h4>4. Markdown Preview Enhanced</h4><p>Preview markdown right inside VS code.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NumiGlzffGTMPwzs0yTX0A.png" /></figure><blockquote>Launch VS Code Quick Open (<em>Ctrl+P</em>), paste the following command, and press enter</blockquote><pre>ext install shd101wyy.markdown-preview-enhanced</pre><h4>5. Git Lens</h4><p>GitLens <strong>supercharges</strong> the Git capabilities built into Visual Studio Code. It helps you to <strong>visualize code authorship</strong> at a glance via Git blame annotations and code lens, <strong>seamlessly navigate and explore </strong>Git repositories, <strong>gain valuable insights</strong> via powerful comparison commands, and so much more</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tdicF-6J9fDGVL8r8gzpwQ.png" /></figure><blockquote>Launch VS Code Quick Open (<em>Ctrl+P</em>), paste the following command, and press enter</blockquote><pre>ext install eamodio.gitlens</pre><h4>6. Prettier — Code formatter</h4><p>Prettier formats all JavaScript / TypeScript / CSS easily using Keyboard shortcuts which can be founded out on its extensions page.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YDh7HK-H01RAU3TTxykh_Q.png" /></figure><blockquote>Launch VS Code Quick Open (<em>Ctrl+P</em>), paste the following command, and press enter</blockquote><pre>ext install esbenp.prettier-vscode</pre><h4>7. ES LINT</h4><p>How about making your JS code error-free and bug-free if u are using es lint in your java scripts components then you need this ES lint extension.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2M5ECWl9PkfzkpNIQj6yhQ.png" /></figure><blockquote>Launch VS Code Quick Open (<em>Ctrl+P</em>), paste the following command, and press enter</blockquote><pre>ext install dbaeumer.vscode-eslint</pre><h4>8. Debugger for Chrome</h4><p>Debug your JavaScript code in the Chrome browser or any other target that supports the Chrome Debugger protocol.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BR5qmUodlwz2tMFDPE17EQ.png" /></figure><p>The demo is here.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pTBUYCONYSNF3MxDrWcpkQ.gif" /></figure><blockquote>Launch VS Code Quick Open (<em>Ctrl+P</em>), paste the following command, and press enter</blockquote><pre>ext install msjsdiag.debugger-for-chrome</pre><h4>9. Live Share</h4><p>Live share is the best group project extension so far. Live share allows to edit anyone’s code remotely in real time. It’s the google docs of VS code.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pvinujuhUsUaOROi6d_fcw.png" /></figure><blockquote>Launch VS Code Quick Open (<em>Ctrl+P</em>), paste the following command, and press enter</blockquote><pre>ext install MS-vsliveshare.vsliveshare</pre><p>You also would want to install the VS Live Share Extension Pack for enabling the integrated voice calling feature.</p><p><strong>VS Live Share Extension Pack</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mBvFz-lS8Vek0ss3d2mW5Q.png" /></figure><blockquote>Launch VS Code Quick Open (<em>Ctrl+P</em>), paste the following command, and press enter</blockquote><pre>ext install MS-vsliveshare.vsliveshare-pack</pre><h4>10. Bracket Pair Colorizers</h4><p>Another cool and handy extension is Bracket Pair Colorizer. It allows us to colorize brackets to easily differentiate and identify the code blocks.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3OkPMNR1yLTn2yJ-GiVqjg.png" /></figure><p>Here is how it looks.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/625/1*Mc7P11ekmFL7irjflGkMIg.png" /></figure><blockquote>Launch VS Code Quick Open (<em>Ctrl+P</em>), paste the following command, and press enter</blockquote><pre>ext install CoenraadS.bracket-pair-colorizer</pre><h4>11. Java Extension pack</h4><p>If you are a Java developer like me then u are gonna love this extension.<br>This extension include -:<br>📦 Language Support for Java™ by Red Hat<br>📦 Debugger for Java<br>📦 Java Test Runner<br>📦 Maven Project Explorer<br>📦 Java Dependency Viewer</p><p>Which are the all u need for compiling and running java files.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9S0pX_hzLMslI69dKd9WsQ.png" /></figure><blockquote>Launch VS Code Quick Open (<em>Ctrl+P</em>), paste the following command, and press enter</blockquote><pre>ext install vscjava.vscode-java-pack</pre><h4>12. Auto Close Tag</h4><p>This is a must-have web dev extension. It auto closes open tags of HTML,XML, PHP, Vue, JavaScript, TypeScript, JSX, TSX languages.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uHrbBpnO4kIqT2AIFcZ57Q.png" /></figure><p>Demo.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*EbGIozYQA3qS3nXpNtSDeg.gif" /></figure><blockquote>Launch VS Code Quick Open (<em>Ctrl+P</em>), paste the following command, and press enter</blockquote><pre>ext install formulahendry.auto-close-tag</pre><h4>13. Auto Rename Tag</h4><p>Auto rename paired HTML/XML tags. Check demo for more info.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tyvshBtDo61V3auEF81AUw.png" /></figure><p>Demo.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ME0oAmIJdO6zaaYwL1DPwA.gif" /></figure><blockquote>Launch VS Code Quick Open (<em>Ctrl+P</em>), paste the following command, and press enter</blockquote><pre>ext install formulahendry.auto-rename-tag</pre><h4>14. Live Server</h4><p>How about an extension which shows you the real-time output of your web projects on your favorite browser. Well, live server gives you the power to do that.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nwShvnQMHyx42MsDxEmoGg.png" /></figure><p>Demo.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/896/1*CfYU3dAoc-39eAJf2hgb3A.gif" /></figure><blockquote>Launch VS Code Quick Open (<em>Ctrl+P</em>), paste the following command, and press enter</blockquote><pre>ext install ritwickdey.LiveServer</pre><h4>15. Code Spell Checker</h4><p>Real-Time Spell checker of your code for all the variable spell check and function spell checker.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pMcJxNIVESlZmnyJ5bnTkw.png" /></figure><p>The Demo is here.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/745/1*3tgHzDUWembdB022yWutug.gif" /></figure><blockquote>Launch VS Code Quick Open (<em>Ctrl+P</em>), paste the following command, and press enter</blockquote><pre>ext install streetsidesoftware.code-spell-checker</pre><h4>16. Arduino</h4><p>How about I tell you that there is an extension for coding, deploying and debugging all the Arduino programs right from vs code! Well here is such extension.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*D--4xlNd3oj1NNJ9za08SQ.png" /></figure><blockquote>Launch VS Code Quick Open (<em>Ctrl+P</em>), paste the following command, and press enter</blockquote><pre>ext install vsciot-vscode.vscode-arduino</pre><h4>17. CMake Tools</h4><p>Powerful extension for managing all builds for the c-make file and required <br>C-make tools.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NWklaM1Jpj5aHQ-0fhkVWA.png" /></figure><blockquote>Launch VS Code Quick Open (<em>Ctrl+P</em>), paste the following command, and press enter</blockquote><pre>ext install vector-of-bool.cmake-tools</pre><h4>18. Flutter</h4><p>If you are in native app development and don’t want to leave VS code than these an extension you all are gonna love. Check out the demo for more info.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8kx7e8qbs9eU-UprDJb-5g.png" /></figure><p>Demo.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/878/1*bYuD5OBj28zyea3-K2bdHQ.gif" /></figure><blockquote>Launch VS Code Quick Open (<em>Ctrl+P</em>), paste the following command, and press enter</blockquote><pre>ext install Dart-Code.flutter</pre><p>You will also dart extension for this so here it is.</p><p><strong>Dart</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bQw1FmYoSbXbQluIDcZbJA.png" /></figure><blockquote>Launch VS Code Quick Open (<em>Ctrl+P</em>), paste the following command, and press enter</blockquote><pre>ext install Dart-Code.dart-code</pre><h4>19. vs code-pdf</h4><p>This extension allows us to directly view pdf files in VS Code.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0P4riUCov_PSWIb9ckF3Iw.png" /></figure><blockquote>Launch VS Code Quick Open (<em>Ctrl+P</em>), paste the following command, and press enter</blockquote><pre>ext install tomoki1207.pdf</pre><h4>20. vscode-spotify</h4><p>How about running Spotify right from VS code. Well, that’s what this extension does!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HqWUVIE1VBDEdjpjZrq5Gg.png" /></figure><blockquote>Launch VS Code Quick Open (<em>Ctrl+P</em>), paste the following command, and press enter</blockquote><pre>ext install shyykoserhiy.vscode-spotify</pre><h4>21. GitHub Pull Requests</h4><p>This extension allows you to review and manage GitHub pull requests in Visual Studio Code. Easily create and deal all the pull requests from VS Code GUI!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*eAxnW260vDaNsAL-UL2Z6Q.png" /></figure><p>The Demo is here.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*srDmPMoySoeuKH6LvUyw6A.gif" /></figure><blockquote>Launch VS Code Quick Open (<em>Ctrl+P</em>), paste the following command, and press enter</blockquote><pre>ext install GitHub.vscode-pull-request-github</pre><h4>22. Settings Sync</h4><p>Well if you are a distro hopper or have multiple machines to work upon but enabling the customizations and tweaks of vs code on all machines are a hassle? then there is extension known as Settings Sync which saves all the extensions you downloaded, all your settings, all your color themes also all your custom changed key bindings to the cloud so that u don’t need to do the process of applying all settings again on different machines. Just download ur settings from the cloud via this extension and you are done!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2cZel-GLURgP2seugfyXmQ.png" /></figure><blockquote>Launch VS Code Quick Open (<em>Ctrl+P</em>), paste the following command, and press enter</blockquote><pre>ext install Shan.code-settings-sync</pre><h4>23. Power Mode</h4><p>This is an attractive, fun to use extension which will make your coding experience more pleasant and fancy.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JUqhPb58QATyue7oLNJsjw.png" /></figure><p>This is how it looks.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/714/1*NL61AbuKIE5mSNY_Sg5wyg.gif" /></figure><p>There are also many variants to try in it.</p><blockquote>Launch VS Code Quick Open (<em>Ctrl+P</em>), paste the following command, and press enter</blockquote><pre>ext install hoovercj.vscode-power-mode</pre><h4>24. Team Chat: for Slack, Discord, Live Share</h4><p>How about slack discord and Live share conversation right into vs code. With this extension, u can!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DKbR4_R_3N72JnmEyTphyg.png" /></figure><blockquote>Launch VS Code Quick Open (<em>Ctrl+P</em>), paste the following command, and press enter</blockquote><pre>ext install karigari.chat</pre><h4>25.Bookmarks</h4><p>Mark lines and jumps to them.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/610/1*VXGElW90NAb-mousqoMRsg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/664/1*0FlGKF5Q5R_p9iC3yZ90eA.png" /></figure><blockquote>Launch VS Code Quick Open (<em>Ctrl+P</em>), paste the following command, and press enter</blockquote><pre>ext install alefragnani.Bookmarks</pre><h4>26. Git History</h4><p>View git log, file or line History.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jejFUQMeqJTvKVsBlsaNfw.png" /></figure><p>The demo is here.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Tzd4QrN1DRne7IIl4CBNjw.gif" /></figure><blockquote>Launch VS Code Quick Open (<em>Ctrl+P</em>), paste the following command, and press enter</blockquote><pre>ext install donjayamanne.githistory</pre><h4>27. Kanban</h4><p>If u have worked with making to-dos with kanban u know how awesome it is. But if u haven’t well kanban is a to-do creating website which creates awesome formatted to-do and much more. But how about I say kanban in vs code!</p><p>Check demo for more info.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yuJI-9UrWtmLvMEaDqLwRw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*22Zb3FPnC6sqZihCObszAA.gif" /></figure><blockquote>Launch VS Code Quick Open (<em>Ctrl+P</em>), paste the following command, and press enter</blockquote><pre>ext install mkloubert.vscode-kanban</pre><h4>28. carbon-now-sh</h4><p>How about showcasing segment of your code, what we do generally is screenshot the segment of the code and share them well that’s old school now try out carbon-now-sh, here is it how!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*k9tJurUM_ApafqB1q8-VhA.gif" /></figure><blockquote>Launch VS Code Quick Open (<em>Ctrl+P</em>), paste the following command, and press enter</blockquote><pre>ext install ericadamski.carbon-now-sh</pre><h4>29. Polacode</h4><p>If u still need to take a screenshot of your code then here is a modern approach!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*68inhBHJIU8jkmVGKzqzEg.gif" /></figure><blockquote>Launch VS Code Quick Open (<em>Ctrl+P</em>), paste the following command, and press enter</blockquote><pre>ext install pnp.polacode</pre><h4>30. Intellisense</h4><p>Lastly are all the intellisense extensions which will give you wide language support such as syntax highlighting, code autocomplete, snippet support and much more. Here are a few to consider.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*Hwg_P3TLw4da-NyLGRP40Q.gif" /><figcaption>These are the intellisense of all programing language. U can download for the one you needed by writing the programing language name and then intellisense.</figcaption></figure><h4>31. Customization- Themes &amp; Icon packs</h4><p>Well first take a look at what VS code has to first offer by default in the name of customization and themes.</p><p>U can view them by opening command palette by:-</p><pre>ctrl + shift + p      or  cmd + shift + p</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mlG2u43C_2f7SGHLMMlnEg.gif" /><figcaption>By default, many themes are there which totally awesome!!</figcaption></figure><p>and then type in themes as shown in above.</p><p>But say you are tired of the built-in themes an want to try out something cool and more productive. So here are a few ones to try it out.</p><blockquote><em>I have collected from multiple sources the best color themes and here is a short and sweet list of the best themes. Also, I will add the links to the sources down below if you want to see them in detail.</em></blockquote><h4>1. Themes</h4><p><strong>1. Andromeda<br></strong>This particular theme is one hell of a gem. If you’re a sucker of dark themes, I’m sure you’ll love this one. A very subtle amount of colors, easy on eyes and supporting most languages. Definitely, check it out.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OLUMipm70y-pfeNj2tn6xA.png" /></figure><blockquote>Launch VS Code Quick Open (<em>Ctrl+P</em>), paste the following command, and press enter</blockquote><pre>ext install EliverLara.andromeda</pre><p>2. <strong>Shades of purple</strong></p><p>⚡ A professional theme with hand-picked &amp; bold shades of purple to go along with your VS Code. A custom VS Code theme with style</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FoWkxqx-sqdZ5akHmdhV9A.png" /></figure><blockquote>Launch VS Code Quick Open (<em>Ctrl+P</em>), paste the following command, and press enter</blockquote><pre>ext install ahmadawais.shades-of-purple</pre><p><strong>3. Material theme</strong></p><p>The most awesome material theme for vs code .</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lPqqDB1U05i2lfBjlrbEmg.png" /></figure><blockquote>Launch VS Code Quick Open (<em>Ctrl+P</em>), paste the following command, and press enter</blockquote><pre>ext install Equinusocio.vsc-material-theme</pre><p><strong>4. Dracula</strong></p><p>Every dark theme list is incomplete without mentioning Darcula theme. Enough said! It’s THE best dark theme out there. Period. The fact that this theme is available not only for VS Code but for <a href="https://draculatheme.com/">other editors</a> as well makes it a goto theme for dark theme enthusiasts for their streamlined workflows.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VXgT4EFpAKtPfXTgi00BqA.png" /></figure><blockquote>Launch VS Code Quick Open (<em>Ctrl+P</em>), paste the following command, and press enter</blockquote><pre>ext install dracula-theme.theme-dracula</pre><p><strong>5. Atom one dark theme</strong></p><p>If you migrated from atom to vs code but loved the looks of atom here is a theme for you.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YM86TuhMyojI1XyoB8-0gA.png" /></figure><blockquote>Launch VS Code Quick Open (<em>Ctrl+P</em>), paste the following command, and press enter</blockquote><pre>ext install akamud.vscode-theme-onedark</pre><p><strong>6. Cobalt2 Theme Official by Wes Bos</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*oyd87OPOHvu5EdLD4JZ-Lg.png" /></figure><blockquote>Launch VS Code Quick Open (<em>Ctrl+P</em>), paste the following command, and press enter</blockquote><pre>ext install wesbos.theme-cobalt2</pre><p><strong>7. Night owl Theme</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*BNso1E9KIL7bIsPl7M_x4A.png" /></figure><blockquote>Launch VS Code Quick Open (<em>Ctrl+P</em>), paste the following command, and press enter</blockquote><pre>ext install sdras.night-owl</pre><p><strong>8. Nord by arcticicestudio</strong></p><p>An arctic, north-bluish clean and elegant Visual Studio Code theme.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*t9LYDydL3JByeOSDeSePvA.png" /></figure><blockquote>Launch VS Code Quick Open (<em>Ctrl+P</em>), paste the following command, and press enter</blockquote><pre>ext install arcticicestudio.nord-visual-studio-code</pre><p>9. <strong>Mno by u29dc<br></strong>Minimal monochrome theme.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ElXa-w5txBM9XprhzJp1dA.png" /></figure><blockquote>Launch VS Code Quick Open (<em>Ctrl+P</em>), paste the following command, and press enter</blockquote><pre>ext install u29dc.mno</pre><p><strong>10. Best light theme bluloco-light</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*XEZKtMEnaXDTGKmTZ7hryg.png" /></figure><blockquote>Launch VS Code Quick Open (<em>Ctrl+P</em>), paste the following command, and press enter</blockquote><pre>ext install uloco.theme-bluloco-light</pre><h4>2. Icon Packs</h4><ol><li><strong>City Lights Icons</strong></li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9O73UWg0mAcmR1X2FPgTVQ.gif" /></figure><blockquote>Launch VS Code Quick Open (<em>Ctrl+P</em>), paste the following command, and press enter</blockquote><pre>ext install Yummygum.city-lights-icon-vsc</pre><p><strong>2. VS Code Icons</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*69vby7KoGBO5D6XDs2vdIg.gif" /></figure><blockquote>Launch VS Code Quick Open (<em>Ctrl+P</em>), paste the following command, and press enter</blockquote><pre>ext install robertohuertasm.vscode-icons</pre><p><strong>3.Seti Icons</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*oSPCbBSpImFco3QfRMp-pA.png" /></figure><blockquote>Launch VS Code Quick Open (<em>Ctrl+P</em>), paste the following command, and press enter</blockquote><pre>ext install qinjia.seti-icons</pre><p><strong>4. Material Icons</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jzkzYJLCeOPa-ytNsp82oA.png" /></figure><blockquote>Launch VS Code Quick Open (<em>Ctrl+P</em>), paste the following command, and press enter</blockquote><pre>ext install PKief.material-icon-theme</pre><h4>3. Shortcuts and Hot Keys.</h4><p>So let’s see what we got here.<br>VS code is all about shortcuts here we have the shortcut to open files directly, u have direct access to open files and close, we have shortcuts open Command Palette, shortcut to go in zen mode etc</p><ol><li><strong>Command Palette</strong></li></ol><p>Access all available commands based on your current context.</p><pre>Keyboard Shortcut: Ctrl+Shift+P</pre><p><strong>2. Default keyboard shortcuts</strong></p><p>All of the commands are in the Command Palette with the associated key binding (if it exists). If you forget a keyboard shortcut, use the Command Palette to help you out.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/754/1*hkc58WQ2gZRWsWJrpTgwEw.png" /></figure><p><strong>3. Keyboard reference sheets</strong></p><p>Download the keyboard shortcut reference sheet for your platform (<a href="https://go.microsoft.com/fwlink/?linkid=832143">macOS</a>, <a href="https://go.microsoft.com/fwlink/?linkid=832145">Windows</a>, <a href="https://go.microsoft.com/fwlink/?linkid=832144">Linux</a>).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/996/1*AWLaiwFBKGXywj8RUg6M-w.png" /></figure><p><strong>4. Quick Open</strong></p><pre>Keyboard Shortcut: Ctrl+P</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kZ4Cl5LDR3UnxIxzLEYxeA.gif" /></figure><p><strong>5. Errors and warnings</strong></p><p>Quickly jump to errors and warnings in the project.</p><pre>Keyboard Shortcut: Ctrl+Shift+M</pre><p>Cycle through errors with: F8 or Shift+F8</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*i-TD9eysJ1hkMAGukeAVTA.gif" /></figure><p><strong>6. Split Views</strong></p><p>If you have a very big code and you want to compare segments of same<br>code side by side well you can- Just press shortcut ctrl + \</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*Xd_-03mokKD-buX6TKTkvA.gif" /></figure><p><strong>7. Side bars</strong></p><p>Press ctrl + b to open and close side bars</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*CWJt5Tm6ZWLwkEx9kH6tlg.gif" /></figure><p><strong>8. Zen mode</strong></p><p>U can enter in zen mode by pressing ctrl + z</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*BdQHjysYNAaIvaArOi-oyA.gif" /></figure><p><em>Sometimes its set to something else just search zen mode in key preferences and you will get the key binds.</em></p><p><strong>9</strong>.<strong> Type same lines with writing once!</strong></p><p>This a handy shortcut which might help us many times.</p><p>u can press shift + alt + up / down</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*_eS0RLb08GuxKpMcrOeMjQ.gif" /></figure><p><strong>10. Find in all files</strong></p><p>Find in all files allows you to search the code in all files. And also you can always press ctrl + f to find in selected files.</p><p>u can press ctrl + shift + f</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*5yFRWnjEmWsNIKphXAK1YA.gif" /></figure><p>So that was all the required default keyboard shortcuts. But if you would additionally want your custom shortcuts created, you can and here is how?</p><p>This will open up a tab showing all the shortcuts with what action they perform and you can then either search for a specific action and then change it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IlG3H4CVjFw7lxnyuqFpKA.png" /></figure><p>Like for example I have a shortcut for extension code runner and the shortcut is for compiling code by just pressing alt + shift + r and it compiles the code and displays the output.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*I0RN06vTc0xvAibl4UgkVw.gif" /><figcaption>As soon as I press Alt + shift + r the code gets compiled. [ Custom key binds ]</figcaption></figure><p>Moreover, I have also set up the following key binds u can download the keybinds.json file .</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9d5fe63e9dfb97a9c892e9397fb968ab/href">https://medium.com/media/9d5fe63e9dfb97a9c892e9397fb968ab/href</a></iframe><p>There are key binds for git commit +git push + git pull; also to create a new file ; new folder …</p><h4>4. Using VS Code Functionalities</h4><ol><li><strong>Rename All Occurrences<br></strong>If you select a variable/method and hit <strong>F2</strong>, you can edit the name and it will change every instance of that variable’s name throughout the entire current working project.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/670/1*pZJI_KZP64Uowjk4UQXTRA.png" /></figure><p>If you only want to change within the current file, use the <strong>Command + F2 (on Mac)</strong> or <strong>Ctrl + F2 (on Windows) </strong>keyboard shortcut and VS Code will spawn a cursor at every instance throughout the current file.</p><p><strong>2. Go to Definition</strong></p><p>You could spend several minutes searching for the right file, or you could press <strong>Command (on Mac)</strong> or <strong>Ctrl (on Windows)</strong> key and click the variable/method with your mouse. VS Code will take you to it’s definition right away.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/670/1*M0F0oaB_3k--jamh50u3oA.png" /></figure><p>Or you could just hover your cursor over the variable/method along with pressing the <strong>Command (on Mac)</strong> or <strong>Ctrl (on Windows)</strong> key, it will shows you the definition right in line where your cursor is.</p><p><strong>3. Edit Multiple Lines at once</strong></p><p>f you ever need to insert or delete multiple instances of text throughout a document, all you have to do is create <strong>multiple cursors</strong>. You can do this by holding down <strong>Option (on Mac) </strong>or<strong> Alt (on Windows) </strong>and clicking anywhere in the text. Every click creates a new cursor.</p><p>This is particularly useful for things like HTML, where you might want to add many instances of the same class or change the format of several hyperlinks.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/670/1*qfruKm_9jEFTt1SxMeIRbg.png" /></figure><p><strong>4. Debugger</strong></p><p>The debugger deserves a video all to iteself — thankfully, VS Code has already made one of those.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2F6cOsxaNC06c%3Ffeature%3Doembed&amp;url=http%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3D6cOsxaNC06c&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2F6cOsxaNC06c%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/f5cc6065c2bd9f84906b447909305f24/href">https://medium.com/media/f5cc6065c2bd9f84906b447909305f24/href</a></iframe><p><strong>5</strong>. <strong>Peek Types and Show References</strong></p><p>Not sure what some class or interface is all about? You can find the <em>peek types</em> option by highlighting and right-clicking an interface.</p><p>If you happen to be looking at an interface and want to know where it is being used, do the same thing, but click on <em>show references</em>. This will provide you with a list of all files using that code.</p><p><strong>6. Multi cursor selection</strong></p><pre>Mac: opt+cmd+up or opt+cmd+down</pre><pre>Windows: ctrl+alt+up or ctrl+alt+down</pre><pre>Linux: alt+shift+up or alt+shift+down</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/210/1*6Z9JklenHA6ASeBc3arOkA.gif" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/574/1*b2rAqSLJSWNY6trbGnbO1Q.gif" /></figure><p>Add more cursors to current selection.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/574/1*b2rAqSLJSWNY6trbGnbO1Q.gif" /></figure><p><strong>7. Join line</strong></p><pre>Mac: ctrl+j</pre><pre>Windows / Linux: Not bound by default. Open Keyboard Shortcuts and bind editor.action.joinLines to a shortcut of your choice.</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/896/1*UyDM7R7QbTWMiUdWIERoqw.gif" /></figure><p><strong>8. Navigate to a specific line</strong></p><pre>Mac: ctrl+g or cmd+p, :</pre><pre>Windows / Linux: ctrl+g</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1020/1*Nz2DTqFoHsKi4oWHobjYGw.gif" /></figure><p><strong>9. Move line up and down</strong></p><pre>Mac: opt+up or opt+down</pre><pre>Windows / Linux: alt+up or alt+down</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*EzfMDUjdGDUNr_ylFAl1gA.gif" /></figure><p><strong>10. Whole document format</strong></p><pre>Windows / Linux: shift+alt+f</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/778/1*zV00HsAS4xJhi499BJWFug.gif" /></figure><p><strong>11. Find All References</strong></p><p>Select a symbol then type shift+f12. Alternatively, you can use the context menu.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HN7qBIJ7Lo0U7umUmUV6Iw.gif" /></figure><p><strong>12. Rename Symbol</strong></p><p>Select a symbol then type f2. Alternatively, you can use the context menu.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1A2IwTGn8bysVxI7jXBY5g.gif" /></figure><h3>5. Tweaking Vs Code — settings.json</h3><p><em>Well, you can do multiple things via editing settings.json file but make sure what you are doing. You can set compiler paths for programming languages, you can edit workspace settings, you can also edit font family, font colors, lint settings and much more.</em></p><p>Here is how you can open settings.json file</p><p><strong>Settings File Locations</strong></p><ul><li><strong>Windows</strong> %APPDATA%\Code\User\settings.json</li><li><strong>Mac</strong> $HOME/Library/Application Support/Code/User/settings.json</li><li><strong>Linux</strong> $HOME/.config/Code/User/settings.json</li></ul><p>The menu command <strong>File</strong> &gt; <strong>Preferences</strong> &gt; <strong>Settings</strong> (<strong>Code</strong> &gt; <strong>Preferences</strong> &gt; <strong>Settings</strong> on Mac) provides entry to configure user and workspace settings. You are provided with a list of Default Settings. Copy any setting that you want to change to the appropriate settings.json file. The tabs on the right let you switch quickly between the user and workspace settings files.</p><p>You can also open the user and workspace settings from the <strong>Command Palette</strong>(kb(workbench.action.showCommands)) with <strong>Preferences: Open User Settings</strong> and <strong>Preferences: Open Workspace Settings</strong> or use the keyboard shortcut (kb(workbench.action.openGlobalSettings)).</p><p>In the example below, we disabled line numbers in the editor and configured line wrapping to wrap automatically based on the size of the editor.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*V-vNRsAFfTzl4NdClM6DCw.png" /></figure><p>Changes to settings are reloaded by VS Code after the modified settings.json file is saved.</p><blockquote><strong><em>Note:</em></strong><em> Workspace settings are useful for sharing project specific settings across a team.</em></blockquote><p>This was some basic info about settings.json file, you can find detailed info here :-</p><ol><li><a href="https://vscode.readthedocs.io/en/latest/getstarted/settings/">link 1</a></li><li><a href="https://code.visualstudio.com/docs/getstarted/settings">link 2</a></li></ol><h3>Conclusion: Visual Studio Code can do that -:</h3><p>Visual Studio Code is a good Editor, that can adapt to many languages and technologies out there, and discovering these little helpers can sometimes take time.<br>I hope my post can help you increase your productivity and help you boost your coding skills.</p><p><em>NOTE: If i had missed anything pls free to comment down below</em></p><h4>Thanks for reading! If you find this helpful don’t forget to leave some claps 👏🏻 and don’t forget to share this with your friends and followers! If you have some tips regarding VS Code, feel free to comment or you can tweet to me at as well- <a href="https://twitter.com/jainal_gosaliya">jainal_gosaliya</a></h4><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fb030dfc9a72" width="1" height="1" alt=""><hr><p><a href="https://medium.com/club-devbytes/how-to-use-v-s-code-like-a-pro-fb030dfc9a72">How to use V.S Code like a pro?</a> was originally published in <a href="https://medium.com/club-devbytes">Club DevBytes</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>