<?xml version="1.0" encoding="UTF-8"?><rss version="2.0" xmlns:content="http://purl.org/rss/1.0/modules/content/"><channel><title>Rafe Uddaraj, articles</title><description>Deep dives into how software systems work: databases, distributed systems, and architecture.</description><link>https://www.rafeuddaraj.me/</link><language>en-us</language><item><title>Engineering Roadmap: Why &apos;Exactly Once&apos; Delivery Is Mostly a Lie</title><link>https://www.rafeuddaraj.me/blog/exactly-once-delivery-myth-distributed-systems/</link><guid isPermaLink="true">https://www.rafeuddaraj.me/blog/exactly-once-delivery-myth-distributed-systems/</guid><description>A complete engineering guide on why exactly-once delivery is mathematically impossible at the network level, and how to build effectively-once architectures in production using idempotency, transactional outbox, and inbox patterns.</description><pubDate>Tue, 08 Sep 2026 00:00:00 GMT</pubDate><content:encoded>&lt;p&gt;Imagine a real-world production incident. You built a payment API for an e-commerce platform. When a user clicks the checkout button, your payment service processes the request and calls an external payment gateway like Stripe or PayPal. During system design review, the architecture flow looked clean and predictable.&lt;/p&gt;
&lt;p&gt;Then, at 3 AM, your PagerDuty alert fires. Customer support reports that hundreds of users were charged twice for the exact same order on their credit cards.&lt;/p&gt;
&lt;p&gt;You open your production logs to trace what happened behind the scenes:&lt;/p&gt;
&lt;ol&gt;
&lt;li&gt;Your Payment Service dispatched an HTTP POST request to the payment gateway: &lt;code&gt;Charge $100&lt;/code&gt;.&lt;/li&gt;
&lt;li&gt;The payment gateway processed the charge successfully and debited &lt;code&gt;$100&lt;/code&gt; from the user&apos;s card.&lt;/li&gt;
&lt;li&gt;Just one millisecond before the &lt;code&gt;200 OK&lt;/code&gt; response packet reached your server, an intermediate network link dropped, causing a &lt;code&gt;TCP Socket Timeout&lt;/code&gt; on your application server.&lt;/li&gt;
&lt;li&gt;From the perspective of your Payment Service, it cannot determine whether the money was charged or if the request dropped before reaching the gateway.&lt;/li&gt;
&lt;li&gt;To keep the service fault-tolerant, an automatic retry mechanism kicked in and dispatched an identical retry request.&lt;/li&gt;
&lt;li&gt;The payment gateway received the second request as a new transaction and charged the user another &lt;code&gt;$100&lt;/code&gt;.&lt;/li&gt;
&lt;/ol&gt;
&lt;figure&gt;&lt;img src=&quot;https://raw.githubusercontent.com/rafeuddaraj/rafes-blog-assets/refs/heads/exactly-once-delivery-myth-distributed-systems/assets/payment-double-charge.svg&quot; alt=&quot;Double Charge Production Incident&quot; loading=&quot;lazy&quot; decoding=&quot;async&quot; width=&quot;800&quot; height=&quot;350&quot;&gt;&lt;figcaption&gt;Double Charge Production Incident&lt;/figcaption&gt;&lt;/figure&gt;
&lt;p&gt;A user was billed &lt;code&gt;$200&lt;/code&gt; instead of &lt;code&gt;$100&lt;/code&gt;. This illustrates the classic crisis of &lt;strong&gt;Exactly-Once Delivery&lt;/strong&gt; in distributed systems.&lt;/p&gt;
&lt;p&gt;While an &quot;Exactly-Once&quot; guarantee sounds appealing, achieving it across unreliable networks is mathematically impossible. When engineers migrate from monoliths to microservices, the most common pitfall is treating the network as fully reliable.&lt;/p&gt;
&lt;p&gt;In this deep dive, we explore the low-level mechanics of distributed systems. We examine why network-level exactly-once delivery cannot exist and how senior engineers construct &lt;strong&gt;Effectively-Once&lt;/strong&gt; architectures in production using &lt;strong&gt;Idempotency&lt;/strong&gt;, &lt;strong&gt;Transactional Outbox&lt;/strong&gt;, and &lt;strong&gt;Inbox Patterns&lt;/strong&gt;.&lt;/p&gt;
&lt;hr&gt;
&lt;h2 id=&quot;network-uncertainty-and-the-lost-ack-problem&quot;&gt;Network Uncertainty and The Lost ACK Problem&lt;/h2&gt;
&lt;p&gt;To understand fundamental uncertainty in distributed architectures, we must examine the physical realities of the network layer. Whenever two independent nodes communicate over a network, the intermediate links, switches, routers, and middleboxes are inherently fallible.&lt;/p&gt;
&lt;p&gt;A foundational theorem in computer science, the &lt;strong&gt;Two Generals&apos; Problem&lt;/strong&gt;, mathematically proves that two separate nodes communicating over an unreliable channel can never reach 100% consensus on state using finite messages.&lt;/p&gt;
&lt;p&gt;When a client transmits a request to a server, three distinct failure scenarios can occur from the client&apos;s perspective:&lt;/p&gt;
&lt;ol&gt;
&lt;li&gt;&lt;strong&gt;Request Lost in Transit:&lt;/strong&gt; The request packet drops due to network congestion or routing failure before reaching the server.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Server Crashes Pre-Execution:&lt;/strong&gt; The server receives the packet but crashes (power loss, kernel panic, OOM) before execution completes.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Execution Succeeded but ACK Lost:&lt;/strong&gt; The server receives the request, mutates state in its database, but the acknowledgment (ACK / &lt;code&gt;200 OK&lt;/code&gt;) packet drops on the return path.&lt;/li&gt;
&lt;/ol&gt;
&lt;figure&gt;&lt;img src=&quot;https://raw.githubusercontent.com/rafeuddaraj/rafes-blog-assets/refs/heads/exactly-once-delivery-myth-distributed-systems/assets/network-lost-ack.svg&quot; alt=&quot;The Lost ACK Problem&quot; loading=&quot;lazy&quot; decoding=&quot;async&quot; width=&quot;800&quot; height=&quot;300&quot;&gt;&lt;figcaption&gt;The Lost ACK Problem&lt;/figcaption&gt;&lt;/figure&gt;
&lt;p&gt;The critical challenge is that when the sender encounters a timeout error, it receives identical symptoms (&lt;code&gt;ETIMEDOUT&lt;/code&gt; / &lt;code&gt;ECONNRESET&lt;/code&gt;) across all three distinct scenarios.&lt;/p&gt;
&lt;p&gt;If the client assumes failure and retransmits, scenario 3 creates a duplicate mutation. If the client assumes success, scenarios 1 and 2 result in silent, permanent data loss.&lt;/p&gt;
&lt;div class=&quot;callout&quot; role=&quot;note&quot; data-type=&quot;note&quot;&gt;
&lt;p class=&quot;callout-title&quot;&gt;The Post Office Analogy&lt;/p&gt;
&lt;p&gt;If you send an important letter through the mail and receive no response, you cannot determine if the postal carrier lost the envelope or if the recipient received it and simply forgot to reply. To guarantee receipt, you are forced to send a duplicate letter.&lt;/p&gt;
&lt;/div&gt;
&lt;hr&gt;
&lt;h2 id=&quot;three-delivery-semantics-at-most-once-at-least-once-exactly-once&quot;&gt;Three Delivery Semantics: At-Most-Once, At-Least-Once, Exactly-Once&lt;/h2&gt;
&lt;p&gt;To navigate network uncertainty, distributed systems classify message transport into three distinct operational models:&lt;/p&gt;
&lt;figure&gt;&lt;img src=&quot;https://raw.githubusercontent.com/rafeuddaraj/rafes-blog-assets/refs/heads/exactly-once-delivery-myth-distributed-systems/assets/delivery-semantics.svg&quot; alt=&quot;Delivery Semantics Comparison&quot; loading=&quot;lazy&quot; decoding=&quot;async&quot; width=&quot;800&quot; height=&quot;350&quot;&gt;&lt;figcaption&gt;Delivery Semantics Comparison&lt;/figcaption&gt;&lt;/figure&gt;
&lt;h3 id=&quot;1-at-most-once-0-or-1-delivery&quot;&gt;1. At-Most-Once (0 or 1 delivery)&lt;/h3&gt;
&lt;p&gt;The system transmits a message once. If an error or timeout occurs, it never retries (Fire and Forget).&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;Advantage:&lt;/strong&gt; Guarantees zero duplicate processing.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Risk:&lt;/strong&gt; Any network hiccup leads to permanent data loss.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Use Case:&lt;/strong&gt; High-throughput telemetry, real-time metrics, video streaming packets, and high-frequency IoT sensors where dropped samples are acceptable.&lt;/li&gt;
&lt;/ul&gt;
&lt;h3 id=&quot;2-at-least-once-1-or-more-deliveries&quot;&gt;2. At-Least-Once (1 or more deliveries)&lt;/h3&gt;
&lt;p&gt;The sender repeatedly retransmits the message until it receives explicit acknowledgment from the receiver.&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;Advantage:&lt;/strong&gt; Message loss rate drops to near zero.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Risk:&lt;/strong&gt; Whenever an ACK packet drops, the receiver receives duplicate messages.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Use Case:&lt;/strong&gt; Financial ledgers, order workflows, and messaging systems like Apache Kafka, RabbitMQ, and AWS SQS by default.&lt;/li&gt;
&lt;/ul&gt;
&lt;h3 id=&quot;3-exactly-once-exactly-1-delivery&quot;&gt;3. Exactly-Once (Exactly 1 delivery)&lt;/h3&gt;
&lt;p&gt;A theoretical model where a message travels across the network exactly once and executes business logic exactly once. At the pure network transport layer, this is physically impossible. However, we can simulate an &lt;strong&gt;Effectively-Once&lt;/strong&gt; model by combining At-Least-Once transport with application and storage-level deduplication.&lt;/p&gt;
&lt;hr&gt;
&lt;h2 id=&quot;the-core-misconception-delivery-vs-processing&quot;&gt;The Core Misconception: Delivery vs. Processing&lt;/h2&gt;
&lt;p&gt;A common architectural mistake is conflating message delivery with message execution:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;Delivery (Transport Layer):&lt;/strong&gt; Transferring bytes from the broker or sender across a socket to the consumer.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Processing (Application Layer):&lt;/strong&gt; Parsing the payload and executing domain logic in memory.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Side Effect (Persistence / External Layer):&lt;/strong&gt; Committing state changes, such as mutating database rows, creating charges on Stripe, or dispatching emails.&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;You cannot prevent duplicate packet delivery across an unreliable network. However, if you design your execution layer so that receiving the same payload ten times produces exactly one side effect, the system behaves as &lt;strong&gt;Effectively-Once&lt;/strong&gt; to your users.&lt;/p&gt;
&lt;hr&gt;
&lt;h2 id=&quot;the-real-enemy-is-duplicate-side-effects-not-duplicate-messages&quot;&gt;The Real Enemy is Duplicate Side Effects, Not Duplicate Messages&lt;/h2&gt;
&lt;p&gt;Receiving a duplicate network frame causes minimal harm. Catastrophic failures occur when duplicate payloads trigger duplicate side effects:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;Charging a user&apos;s credit card twice&lt;/li&gt;
&lt;li&gt;Decrementing warehouse inventory twice&lt;/li&gt;
&lt;li&gt;Inserting duplicate database records&lt;/li&gt;
&lt;li&gt;Dispatching multiple confirmation notifications&lt;/li&gt;
&lt;/ul&gt;
&lt;figure&gt;&lt;img src=&quot;https://raw.githubusercontent.com/rafeuddaraj/rafes-blog-assets/refs/heads/exactly-once-delivery-myth-distributed-systems/assets/duplicate-side-effects.svg&quot; alt=&quot;The Real Enemy: Duplicate Side Effects&quot; loading=&quot;lazy&quot; decoding=&quot;async&quot; width=&quot;800&quot; height=&quot;400&quot;&gt;&lt;figcaption&gt;The Real Enemy: Duplicate Side Effects&lt;/figcaption&gt;&lt;/figure&gt;
&lt;p&gt;Production architectures must embrace duplicate transport while building strict guards around every persistent side effect.&lt;/p&gt;
&lt;hr&gt;
&lt;h2 id=&quot;idempotency-the-practical-escape-hatch&quot;&gt;Idempotency: The Practical Escape Hatch&lt;/h2&gt;
&lt;p&gt;Idempotency is the primary defensive mechanism against duplicate execution.&lt;/p&gt;
&lt;p&gt;In mathematics and computer science, an operation &lt;span class=&quot;katex&quot;&gt;&lt;span class=&quot;katex-html&quot; aria-hidden=&quot;true&quot;&gt;&lt;span class=&quot;base&quot;&gt;&lt;span class=&quot;strut&quot; style=&quot;height:1em;vertical-align:-0.25em;&quot;&gt;&lt;/span&gt;&lt;span class=&quot;mord mathnormal&quot; style=&quot;margin-right:0.1076em;&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;mopen&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mord mathnormal&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;mclose&quot;&gt;)&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/span&gt; is defined as &lt;strong&gt;idempotent&lt;/strong&gt; if applying it multiple times yields the exact same result as applying it once:&lt;/p&gt;
&lt;span class=&quot;katex-display&quot;&gt;&lt;span class=&quot;katex&quot;&gt;&lt;span class=&quot;katex-html&quot; aria-hidden=&quot;true&quot;&gt;&lt;span class=&quot;base&quot;&gt;&lt;span class=&quot;strut&quot; style=&quot;height:1em;vertical-align:-0.25em;&quot;&gt;&lt;/span&gt;&lt;span class=&quot;mord mathnormal&quot; style=&quot;margin-right:0.1076em;&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;mopen&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mord mathnormal&quot; style=&quot;margin-right:0.1076em;&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;mopen&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mord mathnormal&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;mclose&quot;&gt;))&lt;/span&gt;&lt;span class=&quot;mspace&quot; style=&quot;margin-right:0.2778em;&quot;&gt;&lt;/span&gt;&lt;span class=&quot;mrel&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mspace&quot; style=&quot;margin-right:0.2778em;&quot;&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class=&quot;base&quot;&gt;&lt;span class=&quot;strut&quot; style=&quot;height:1em;vertical-align:-0.25em;&quot;&gt;&lt;/span&gt;&lt;span class=&quot;mord mathnormal&quot; style=&quot;margin-right:0.1076em;&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;mopen&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mord mathnormal&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;mclose&quot;&gt;)&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;
&lt;figure&gt;&lt;img src=&quot;https://raw.githubusercontent.com/rafeuddaraj/rafes-blog-assets/refs/heads/exactly-once-delivery-myth-distributed-systems/assets/idempotency-flow.svg&quot; alt=&quot;Idempotency Flow Architecture&quot; loading=&quot;lazy&quot; decoding=&quot;async&quot; width=&quot;800&quot; height=&quot;400&quot;&gt;&lt;figcaption&gt;Idempotency Flow Architecture&lt;/figcaption&gt;&lt;/figure&gt;
&lt;h3 id=&quot;how-idempotency-keys-work-in-practice&quot;&gt;How Idempotency Keys Work in Practice:&lt;/h3&gt;
&lt;ol&gt;
&lt;li&gt;The client generates a unique UUID for the intent and attaches it to the HTTP header: &lt;code&gt;Idempotency-Key: 9b1deb4d-3b7d-4bad-9bdd-2b0d7b3dcb6d&lt;/code&gt;.&lt;/li&gt;
&lt;li&gt;Before running business logic, the server checks the key in a shared persistence layer (e.g., PostgreSQL or Redis).&lt;/li&gt;
&lt;li&gt;If the key exists with status &lt;code&gt;COMPLETED&lt;/code&gt;, the server bypasses execution and immediately returns the cached response.&lt;/li&gt;
&lt;li&gt;If the key is new, the server acquires a lock (&lt;code&gt;IN_PROGRESS&lt;/code&gt;), executes domain logic, persists the result, and transitions status to &lt;code&gt;COMPLETED&lt;/code&gt;.&lt;/li&gt;
&lt;/ol&gt;
&lt;div class=&quot;callout&quot; role=&quot;note&quot; data-type=&quot;tip&quot;&gt;
&lt;p class=&quot;callout-title&quot;&gt;REST Semantics and Idempotency&lt;/p&gt;
&lt;p&gt;In REST API design, &lt;code&gt;GET&lt;/code&gt;, &lt;code&gt;PUT&lt;/code&gt;, and &lt;code&gt;DELETE&lt;/code&gt; verbs are naturally idempotent by specification. Repeating a &lt;code&gt;DELETE /items/42&lt;/code&gt; multiple times leaves the system in the same target state. In contrast, &lt;code&gt;POST&lt;/code&gt; is non-idempotent by default. Production POST endpoints handling billing, fund transfers, or order submission should mandate an &lt;code&gt;Idempotency-Key&lt;/code&gt; header.&lt;/p&gt;
&lt;/div&gt;
&lt;hr&gt;
&lt;h2 id=&quot;database-unique-constraints-and-the-check-then-insert-trap&quot;&gt;Database Unique Constraints and the Check-Then-Insert Trap&lt;/h2&gt;
&lt;p&gt;A naive implementation of idempotency relies on application memory checks:&lt;/p&gt;
&lt;div class=&quot;expressive-code&quot;&gt;&lt;style&gt;.expressive-code{font-family:var(--ec-uiFontFml);font-size:var(--ec-uiFontSize);font-weight:var(--ec-uiFontWg);line-height:var(--ec-uiLineHt);text-size-adjust:none;-webkit-text-size-adjust:none}.expressive-code *:not(:is(svg, svg *)){all:revert;box-sizing:border-box}.expressive-code pre{display:flex;margin:0;padding:0;border:var(--ec-brdWd) solid var(--ec-brdCol);border-radius:calc(var(--ec-brdRad) + var(--ec-brdWd));background:var(--ec-codeBg)}.expressive-code pre:focus-visible{outline:3px solid var(--ec-focusBrd);outline-offset:-3px}.expressive-code pre &gt; code{all:unset;display:block;flex:1 0 100%;padding:var(--ec-codePadBlk) 0;color:var(--ec-codeFg);font-family:var(--ec-codeFontFml);font-size:var(--ec-codeFontSize);font-weight:var(--ec-codeFontWg);line-height:var(--ec-codeLineHt)}.expressive-code pre{overflow-x:auto}.expressive-code pre.wrap .ec-line .code{white-space:pre-wrap;overflow-wrap:break-word;min-width:min(20ch, var(--ecMaxLine, 20ch))}.expressive-code pre.wrap .ec-line .code span.indent{white-space:pre}.expressive-code pre::-webkit-scrollbar,.expressive-code pre::-webkit-scrollbar-track{background-color:inherit;border-radius:calc(var(--ec-brdRad) + var(--ec-brdWd));border-top-left-radius:0;border-top-right-radius:0}.expressive-code pre::-webkit-scrollbar-thumb{background-color:var(--ec-sbThumbCol);border:4px solid transparent;background-clip:content-box;border-radius:10px}.expressive-code pre::-webkit-scrollbar-thumb:hover{background-color:var(--ec-sbThumbHoverCol)}.expressive-code pre::-webkit-scrollbar-corner{background:transparent}.expressive-code .ec-line{direction:ltr;unicode-bidi:isolate;display:grid;grid-template-areas:&apos;gutter code&apos;;grid-template-columns:auto 1fr;position:relative}.expressive-code .ec-line .gutter{grid-area:gutter;color:var(--ec-gtrFg)}.expressive-code .ec-line .gutter &gt; *{pointer-events:none;user-select:none;-webkit-user-select:none}.expressive-code .ec-line .gutter ~ .code{--ecLineBrdCol:var(--ec-gtrBrdCol)}.expressive-code .ec-line.highlight .gutter{color:var(--ec-gtrHlFg)}.expressive-code .ec-line .code{grid-area:code;position:relative;box-sizing:content-box;padding-inline-start:calc(var(--ecIndent, 0ch) + var(--ec-codePadInl) - var(--ecGtrBrdWd));padding-inline-end:var(--ec-codePadInl);text-indent:calc(var(--ecIndent, 0ch) * -1)}.expressive-code .ec-line .code::before,.expressive-code .ec-line .code::after,.expressive-code .ec-line .code :where(*){text-indent:0}.expressive-code .ec-line .code{--ecGtrBrdWd:var(--ec-gtrBrdWd);border-inline-start:var(--ecGtrBrdWd) solid var(--ecLineBrdCol, transparent)}.expressive-code .sr-only{position:absolute;width:1px;height:1px;padding:0;margin:-1px;overflow:hidden;clip:rect(0, 0, 0, 0);white-space:nowrap;border-width:0}.expressive-code .ec-line.mark{--tmLineBgCol:var(--ec-tm-markBg)}.expressive-code .ec-line.mark .code{--ecLineBrdCol:var(--ec-tm-markBrdCol)}.expressive-code .ec-line.ins{--tmLineBgCol:var(--ec-tm-insBg);--tmLabel:var(--ec-tm-insDiffIndContent)}.expressive-code .ec-line.ins .code{--ecLineBrdCol:var(--ec-tm-insBrdCol)}.expressive-code .ec-line.ins .code::before{color:var(--ec-tm-insDiffIndCol)}.expressive-code .ec-line.del{--tmLineBgCol:var(--ec-tm-delBg);--tmLabel:var(--ec-tm-delDiffIndContent)}.expressive-code .ec-line.del .code{--ecLineBrdCol:var(--ec-tm-delBrdCol)}.expressive-code .ec-line.del .code::before{color:var(--ec-tm-delDiffIndCol)}.expressive-code .ec-line.mark,.expressive-code .ec-line.ins,.expressive-code .ec-line.del{background:var(--tmLineBgCol)}.expressive-code .ec-line.mark .code,.expressive-code .ec-line.ins .code,.expressive-code .ec-line.del .code{--ecGtrBrdWd:var(--ec-tm-lineMarkerAccentWd)}.expressive-code .ec-line.mark .code::before,.expressive-code .ec-line.ins .code::before,.expressive-code .ec-line.del .code::before{display:block;position:absolute;left:0;box-sizing:border-box;content:var(--tmLabel, &apos; &apos;);padding-inline-start:var(--ec-tm-lineDiffIndMargLeft);text-align:center;white-space:pre}.expressive-code .ec-line.mark.tm-label .code::before,.expressive-code .ec-line.ins.tm-label .code::before,.expressive-code .ec-line.del.tm-label .code::before{background:var(--ecLineBrdCol);padding:0 calc(var(--ec-tm-lineMarkerLabelPadInl) + var(--ec-tm-lineMarkerAccentWd)) 0 var(--ec-tm-lineMarkerLabelPadInl);color:var(--ec-tm-lineMarkerLabelCol)}.expressive-code .ec-line mark{--tmInlineBgCol:var(--ec-tm-markBg);--tmInlineBrdCol:var(--ec-tm-markBrdCol)}.expressive-code .ec-line ins{--tmInlineBgCol:var(--ec-tm-insBg);--tmInlineBrdCol:var(--ec-tm-insBrdCol)}.expressive-code .ec-line del{--tmInlineBgCol:var(--ec-tm-delBg);--tmInlineBrdCol:var(--ec-tm-delBrdCol)}.expressive-code .ec-line mark,.expressive-code .ec-line ins,.expressive-code .ec-line del{all:unset;display:inline-block;position:relative;--tmBrdL:var(--ec-tm-inlMarkerBrdWd);--tmBrdR:var(--ec-tm-inlMarkerBrdWd);--tmRadL:var(--ec-tm-inlMarkerBrdRad);--tmRadR:var(--ec-tm-inlMarkerBrdRad);margin-inline:0.025rem;padding-inline:var(--ec-tm-inlMarkerPad);border-radius:var(--tmRadL) var(--tmRadR) var(--tmRadR) var(--tmRadL);background:var(--tmInlineBgCol);background-clip:padding-box}.expressive-code .ec-line mark.open-start,.expressive-code .ec-line ins.open-start,.expressive-code .ec-line del.open-start{margin-inline-start:0;padding-inline-start:0;--tmBrdL:0px;--tmRadL:0}.expressive-code .ec-line mark.open-end,.expressive-code .ec-line ins.open-end,.expressive-code .ec-line del.open-end{margin-inline-end:0;padding-inline-end:0;--tmBrdR:0px;--tmRadR:0}.expressive-code .ec-line mark::before,.expressive-code .ec-line ins::before,.expressive-code .ec-line del::before{content:&apos;&apos;;position:absolute;pointer-events:none;display:inline-block;inset:0;border-radius:var(--tmRadL) var(--tmRadR) var(--tmRadR) var(--tmRadL);border:var(--ec-tm-inlMarkerBrdWd) solid var(--tmInlineBrdCol);border-inline-width:var(--tmBrdL) var(--tmBrdR)}.expressive-code .frame{all:unset;position:relative;display:block;--header-border-radius:calc(var(--ec-brdRad) + var(--ec-brdWd));--tab-border-radius:calc(var(--ec-frm-edTabBrdRad) + var(--ec-brdWd));--button-spacing:0.4rem;--code-background:var(--ec-frm-edBg);border-radius:var(--header-border-radius);box-shadow:var(--ec-frm-frameBoxShdCssVal)}.expressive-code .frame .header{display:none;z-index:1;position:relative;border-radius:var(--header-border-radius) var(--header-border-radius) 0 0}.expressive-code .frame.has-title pre,.expressive-code .frame.has-title code,.expressive-code .frame.is-terminal pre,.expressive-code .frame.is-terminal code{border-top:none;border-top-left-radius:0;border-top-right-radius:0}.expressive-code .frame .title:empty:before{content:&apos;\a0&apos;}.expressive-code .frame.has-title:not(.is-terminal){--button-spacing:calc(1.9rem + 2 * (var(--ec-uiPadBlk) + var(--ec-frm-edActTabIndHt)))}.expressive-code .frame.has-title:not(.is-terminal) .title{position:relative;color:var(--ec-frm-edActTabFg);background:var(--ec-frm-edActTabBg);background-clip:padding-box;margin-block-start:var(--ec-frm-edTabsMargBlkStart);padding:calc(var(--ec-uiPadBlk) + var(--ec-frm-edActTabIndHt)) var(--ec-uiPadInl);border:var(--ec-brdWd) solid var(--ec-frm-edActTabBrdCol);border-radius:var(--tab-border-radius) var(--tab-border-radius) 0 0;border-bottom:none;overflow:hidden}.expressive-code .frame.has-title:not(.is-terminal) .title::after{content:&apos;&apos;;position:absolute;pointer-events:none;inset:0;border-top:var(--ec-frm-edActTabIndHt) solid var(--ec-frm-edActTabIndTopCol);border-bottom:var(--ec-frm-edActTabIndHt) solid var(--ec-frm-edActTabIndBtmCol)}.expressive-code .frame.has-title:not(.is-terminal) .header{display:flex;background:linear-gradient(to top, var(--ec-frm-edTabBarBrdBtmCol) var(--ec-brdWd), transparent var(--ec-brdWd)),linear-gradient(var(--ec-frm-edTabBarBg), var(--ec-frm-edTabBarBg));background-repeat:no-repeat;padding-inline-start:var(--ec-frm-edTabsMargInlStart)}.expressive-code .frame.has-title:not(.is-terminal) .header::before{content:&apos;&apos;;position:absolute;pointer-events:none;inset:0;border:var(--ec-brdWd) solid var(--ec-frm-edTabBarBrdCol);border-radius:inherit;border-bottom:none}.expressive-code .frame.is-terminal{--button-spacing:calc(1.9rem + var(--ec-brdWd) + 2 * var(--ec-uiPadBlk));--code-background:var(--ec-frm-trmBg)}.expressive-code .frame.is-terminal .header{display:flex;align-items:center;justify-content:center;padding-block:var(--ec-uiPadBlk);padding-block-end:calc(var(--ec-uiPadBlk) + var(--ec-brdWd));position:relative;font-weight:500;letter-spacing:0.025ch;color:var(--ec-frm-trmTtbFg);background:var(--ec-frm-trmTtbBg);border:var(--ec-brdWd) solid var(--ec-brdCol);border-bottom:none}.expressive-code .frame.is-terminal .header::before{content:&apos;&apos;;position:absolute;pointer-events:none;left:var(--ec-uiPadInl);width:2.1rem;height:0.56rem;line-height:0;background-color:var(--ec-frm-trmTtbDotsFg);opacity:var(--ec-frm-trmTtbDotsOpa);-webkit-mask-image:var(--ec-frm-trmIcon);-webkit-mask-repeat:no-repeat;mask-image:var(--ec-frm-trmIcon);mask-repeat:no-repeat}.expressive-code .frame.is-terminal .header::after{content:&apos;&apos;;position:absolute;pointer-events:none;inset:0;border-bottom:var(--ec-brdWd) solid var(--ec-frm-trmTtbBrdBtmCol)}.expressive-code .frame pre{background:var(--code-background)}.expressive-code .copy{display:flex;gap:0.25rem;flex-direction:row;position:absolute;inset-block-start:calc(var(--ec-brdWd) + var(--button-spacing));inset-inline-end:calc(var(--ec-brdWd) + var(--ec-uiPadInl) / 2)}@media (scripting: none){.expressive-code .copy{display:none}}.expressive-code .copy{direction:ltr;unicode-bidi:isolate}.expressive-code .copy button{position:relative;align-self:flex-end;margin:0;padding:0;border:none;border-radius:0.2rem;z-index:1;cursor:pointer;transition-property:opacity, background, border-color;transition-duration:0.2s;transition-timing-function:cubic-bezier(0.25, 0.46, 0.45, 0.94);width:2.5rem;height:2.5rem;background:var(--code-background);opacity:0.75}.expressive-code .copy button div{position:absolute;inset:0;border-radius:inherit;background:var(--ec-frm-inlBtnBg);opacity:var(--ec-frm-inlBtnBgIdleOpa);transition-property:inherit;transition-duration:inherit;transition-timing-function:inherit}.expressive-code .copy button::before{content:&apos;&apos;;position:absolute;pointer-events:none;inset:0;border-radius:inherit;border:var(--ec-brdWd) solid var(--ec-frm-inlBtnBrd);opacity:var(--ec-frm-inlBtnBrdOpa)}.expressive-code .copy button::after{content:&apos;&apos;;position:absolute;pointer-events:none;inset:0;background-color:var(--ec-frm-inlBtnFg);-webkit-mask-image:var(--ec-frm-copyIcon);-webkit-mask-repeat:no-repeat;mask-image:var(--ec-frm-copyIcon);mask-repeat:no-repeat;margin:0.475rem;line-height:0}.expressive-code .copy button:hover,.expressive-code .copy button:focus:focus-visible{opacity:1}.expressive-code .copy button:hover div,.expressive-code .copy button:focus:focus-visible div{opacity:var(--ec-frm-inlBtnBgHoverOrFocusOpa)}.expressive-code .copy button:active{opacity:1}.expressive-code .copy button:active div{opacity:var(--ec-frm-inlBtnBgActOpa)}.expressive-code .copy .feedback{--tooltip-arrow-size:0.35rem;--tooltip-bg:var(--ec-frm-tooltipSuccessBg);color:var(--ec-frm-tooltipSuccessFg);pointer-events:none;user-select:none;-webkit-user-select:none;position:relative;align-self:center;background-color:var(--tooltip-bg);z-index:99;padding:0.125rem 0.75rem;border-radius:0.2rem;margin-inline-end:var(--tooltip-arrow-size);opacity:0;transition-property:opacity, transform;transition-duration:0.2s;transition-timing-function:ease-in-out;transform:translate3d(0, 0.25rem, 0)}.expressive-code .copy .feedback::after{content:&apos;&apos;;position:absolute;pointer-events:none;top:calc(50% - var(--tooltip-arrow-size));inset-inline-end:calc(-2 * (var(--tooltip-arrow-size) - 0.5px));border:var(--tooltip-arrow-size) solid transparent;border-inline-start-color:var(--tooltip-bg)}.expressive-code .copy .feedback.show{opacity:1;transform:translate3d(0, 0, 0)}@media (hover: hover){.expressive-code{}.expressive-code .copy button{opacity:0;width:2rem;height:2rem}.expressive-code .frame:hover .copy button:not(:hover),.expressive-code .frame:focus-within :focus-visible ~ .copy button:not(:hover),.expressive-code .frame .copy .feedback.show ~ button:not(:hover){opacity:0.75}}.expressive-code :nth-child(1 of .ec-line) .code{padding-inline-end:calc(2rem + var(--ec-codePadInl))}:root{--ec-brdRad:0.75rem;--ec-brdWd:1.5px;--ec-brdCol:var(--code-line);--ec-codeFontFml:var(--font-code);--ec-codeFontSize:0.875rem;--ec-codeFontWg:400;--ec-codeLineHt:1.75;--ec-codePadBlk:1rem;--ec-codePadInl:1.125rem;--ec-codeBg:var(--code-bg);--ec-codeFg:#e6edf3;--ec-codeSelBg:#264f78;--ec-gtrFg:#6e7681;--ec-gtrBrdCol:#6e768133;--ec-gtrBrdWd:1.5px;--ec-gtrHlFg:#e6edf3;--ec-uiFontFml:var(--font-mono);--ec-uiFontSize:0.75rem;--ec-uiFontWg:400;--ec-uiLineHt:1.65;--ec-uiPadBlk:0.25rem;--ec-uiPadInl:1rem;--ec-uiSelBg:#6e768166;--ec-uiSelFg:#e6edf3;--ec-focusBrd:#1f6feb;--ec-sbThumbCol:#8b949e33;--ec-sbThumbHoverCol:#8b949e3d;--ec-tm-lineMarkerAccentMarg:0rem;--ec-tm-lineMarkerAccentWd:0.15rem;--ec-tm-lineMarkerLabelPadInl:0.2rem;--ec-tm-lineMarkerLabelCol:white;--ec-tm-lineDiffIndMargLeft:0.3rem;--ec-tm-inlMarkerBrdWd:1.5px;--ec-tm-inlMarkerBrdRad:0.2rem;--ec-tm-inlMarkerPad:0.15rem;--ec-tm-insDiffIndContent:&apos;+&apos;;--ec-tm-delDiffIndContent:&apos;-&apos;;--ec-tm-markBg:#264a8980;--ec-tm-markBrdCol:#5570b3d0;--ec-tm-insBg:#26561c80;--ec-tm-insBrdCol:#4e7e41d0;--ec-tm-insDiffIndCol:#7eb070d0;--ec-tm-delBg:#81322b80;--ec-tm-delBrdCol:#ae594fd0;--ec-tm-delDiffIndCol:#e68a7ed0;--ec-frm-shdCol:#0000005b;--ec-frm-frameBoxShdCssVal:none;--ec-frm-edActTabBg:var(--code-bg);--ec-frm-edActTabFg:var(--code-muted);--ec-frm-edActTabBrdCol:transparent;--ec-frm-edActTabIndHt:1.5px;--ec-frm-edActTabIndTopCol:transparent;--ec-frm-edActTabIndBtmCol:#0d1117;--ec-frm-edTabsMargInlStart:0;--ec-frm-edTabsMargBlkStart:0;--ec-frm-edTabBrdRad:0.75rem;--ec-frm-edTabBarBg:var(--code-bg);--ec-frm-edTabBarBrdCol:var(--code-line);--ec-frm-edTabBarBrdBtmCol:var(--code-line);--ec-frm-edBg:var(--code-bg);--ec-frm-trmTtbFg:var(--code-muted);--ec-frm-trmTtbDotsFg:var(--code-muted);--ec-frm-trmTtbDotsOpa:0.15;--ec-frm-trmTtbBg:var(--code-bg);--ec-frm-trmTtbBrdBtmCol:var(--code-line);--ec-frm-trmBg:var(--code-bg);--ec-frm-inlBtnBg:var(--code-ink);--ec-frm-inlBtnBgIdleOpa:0;--ec-frm-inlBtnBgHoverOrFocusOpa:0.2;--ec-frm-inlBtnBgActOpa:0.3;--ec-frm-inlBtnFg:var(--code-ink);--ec-frm-inlBtnBrd:var(--code-line);--ec-frm-inlBtnBrdOpa:0.4;--ec-frm-tooltipSuccessBg:var(--color-emerald);--ec-frm-tooltipSuccessFg:var(--color-bg);--ec-frm-copyIcon:url(&quot;data:image/svg+xml,%3Csvg%20xmlns%3D&apos;http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg&apos;%20viewBox%3D&apos;0%200%2024%2024&apos;%20fill%3D&apos;none&apos;%20stroke%3D&apos;black&apos;%20stroke-width%3D&apos;1.75&apos;%3E%3Cpath%20d%3D&apos;M3%2019a2%202%200%200%201-1-2V2a2%202%200%200%201%201-1h13a2%202%200%200%201%202%201&apos;%2F%3E%3Crect%20x%3D&apos;6&apos;%20y%3D&apos;5&apos;%20width%3D&apos;16&apos;%20height%3D&apos;18&apos;%20rx%3D&apos;1.5&apos;%20ry%3D&apos;1.5&apos;%2F%3E%3C%2Fsvg%3E&quot;);--ec-frm-trmIcon:url(&quot;data:image/svg+xml,%3Csvg%20xmlns%3D&apos;http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg&apos;%20viewBox%3D&apos;0%200%2060%2016&apos;%20preserveAspectRatio%3D&apos;xMidYMid%20meet&apos;%3E%3Ccircle%20cx%3D&apos;8&apos;%20cy%3D&apos;8&apos;%20r%3D&apos;8&apos;%2F%3E%3Ccircle%20cx%3D&apos;30&apos;%20cy%3D&apos;8&apos;%20r%3D&apos;8&apos;%2F%3E%3Ccircle%20cx%3D&apos;52&apos;%20cy%3D&apos;8&apos;%20r%3D&apos;8&apos;%2F%3E%3C%2Fsvg%3E&quot;)}.expressive-code .ec-line :where(span[style^=&apos;--&apos;]:not([class])){color:var(--0, inherit);background-color:var(--0bg, transparent);font-style:var(--0fs, inherit);font-weight:var(--0fw, inherit);text-decoration:var(--0td, inherit)}&lt;/style&gt;&lt;script type=&quot;module&quot; src=&quot;/_astro/ec.0vx5m.js&quot;&gt;&lt;/script&gt;&lt;figure class=&quot;frame has-title&quot;&gt;&lt;figcaption class=&quot;header&quot;&gt;&lt;span class=&quot;title&quot;&gt;JavaScript&lt;/span&gt;&lt;/figcaption&gt;&lt;pre data-language=&quot;javascript&quot;&gt;&lt;code&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span style=&quot;--0:#8B949E&quot;&gt;// DANGEROUS ANTI-PATTERN: Check-Then-Insert Race Condition&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;const&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; &lt;/span&gt;&lt;span style=&quot;--0:#79C0FF&quot;&gt;existing&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; &lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;=&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; &lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;await&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; db.&lt;/span&gt;&lt;span style=&quot;--0:#D2A8FF&quot;&gt;query&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;(&lt;/span&gt;&lt;span style=&quot;--0:#A5D6FF&quot;&gt;&apos;SELECT * FROM payments WHERE idempotency_key = $1&apos;&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;, [key]);&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;
&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;if&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; (&lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;!&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;existing.rows.&lt;/span&gt;&lt;span style=&quot;--0:#79C0FF&quot;&gt;length&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;) {&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span class=&quot;indent&quot;&gt;  &lt;/span&gt;&lt;span style=&quot;--0:#8B949E&quot;&gt;// If concurrent requests arrive simultaneously, both evaluate to true!&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span class=&quot;indent&quot;&gt;  &lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;await&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; &lt;/span&gt;&lt;span style=&quot;--0:#D2A8FF&quot;&gt;chargeCard&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;(amount);&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span class=&quot;indent&quot;&gt;  &lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;await&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; db.&lt;/span&gt;&lt;span style=&quot;--0:#D2A8FF&quot;&gt;query&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;(&lt;/span&gt;&lt;span style=&quot;--0:#A5D6FF&quot;&gt;&apos;INSERT INTO payments (idempotency_key, status) VALUES ($1, $2)&apos;&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;, [key, &lt;/span&gt;&lt;span style=&quot;--0:#A5D6FF&quot;&gt;&apos;DONE&apos;&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;]);&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;}&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;/code&gt;&lt;/pre&gt;&lt;div class=&quot;copy&quot;&gt;&lt;div aria-live=&quot;polite&quot;&gt;&lt;/div&gt;&lt;button title=&quot;Copy to clipboard&quot; data-copied=&quot;Copied!&quot; data-code=&quot;// DANGEROUS ANTI-PATTERN: Check-Then-Insert Race Conditionconst existing = await db.query(&amp;#x27;SELECT * FROM payments WHERE idempotency_key = $1&amp;#x27;, [key]);if (!existing.rows.length) {  // If concurrent requests arrive simultaneously, both evaluate to true!  await chargeCard(amount);  await db.query(&amp;#x27;INSERT INTO payments (idempotency_key, status) VALUES ($1, $2)&amp;#x27;, [key, &amp;#x27;DONE&amp;#x27;]);}&quot;&gt;&lt;div&gt;&lt;/div&gt;&lt;/button&gt;&lt;/div&gt;&lt;/figure&gt;&lt;/div&gt;
&lt;p&gt;If two duplicate requests hit separate node instances concurrently, both queries return empty results, and both threads proceed to charge the user. This is the classic &lt;strong&gt;Check-Then-Insert&lt;/strong&gt; race condition.&lt;/p&gt;
&lt;p&gt;Application-level checks cannot guarantee safety in concurrent systems. Database unique constraints provide the only authoritative synchronization boundary.&lt;/p&gt;
&lt;figure&gt;&lt;img src=&quot;https://raw.githubusercontent.com/rafeuddaraj/rafes-blog-assets/refs/heads/exactly-once-delivery-myth-distributed-systems/assets/db-unique-constraint.svg&quot; alt=&quot;Database Level Unique Constraint&quot; loading=&quot;lazy&quot; decoding=&quot;async&quot; width=&quot;800&quot; height=&quot;400&quot;&gt;&lt;figcaption&gt;Database Level Unique Constraint&lt;/figcaption&gt;&lt;/figure&gt;
&lt;div class=&quot;expressive-code&quot;&gt;&lt;figure class=&quot;frame has-title&quot;&gt;&lt;figcaption class=&quot;header&quot;&gt;&lt;span class=&quot;title&quot;&gt;SQL&lt;/span&gt;&lt;/figcaption&gt;&lt;pre data-language=&quot;sql&quot;&gt;&lt;code&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;CREATE&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; &lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;TABLE&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; &lt;/span&gt;&lt;span style=&quot;--0:#D2A8FF&quot;&gt;idempotency_keys&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; (&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span class=&quot;indent&quot;&gt;    &lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;key&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; &lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;VARCHAR&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;(&lt;/span&gt;&lt;span style=&quot;--0:#79C0FF&quot;&gt;255&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;) &lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;PRIMARY KEY&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;,&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span class=&quot;indent&quot;&gt;    &lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;status&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; &lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;VARCHAR&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;(&lt;/span&gt;&lt;span style=&quot;--0:#79C0FF&quot;&gt;50&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;) &lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;NOT NULL&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;, &lt;/span&gt;&lt;span style=&quot;--0:#8B949E&quot;&gt;-- &apos;IN_PROGRESS&apos;, &apos;COMPLETED&apos;, &apos;FAILED&apos;&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span class=&quot;indent&quot;&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;    &lt;/span&gt;&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;response_body JSONB,&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span class=&quot;indent&quot;&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;    &lt;/span&gt;&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;created_at &lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;TIMESTAMP WITH TIME ZONE&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; &lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;DEFAULT&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; &lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;NOW&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;()&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;);&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;/code&gt;&lt;/pre&gt;&lt;div class=&quot;copy&quot;&gt;&lt;div aria-live=&quot;polite&quot;&gt;&lt;/div&gt;&lt;button title=&quot;Copy to clipboard&quot; data-copied=&quot;Copied!&quot; data-code=&quot;CREATE TABLE idempotency_keys (    key VARCHAR(255) PRIMARY KEY,    status VARCHAR(50) NOT NULL, -- &amp;#x27;IN_PROGRESS&amp;#x27;, &amp;#x27;COMPLETED&amp;#x27;, &amp;#x27;FAILED&amp;#x27;    response_body JSONB,    created_at TIMESTAMP WITH TIME ZONE DEFAULT NOW());&quot;&gt;&lt;div&gt;&lt;/div&gt;&lt;/button&gt;&lt;/div&gt;&lt;/figure&gt;&lt;/div&gt;
&lt;p&gt;Database B-Tree indexes enforce row uniqueness at the storage engine level. When multiple workers attempt concurrent inserts for the same key, exactly one transaction succeeds while all others fail with a unique violation error.&lt;/p&gt;
&lt;hr&gt;
&lt;h2 id=&quot;consumer-crashes-and-the-inbox-pattern&quot;&gt;Consumer Crashes and the Inbox Pattern&lt;/h2&gt;
&lt;p&gt;When processing asynchronous message queues (Kafka, RabbitMQ, SQS), worker crashes create duplicate processing risks:&lt;/p&gt;
&lt;ol&gt;
&lt;li&gt;A consumer retrieves a message from the queue.&lt;/li&gt;
&lt;li&gt;The consumer credits &lt;code&gt;$100&lt;/code&gt; to the user&apos;s account balance.&lt;/li&gt;
&lt;li&gt;Just before dispatching the &lt;code&gt;ACK&lt;/code&gt; back to the broker, the consumer process suffers an Out of Memory (OOM) crash.&lt;/li&gt;
&lt;/ol&gt;
&lt;p&gt;Because the broker never receives an ACK, it assumes delivery failed. Upon consumer reboot, the broker redelivers the message, causing another &lt;code&gt;$100&lt;/code&gt; credit.&lt;/p&gt;
&lt;figure&gt;&lt;img src=&quot;https://raw.githubusercontent.com/rafeuddaraj/rafes-blog-assets/refs/heads/exactly-once-delivery-myth-distributed-systems/assets/inbox-pattern.svg&quot; alt=&quot;Inbox Pattern for Consumer Crashes&quot; loading=&quot;lazy&quot; decoding=&quot;async&quot; width=&quot;800&quot; height=&quot;400&quot;&gt;&lt;figcaption&gt;Inbox Pattern for Consumer Crashes&lt;/figcaption&gt;&lt;/figure&gt;
&lt;p&gt;To prevent this vulnerability, engineers deploy the &lt;strong&gt;Inbox Pattern&lt;/strong&gt;.&lt;/p&gt;
&lt;p&gt;The core invariant of the Inbox Pattern: &lt;strong&gt;Persisting the processed message identifier and updating domain data must execute within a single atomic database transaction.&lt;/strong&gt;&lt;/p&gt;
&lt;div class=&quot;expressive-code&quot;&gt;&lt;figure class=&quot;frame has-title&quot;&gt;&lt;figcaption class=&quot;header&quot;&gt;&lt;span class=&quot;title&quot;&gt;SQL&lt;/span&gt;&lt;/figcaption&gt;&lt;pre data-language=&quot;sql&quot;&gt;&lt;code&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;BEGIN&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;;&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;
&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span style=&quot;--0:#8B949E&quot;&gt;-- 1. Insert message ID into inbox (message_id holds a UNIQUE constraint)&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span style=&quot;--0:#8B949E&quot;&gt;-- On duplicate delivery, the insert fails and aborts the entire transaction block&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;INSERT INTO&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; message_inbox (message_id, received_at)&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;VALUES&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; (&lt;/span&gt;&lt;span style=&quot;--0:#A5D6FF&quot;&gt;&apos;msg-ord-98765&apos;&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;, &lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;NOW&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;());&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;
&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span style=&quot;--0:#8B949E&quot;&gt;-- 2. Mutate business state within the same transaction scope&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;UPDATE&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; user_wallets&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;SET&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; balance &lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;=&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; balance &lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;+&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; &lt;/span&gt;&lt;span style=&quot;--0:#79C0FF&quot;&gt;100&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;WHERE&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; user_id &lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;=&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; &lt;/span&gt;&lt;span style=&quot;--0:#A5D6FF&quot;&gt;&apos;usr-001&apos;&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;;&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;
&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span style=&quot;--0:#8B949E&quot;&gt;-- 3. Record audit trail&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;INSERT INTO&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; wallet_transactions (user_id, amount, &lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;type&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;)&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;VALUES&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; (&lt;/span&gt;&lt;span style=&quot;--0:#A5D6FF&quot;&gt;&apos;usr-001&apos;&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;, &lt;/span&gt;&lt;span style=&quot;--0:#79C0FF&quot;&gt;100&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;, &lt;/span&gt;&lt;span style=&quot;--0:#A5D6FF&quot;&gt;&apos;CREDIT&apos;&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;);&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;
&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span style=&quot;--0:#8B949E&quot;&gt;-- 4. Commit atomically&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;COMMIT&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;;&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;/code&gt;&lt;/pre&gt;&lt;div class=&quot;copy&quot;&gt;&lt;div aria-live=&quot;polite&quot;&gt;&lt;/div&gt;&lt;button title=&quot;Copy to clipboard&quot; data-copied=&quot;Copied!&quot; data-code=&quot;BEGIN;-- 1. Insert message ID into inbox (message_id holds a UNIQUE constraint)-- On duplicate delivery, the insert fails and aborts the entire transaction blockINSERT INTO message_inbox (message_id, received_at)VALUES (&amp;#x27;msg-ord-98765&amp;#x27;, NOW());-- 2. Mutate business state within the same transaction scopeUPDATE user_walletsSET balance = balance + 100WHERE user_id = &amp;#x27;usr-001&amp;#x27;;-- 3. Record audit trailINSERT INTO wallet_transactions (user_id, amount, type)VALUES (&amp;#x27;usr-001&amp;#x27;, 100, &amp;#x27;CREDIT&amp;#x27;);-- 4. Commit atomicallyCOMMIT;&quot;&gt;&lt;div&gt;&lt;/div&gt;&lt;/button&gt;&lt;/div&gt;&lt;/figure&gt;&lt;/div&gt;
&lt;p&gt;If the server crashes prior to &lt;code&gt;COMMIT&lt;/code&gt;, the database rolls back all mutations. If it crashes after &lt;code&gt;COMMIT&lt;/code&gt;, the message ID is securely persisted, causing future redelivery attempts to trigger a unique constraint violation and exit cleanly.&lt;/p&gt;
&lt;hr&gt;
&lt;h2 id=&quot;the-dual-write-problem-and-transactional-outbox-pattern&quot;&gt;The Dual-Write Problem and Transactional Outbox Pattern&lt;/h2&gt;
&lt;p&gt;The Inbox Pattern protects message consumption. But how do we guarantee reliable message publishing?&lt;/p&gt;
&lt;p&gt;Consider an order service that writes an order to the database and then publishes an &lt;code&gt;OrderCreated&lt;/code&gt; event to Kafka:&lt;/p&gt;
&lt;div class=&quot;expressive-code&quot;&gt;&lt;figure class=&quot;frame has-title&quot;&gt;&lt;figcaption class=&quot;header&quot;&gt;&lt;span class=&quot;title&quot;&gt;JavaScript&lt;/span&gt;&lt;/figcaption&gt;&lt;pre data-language=&quot;javascript&quot;&gt;&lt;code&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span style=&quot;--0:#8B949E&quot;&gt;// DANGEROUS ANTI-PATTERN: The Dual-Write Problem&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;await&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; db.&lt;/span&gt;&lt;span style=&quot;--0:#D2A8FF&quot;&gt;query&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;(&lt;/span&gt;&lt;span style=&quot;--0:#A5D6FF&quot;&gt;&apos;INSERT INTO orders ...&apos;&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;);       &lt;/span&gt;&lt;span style=&quot;--0:#8B949E&quot;&gt;// Step 1: Database Commit&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;await&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; kafkaProducer.&lt;/span&gt;&lt;span style=&quot;--0:#D2A8FF&quot;&gt;send&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;(&lt;/span&gt;&lt;span style=&quot;--0:#A5D6FF&quot;&gt;&apos;OrderCreated&apos;&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;, &lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;...&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;);  &lt;/span&gt;&lt;span style=&quot;--0:#8B949E&quot;&gt;// Step 2: Process crash or network loss!&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;/code&gt;&lt;/pre&gt;&lt;div class=&quot;copy&quot;&gt;&lt;div aria-live=&quot;polite&quot;&gt;&lt;/div&gt;&lt;button title=&quot;Copy to clipboard&quot; data-copied=&quot;Copied!&quot; data-code=&quot;// DANGEROUS ANTI-PATTERN: The Dual-Write Problemawait db.query(&amp;#x27;INSERT INTO orders ...&amp;#x27;);       // Step 1: Database Commitawait kafkaProducer.send(&amp;#x27;OrderCreated&amp;#x27;, ...);  // Step 2: Process crash or network loss!&quot;&gt;&lt;div&gt;&lt;/div&gt;&lt;/button&gt;&lt;/div&gt;&lt;/figure&gt;&lt;/div&gt;
&lt;p&gt;If the process crashes between Step 1 and Step 2, the order exists in the database, but downstream inventory services never receive notification. This is the &lt;strong&gt;Dual-Write Problem&lt;/strong&gt;: two distinct distributed storage engines cannot participate in an atomic commit without complex coordination protocols.&lt;/p&gt;
&lt;p&gt;The standard solution is the &lt;strong&gt;Transactional Outbox Pattern&lt;/strong&gt;:&lt;/p&gt;
&lt;ol&gt;
&lt;li&gt;Domain mutations and outbound message payloads are written to an &lt;code&gt;outbox_events&lt;/code&gt; table inside the same local database transaction.&lt;/li&gt;
&lt;li&gt;Because both writes occur in a single database transaction, ACID properties guarantee both succeed or both roll back.&lt;/li&gt;
&lt;li&gt;An asynchronous relay process (or Change Data Capture engine like Debezium) tails the outbox table and streams events to the message broker.&lt;/li&gt;
&lt;/ol&gt;
&lt;figure&gt;&lt;img src=&quot;https://raw.githubusercontent.com/rafeuddaraj/rafes-blog-assets/refs/heads/exactly-once-delivery-myth-distributed-systems/assets/transactional-outbox.svg&quot; alt=&quot;Transactional Outbox Architecture&quot; loading=&quot;lazy&quot; decoding=&quot;async&quot; width=&quot;800&quot; height=&quot;400&quot;&gt;&lt;figcaption&gt;Transactional Outbox Architecture&lt;/figcaption&gt;&lt;/figure&gt;
&lt;div class=&quot;callout&quot; role=&quot;note&quot; data-type=&quot;warning&quot;&gt;
&lt;p class=&quot;callout-title&quot;&gt;Outbox Guarantees&lt;/p&gt;
&lt;p&gt;The Transactional Outbox pattern provides At-Least-Once delivery. If the relay worker publishes an event to Kafka and crashes before updating the outbox record, the event will be republished. Consequently, downstream consumers must implement the Inbox Pattern.&lt;/p&gt;
&lt;/div&gt;
&lt;hr&gt;
&lt;h2 id=&quot;retry-storms-exponential-backoff-and-jitter&quot;&gt;Retry Storms, Exponential Backoff, and Jitter&lt;/h2&gt;
&lt;p&gt;When a downstream service experiences partial degradation, upstream clients operating under At-Least-Once semantics begin retrying aggressively.&lt;/p&gt;
&lt;p&gt;When the downstream service attempts recovery, it is hit with an overwhelming surge of queued retries, triggering an immediate relapse. This self-inflicted outage is known as a &lt;strong&gt;Retry Storm&lt;/strong&gt; (or Thundering Herd problem).&lt;/p&gt;
&lt;figure&gt;&lt;img src=&quot;https://raw.githubusercontent.com/rafeuddaraj/rafes-blog-assets/refs/heads/exactly-once-delivery-myth-distributed-systems/assets/retry-storm-backoff.svg&quot; alt=&quot;Retry Storms vs Exponential Backoff with Jitter&quot; loading=&quot;lazy&quot; decoding=&quot;async&quot; width=&quot;800&quot; height=&quot;400&quot;&gt;&lt;figcaption&gt;Retry Storms vs Exponential Backoff with Jitter&lt;/figcaption&gt;&lt;/figure&gt;
&lt;p&gt;To mitigate retry storms, production systems combine two strategies:&lt;/p&gt;
&lt;ol&gt;
&lt;li&gt;&lt;strong&gt;Exponential Backoff:&lt;/strong&gt; Increasing retry intervals exponentially (&lt;span class=&quot;katex&quot;&gt;&lt;span class=&quot;katex-html&quot; aria-hidden=&quot;true&quot;&gt;&lt;span class=&quot;base&quot;&gt;&lt;span class=&quot;strut&quot; style=&quot;height:1.0085em;vertical-align:-0.1944em;&quot;&gt;&lt;/span&gt;&lt;span class=&quot;mord&quot;&gt;&lt;span class=&quot;mord&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;msupsub&quot;&gt;&lt;span class=&quot;vlist-t&quot;&gt;&lt;span class=&quot;vlist-r&quot;&gt;&lt;span class=&quot;vlist&quot; style=&quot;height:0.8141em;&quot;&gt;&lt;span style=&quot;top:-3.063em;margin-right:0.05em;&quot;&gt;&lt;span class=&quot;pstrut&quot; style=&quot;height:2.7em;&quot;&gt;&lt;/span&gt;&lt;span class=&quot;sizing reset-size6 size3 mtight&quot;&gt;&lt;span class=&quot;mord mtight&quot;&gt;0&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class=&quot;mpunct&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mspace&quot; style=&quot;margin-right:0.1667em;&quot;&gt;&lt;/span&gt;&lt;span class=&quot;mord&quot;&gt;&lt;span class=&quot;mord&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;msupsub&quot;&gt;&lt;span class=&quot;vlist-t&quot;&gt;&lt;span class=&quot;vlist-r&quot;&gt;&lt;span class=&quot;vlist&quot; style=&quot;height:0.8141em;&quot;&gt;&lt;span style=&quot;top:-3.063em;margin-right:0.05em;&quot;&gt;&lt;span class=&quot;pstrut&quot; style=&quot;height:2.7em;&quot;&gt;&lt;/span&gt;&lt;span class=&quot;sizing reset-size6 size3 mtight&quot;&gt;&lt;span class=&quot;mord mtight&quot;&gt;1&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class=&quot;mpunct&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mspace&quot; style=&quot;margin-right:0.1667em;&quot;&gt;&lt;/span&gt;&lt;span class=&quot;mord&quot;&gt;&lt;span class=&quot;mord&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;msupsub&quot;&gt;&lt;span class=&quot;vlist-t&quot;&gt;&lt;span class=&quot;vlist-r&quot;&gt;&lt;span class=&quot;vlist&quot; style=&quot;height:0.8141em;&quot;&gt;&lt;span style=&quot;top:-3.063em;margin-right:0.05em;&quot;&gt;&lt;span class=&quot;pstrut&quot; style=&quot;height:2.7em;&quot;&gt;&lt;/span&gt;&lt;span class=&quot;sizing reset-size6 size3 mtight&quot;&gt;&lt;span class=&quot;mord mtight&quot;&gt;2&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class=&quot;mpunct&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mspace&quot; style=&quot;margin-right:0.1667em;&quot;&gt;&lt;/span&gt;&lt;span class=&quot;mord&quot;&gt;&lt;span class=&quot;mord&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;msupsub&quot;&gt;&lt;span class=&quot;vlist-t&quot;&gt;&lt;span class=&quot;vlist-r&quot;&gt;&lt;span class=&quot;vlist&quot; style=&quot;height:0.8141em;&quot;&gt;&lt;span style=&quot;top:-3.063em;margin-right:0.05em;&quot;&gt;&lt;span class=&quot;pstrut&quot; style=&quot;height:2.7em;&quot;&gt;&lt;/span&gt;&lt;span class=&quot;sizing reset-size6 size3 mtight&quot;&gt;&lt;span class=&quot;mord mtight&quot;&gt;3&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class=&quot;mspace&quot; style=&quot;margin-right:0.1667em;&quot;&gt;&lt;/span&gt;&lt;span class=&quot;minner&quot;&gt;…&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/span&gt; seconds).&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Full Jitter:&lt;/strong&gt; Introducing random variation into retry delays to distribute incoming traffic evenly across time.&lt;/li&gt;
&lt;/ol&gt;
&lt;div class=&quot;expressive-code&quot;&gt;&lt;figure class=&quot;frame has-title&quot;&gt;&lt;figcaption class=&quot;header&quot;&gt;&lt;span class=&quot;title&quot;&gt;JavaScript&lt;/span&gt;&lt;/figcaption&gt;&lt;pre data-language=&quot;javascript&quot;&gt;&lt;code&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span style=&quot;--0:#8B949E&quot;&gt;// Production-grade Exponential Backoff with Full Jitter&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;async&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; &lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;function&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; &lt;/span&gt;&lt;span style=&quot;--0:#D2A8FF&quot;&gt;fetchWithResilience&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;(&lt;/span&gt;&lt;span style=&quot;--0:#FFA657&quot;&gt;url&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;, &lt;/span&gt;&lt;span style=&quot;--0:#FFA657&quot;&gt;options&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;, &lt;/span&gt;&lt;span style=&quot;--0:#FFA657&quot;&gt;maxRetries&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; &lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;=&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; &lt;/span&gt;&lt;span style=&quot;--0:#79C0FF&quot;&gt;5&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;) {&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span class=&quot;indent&quot;&gt;  &lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;for&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; (&lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;let&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; attempt &lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;=&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; &lt;/span&gt;&lt;span style=&quot;--0:#79C0FF&quot;&gt;0&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;; attempt &lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;&amp;#x3C;&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; maxRetries; attempt&lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;++&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;) {&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span class=&quot;indent&quot;&gt;    &lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;try&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; {&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span class=&quot;indent&quot;&gt;      &lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;const&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; &lt;/span&gt;&lt;span style=&quot;--0:#79C0FF&quot;&gt;response&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; &lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;=&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; &lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;await&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; &lt;/span&gt;&lt;span style=&quot;--0:#D2A8FF&quot;&gt;fetch&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;(url, options);&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span class=&quot;indent&quot;&gt;      &lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;if&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; (response.ok) &lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;return&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; response;&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;
&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span class=&quot;indent&quot;&gt;      &lt;/span&gt;&lt;span style=&quot;--0:#8B949E&quot;&gt;// Do not retry 4xx client errors (excluding 429 Rate Limit)&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span class=&quot;indent&quot;&gt;      &lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;if&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; (response.status &lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;!==&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; &lt;/span&gt;&lt;span style=&quot;--0:#79C0FF&quot;&gt;429&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; &lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;&amp;#x26;&amp;#x26;&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; response.status &lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;&amp;#x3C;&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; &lt;/span&gt;&lt;span style=&quot;--0:#79C0FF&quot;&gt;500&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;) {&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span class=&quot;indent&quot;&gt;        &lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;throw&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; &lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;new&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; &lt;/span&gt;&lt;span style=&quot;--0:#D2A8FF&quot;&gt;Error&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;(&lt;/span&gt;&lt;span style=&quot;--0:#A5D6FF&quot;&gt;`Client Error: ${&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;response&lt;/span&gt;&lt;span style=&quot;--0:#A5D6FF&quot;&gt;.&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;status&lt;/span&gt;&lt;span style=&quot;--0:#A5D6FF&quot;&gt;}`&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;);&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span class=&quot;indent&quot;&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;      &lt;/span&gt;&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;}&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span class=&quot;indent&quot;&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;    &lt;/span&gt;&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;} &lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;catch&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; (error) {&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span class=&quot;indent&quot;&gt;      &lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;if&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; (attempt &lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;===&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; maxRetries &lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;-&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; &lt;/span&gt;&lt;span style=&quot;--0:#79C0FF&quot;&gt;1&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;) &lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;throw&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; error;&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;
&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span class=&quot;indent&quot;&gt;      &lt;/span&gt;&lt;span style=&quot;--0:#8B949E&quot;&gt;// 1. Calculate Exponential Base Delay: 1s, 2s, 4s, 8s, 16s...&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span class=&quot;indent&quot;&gt;      &lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;const&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; &lt;/span&gt;&lt;span style=&quot;--0:#79C0FF&quot;&gt;baseDelay&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; &lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;=&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; Math.&lt;/span&gt;&lt;span style=&quot;--0:#D2A8FF&quot;&gt;pow&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;(&lt;/span&gt;&lt;span style=&quot;--0:#79C0FF&quot;&gt;2&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;, attempt) &lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;*&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; &lt;/span&gt;&lt;span style=&quot;--0:#79C0FF&quot;&gt;1000&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;;&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;
&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span class=&quot;indent&quot;&gt;      &lt;/span&gt;&lt;span style=&quot;--0:#8B949E&quot;&gt;// 2. Full Jitter: Uniform random distribution in [0, baseDelay]&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span class=&quot;indent&quot;&gt;      &lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;const&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; &lt;/span&gt;&lt;span style=&quot;--0:#79C0FF&quot;&gt;delay&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; &lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;=&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; Math.&lt;/span&gt;&lt;span style=&quot;--0:#D2A8FF&quot;&gt;random&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;() &lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;*&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; baseDelay;&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;
&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span class=&quot;indent&quot;&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;      &lt;/span&gt;&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;console.&lt;/span&gt;&lt;span style=&quot;--0:#D2A8FF&quot;&gt;warn&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;(&lt;/span&gt;&lt;span style=&quot;--0:#A5D6FF&quot;&gt;`Attempt ${&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;attempt&lt;/span&gt;&lt;span style=&quot;--0:#A5D6FF&quot;&gt; &lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;+&lt;/span&gt;&lt;span style=&quot;--0:#A5D6FF&quot;&gt; &lt;/span&gt;&lt;span style=&quot;--0:#79C0FF&quot;&gt;1&lt;/span&gt;&lt;span style=&quot;--0:#A5D6FF&quot;&gt;} failed. Retrying in ${&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;Math&lt;/span&gt;&lt;span style=&quot;--0:#A5D6FF&quot;&gt;.&lt;/span&gt;&lt;span style=&quot;--0:#D2A8FF&quot;&gt;round&lt;/span&gt;&lt;span style=&quot;--0:#A5D6FF&quot;&gt;(&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;delay&lt;/span&gt;&lt;span style=&quot;--0:#A5D6FF&quot;&gt;)&lt;/span&gt;&lt;span style=&quot;--0:#A5D6FF&quot;&gt;}ms...`&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;);&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span class=&quot;indent&quot;&gt;      &lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;await&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; &lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;new&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; &lt;/span&gt;&lt;span style=&quot;--0:#79C0FF&quot;&gt;Promise&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;(&lt;/span&gt;&lt;span style=&quot;--0:#FFA657&quot;&gt;resolve&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; &lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;=&gt;&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; &lt;/span&gt;&lt;span style=&quot;--0:#D2A8FF&quot;&gt;setTimeout&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;(resolve, delay));&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span class=&quot;indent&quot;&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;    &lt;/span&gt;&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;}&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span class=&quot;indent&quot;&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;  &lt;/span&gt;&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;}&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;}&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;/code&gt;&lt;/pre&gt;&lt;div class=&quot;copy&quot;&gt;&lt;div aria-live=&quot;polite&quot;&gt;&lt;/div&gt;&lt;button title=&quot;Copy to clipboard&quot; data-copied=&quot;Copied!&quot; data-code=&quot;// Production-grade Exponential Backoff with Full Jitterasync function fetchWithResilience(url, options, maxRetries = 5) {  for (let attempt = 0; attempt &lt; maxRetries; attempt++) {    try {      const response = await fetch(url, options);      if (response.ok) return response;      // Do not retry 4xx client errors (excluding 429 Rate Limit)      if (response.status !== 429 &amp;#x26;&amp;#x26; response.status &lt; 500) {        throw new Error(&amp;#x60;Client Error: ${response.status}&amp;#x60;);      }    } catch (error) {      if (attempt === maxRetries - 1) throw error;      // 1. Calculate Exponential Base Delay: 1s, 2s, 4s, 8s, 16s...      const baseDelay = Math.pow(2, attempt) * 1000;      // 2. Full Jitter: Uniform random distribution in [0, baseDelay]      const delay = Math.random() * baseDelay;      console.warn(&amp;#x60;Attempt ${attempt + 1} failed. Retrying in ${Math.round(delay)}ms...&amp;#x60;);      await new Promise(resolve =&gt; setTimeout(resolve, delay));    }  }}&quot;&gt;&lt;div&gt;&lt;/div&gt;&lt;/button&gt;&lt;/div&gt;&lt;/figure&gt;&lt;/div&gt;
&lt;hr&gt;
&lt;h2 id=&quot;the-myth-vs-reality-of-apache-kafkas-exactly-once&quot;&gt;The Myth vs. Reality of Apache Kafka&apos;s Exactly-Once&lt;/h2&gt;
&lt;p&gt;A prevalent industry misunderstanding is that enabling Kafka&apos;s Exactly-Once Semantics (&lt;code&gt;processing.guarantee=exactly_once_v2&lt;/code&gt;) guarantees end-to-end exactly-once delivery across your entire stack.&lt;/p&gt;
&lt;p&gt;Kafka&apos;s transactional guarantees apply strictly within closed Kafka boundaries:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;Where Kafka EOS Applies:&lt;/strong&gt; Consuming from Kafka Topic A, performing in-memory stream transformations (Kafka Streams), and writing to Kafka Topic B within a single transactional coordinator boundary.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Where Kafka EOS Fails:&lt;/strong&gt; When a consumer calls an external HTTP endpoint (e.g., Stripe, SendGrid, or a third-party microservice). If the consumer crashes during the external network call, Kafka rolls back the read offset, triggering re-execution and duplicate outbound API calls.&lt;/li&gt;
&lt;/ul&gt;
&lt;figure&gt;&lt;img src=&quot;https://raw.githubusercontent.com/rafeuddaraj/rafes-blog-assets/refs/heads/exactly-once-delivery-myth-distributed-systems/assets/kafka-eos-boundary.svg&quot; alt=&quot;Kafka EOS Boundary Limitations&quot; loading=&quot;lazy&quot; decoding=&quot;async&quot; width=&quot;800&quot; height=&quot;400&quot;&gt;&lt;figcaption&gt;Kafka EOS Boundary Limitations&lt;/figcaption&gt;&lt;/figure&gt;
&lt;hr&gt;
&lt;h2 id=&quot;end-to-end-limitations-database-transactions-vs-external-apis&quot;&gt;End-to-End Limitations: Database Transactions vs. External APIs&lt;/h2&gt;
&lt;p&gt;You cannot atomically bind an external HTTP network request inside a relational database transaction.&lt;/p&gt;
&lt;figure&gt;&lt;img src=&quot;https://raw.githubusercontent.com/rafeuddaraj/rafes-blog-assets/refs/heads/exactly-once-delivery-myth-distributed-systems/assets/end-to-end-failure.svg&quot; alt=&quot;End-to-End Failure Matrix&quot; loading=&quot;lazy&quot; decoding=&quot;async&quot; width=&quot;800&quot; height=&quot;250&quot;&gt;&lt;figcaption&gt;End-to-End Failure Matrix&lt;/figcaption&gt;&lt;/figure&gt;
&lt;div class=&quot;expressive-code&quot;&gt;&lt;figure class=&quot;frame has-title&quot;&gt;&lt;figcaption class=&quot;header&quot;&gt;&lt;span class=&quot;title&quot;&gt;JavaScript&lt;/span&gt;&lt;/figcaption&gt;&lt;pre data-language=&quot;javascript&quot;&gt;&lt;code&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span style=&quot;--0:#8B949E&quot;&gt;// HIGHLY DANGEROUS ANTI-PATTERN: Network calls inside DB Transactions&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;await&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; db.&lt;/span&gt;&lt;span style=&quot;--0:#D2A8FF&quot;&gt;query&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;(&lt;/span&gt;&lt;span style=&quot;--0:#A5D6FF&quot;&gt;&apos;BEGIN&apos;&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;);&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;await&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; db.&lt;/span&gt;&lt;span style=&quot;--0:#D2A8FF&quot;&gt;query&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;(&lt;/span&gt;&lt;span style=&quot;--0:#A5D6FF&quot;&gt;&apos;UPDATE accounts SET balance = balance - 100 WHERE id = $1&apos;&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;, [userId]);&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;
&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span style=&quot;--0:#8B949E&quot;&gt;// If this network request hangs for 15s, the database row lock remains open!&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span style=&quot;--0:#8B949E&quot;&gt;// If DB COMMIT fails after Stripe succeeds, the customer is charged without balance deduction!&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;const&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; &lt;/span&gt;&lt;span style=&quot;--0:#79C0FF&quot;&gt;paymentRes&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; &lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;=&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; &lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;await&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; stripe.charges.&lt;/span&gt;&lt;span style=&quot;--0:#D2A8FF&quot;&gt;create&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;({ amount: &lt;/span&gt;&lt;span style=&quot;--0:#79C0FF&quot;&gt;10000&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; });&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;
&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;await&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; db.&lt;/span&gt;&lt;span style=&quot;--0:#D2A8FF&quot;&gt;query&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;(&lt;/span&gt;&lt;span style=&quot;--0:#A5D6FF&quot;&gt;&apos;COMMIT&apos;&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;);&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;/code&gt;&lt;/pre&gt;&lt;div class=&quot;copy&quot;&gt;&lt;div aria-live=&quot;polite&quot;&gt;&lt;/div&gt;&lt;button title=&quot;Copy to clipboard&quot; data-copied=&quot;Copied!&quot; data-code=&quot;// HIGHLY DANGEROUS ANTI-PATTERN: Network calls inside DB Transactionsawait db.query(&amp;#x27;BEGIN&amp;#x27;);await db.query(&amp;#x27;UPDATE accounts SET balance = balance - 100 WHERE id = $1&amp;#x27;, [userId]);// If this network request hangs for 15s, the database row lock remains open!// If DB COMMIT fails after Stripe succeeds, the customer is charged without balance deduction!const paymentRes = await stripe.charges.create({ amount: 10000 });await db.query(&amp;#x27;COMMIT&amp;#x27;);&quot;&gt;&lt;div&gt;&lt;/div&gt;&lt;/button&gt;&lt;/div&gt;&lt;/figure&gt;&lt;/div&gt;
&lt;div class=&quot;callout&quot; role=&quot;note&quot; data-type=&quot;warning&quot;&gt;
&lt;p class=&quot;callout-title&quot;&gt;Golden Rule of Database Transactions&lt;/p&gt;
&lt;p&gt;Never execute external HTTP calls or network I/O inside an open database transaction block. Latency spikes will exhaust your connection pool, and partial failures leave distributed state unrecoverable.&lt;/p&gt;
&lt;/div&gt;
&lt;hr&gt;
&lt;h2 id=&quot;real-world-architecture-payment-processing-pipeline&quot;&gt;Real-World Architecture: Payment Processing Pipeline&lt;/h2&gt;
&lt;p&gt;Below is a robust, production-grade payment architecture designed to handle network failures and duplicate events across every tier:&lt;/p&gt;
&lt;figure&gt;&lt;img src=&quot;https://raw.githubusercontent.com/rafeuddaraj/rafes-blog-assets/refs/heads/exactly-once-delivery-myth-distributed-systems/assets/payment-architecture.svg&quot; alt=&quot;Production Payment System Architecture&quot; loading=&quot;lazy&quot; decoding=&quot;async&quot; width=&quot;800&quot; height=&quot;450&quot;&gt;&lt;figcaption&gt;Production Payment System Architecture&lt;/figcaption&gt;&lt;/figure&gt;
&lt;h3 id=&quot;end-to-end-lifecycle&quot;&gt;End-to-End Lifecycle:&lt;/h3&gt;
&lt;ol&gt;
&lt;li&gt;&lt;strong&gt;Client Layer:&lt;/strong&gt; The client application submits a payment request with a unique client request ID.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Ingress &amp;#x26; DB Guard:&lt;/strong&gt; The API service writes an outbox record with an idempotency key and returns a &lt;code&gt;202 Accepted&lt;/code&gt; response.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Async Processing:&lt;/strong&gt; A background worker picks up the outbox event and initiates the external gateway call with a dedicated provider key.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Gateway Interaction:&lt;/strong&gt; The worker communicates with Stripe using the idempotency key. Network timeouts trigger safe retries using the same key.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Webhook Deduplication:&lt;/strong&gt; Incoming gateway webhooks are validated against an inbox table by event ID, preventing duplicate order completion logic.&lt;/li&gt;
&lt;/ol&gt;
&lt;hr&gt;
&lt;h2 id=&quot;effectively-once-system-architecture&quot;&gt;Effectively-Once System Architecture&lt;/h2&gt;
&lt;p&gt;High availability and consistency require defense in depth across all architectural tiers:&lt;/p&gt;
&lt;figure&gt;&lt;img src=&quot;https://raw.githubusercontent.com/rafeuddaraj/rafes-blog-assets/refs/heads/exactly-once-delivery-myth-distributed-systems/assets/reliability-layers.svg&quot; alt=&quot;Distributed Reliability Layers&quot; loading=&quot;lazy&quot; decoding=&quot;async&quot; width=&quot;800&quot; height=&quot;450&quot;&gt;&lt;figcaption&gt;Distributed Reliability Layers&lt;/figcaption&gt;&lt;/figure&gt;
&lt;ol&gt;
&lt;li&gt;&lt;strong&gt;Transport Layer (At-Least-Once):&lt;/strong&gt; Automatic retry mechanisms with timeout handling.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Traffic Smoothing Layer (Backoff &amp;#x26; Jitter):&lt;/strong&gt; Mitigating thundering herds during system degradation.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Consumer Guard (Inbox Pattern &amp;#x26; Unique Constraints):&lt;/strong&gt; Eliminating race conditions and duplicate writes at the persistence layer.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Publisher Guard (Transactional Outbox):&lt;/strong&gt; Eliminating dual-write inconsistencies between database records and message queues.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Workflow Orchestration (Saga &amp;#x26; Compensations):&lt;/strong&gt; Executing compensating transactions to gracefully roll back distributed state upon terminal errors.&lt;/li&gt;
&lt;/ol&gt;
&lt;hr&gt;
&lt;h2 id=&quot;recap-and-production-readiness-checklist&quot;&gt;Recap and Production Readiness Checklist&lt;/h2&gt;
&lt;p&gt;Keep this distributed systems failure matrix in mind when designing resilient backends:&lt;/p&gt;
&lt;figure&gt;&lt;img src=&quot;https://raw.githubusercontent.com/rafeuddaraj/rafes-blog-assets/refs/heads/exactly-once-delivery-myth-distributed-systems/assets/failure-matrix.svg&quot; alt=&quot;Distributed System Failure Matrix&quot; loading=&quot;lazy&quot; decoding=&quot;async&quot; width=&quot;800&quot; height=&quot;300&quot;&gt;&lt;figcaption&gt;Distributed System Failure Matrix&lt;/figcaption&gt;&lt;/figure&gt;
&lt;h3 id=&quot;production-readiness-checklist&quot;&gt;Production Readiness Checklist:&lt;/h3&gt;
&lt;ul class=&quot;contains-task-list&quot;&gt;
&lt;li class=&quot;task-list-item&quot;&gt;&lt;input type=&quot;checkbox&quot; disabled aria-label=&quot;Clarify Terminology: Distinguish transport semantics from processing semantics in architecture reviews.&quot;&gt; &lt;strong&gt;Clarify Terminology:&lt;/strong&gt; Distinguish transport semantics from processing semantics in architecture reviews.&lt;/li&gt;
&lt;li class=&quot;task-list-item&quot;&gt;&lt;input type=&quot;checkbox&quot; disabled aria-label=&quot;Enforce DB Uniqueness: Eliminate in-memory checks in favor of database unique constraints.&quot;&gt; &lt;strong&gt;Enforce DB Uniqueness:&lt;/strong&gt; Eliminate in-memory checks in favor of database unique constraints.&lt;/li&gt;
&lt;li class=&quot;task-list-item&quot;&gt;&lt;input type=&quot;checkbox&quot; disabled aria-label=&quot;Mandate Idempotency Keys: Require idempotency headers across all state-mutating POST endpoints.&quot;&gt; &lt;strong&gt;Mandate Idempotency Keys:&lt;/strong&gt; Require idempotency headers across all state-mutating POST endpoints.&lt;/li&gt;
&lt;li class=&quot;task-list-item&quot;&gt;&lt;input type=&quot;checkbox&quot; disabled aria-label=&quot;Implement the Inbox Pattern: Bind message ID persistence and domain mutations in a single atomic transaction.&quot;&gt; &lt;strong&gt;Implement the Inbox Pattern:&lt;/strong&gt; Bind message ID persistence and domain mutations in a single atomic transaction.&lt;/li&gt;
&lt;li class=&quot;task-list-item&quot;&gt;&lt;input type=&quot;checkbox&quot; disabled aria-label=&quot;Implement the Outbox Pattern: Decouple event publishing from transaction boundaries using transactional outbox tables.&quot;&gt; &lt;strong&gt;Implement the Outbox Pattern:&lt;/strong&gt; Decouple event publishing from transaction boundaries using transactional outbox tables.&lt;/li&gt;
&lt;li class=&quot;task-list-item&quot;&gt;&lt;input type=&quot;checkbox&quot; disabled aria-label=&quot;Isolate DB Transactions: Keep all network calls and third-party APIs outside database transaction blocks.&quot;&gt; &lt;strong&gt;Isolate DB Transactions:&lt;/strong&gt; Keep all network calls and third-party APIs outside database transaction blocks.&lt;/li&gt;
&lt;li class=&quot;task-list-item&quot;&gt;&lt;input type=&quot;checkbox&quot; disabled aria-label=&quot;Apply Backoff with Jitter: Configure exponential backoff with full jitter across all retry policies.&quot;&gt; &lt;strong&gt;Apply Backoff with Jitter:&lt;/strong&gt; Configure exponential backoff with full jitter across all retry policies.&lt;/li&gt;
&lt;li class=&quot;task-list-item&quot;&gt;&lt;input type=&quot;checkbox&quot; disabled aria-label=&quot;Deduplicate Webhooks: Validate incoming webhook event IDs against an inbox table before processing.&quot;&gt; &lt;strong&gt;Deduplicate Webhooks:&lt;/strong&gt; Validate incoming webhook event IDs against an inbox table before processing.&lt;/li&gt;
&lt;li class=&quot;task-list-item&quot;&gt;&lt;input type=&quot;checkbox&quot; disabled aria-label=&quot;Structured Distributed Tracing: Propagate trace_id, idempotency_key, and message_id across all application logs.&quot;&gt; &lt;strong&gt;Structured Distributed Tracing:&lt;/strong&gt; Propagate &lt;code&gt;trace_id&lt;/code&gt;, &lt;code&gt;idempotency_key&lt;/code&gt;, and &lt;code&gt;message_id&lt;/code&gt; across all application logs.&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;Network partitions in distributed systems are inevitable operational realities. By pairing At-Least-Once delivery with database-enforced idempotency, your system maintains bulletproof consistency regardless of network volatility.&lt;/p&gt;</content:encoded><category>System Design</category><category>Distributed Systems</category><category>System Design</category><category>Backend Architecture</category><category>Kafka</category><category>Idempotency</category><category>Microservices</category><category>Node.js</category><category>PostgreSQL</category></item><item><title>How Cursor Pagination Actually Works Under the Hood</title><link>https://www.rafeuddaraj.me/blog/cursor-pagination-under-the-hood/</link><guid isPermaLink="true">https://www.rafeuddaraj.me/blog/cursor-pagination-under-the-hood/</guid><description>An in-depth technical guide on database execution plans, B-Tree index range scans, the O(N) bottleneck of deep offsets, and production-grade opaque cursor architecture.</description><pubDate>Sun, 06 Sep 2026 02:30:00 GMT</pubDate><content:encoded>&lt;p&gt;Let us think about a familiar engineering scenario where your API design and database query feel absolutely perfect. You have a &lt;code&gt;posts&lt;/code&gt; table with 50 million records. When you load the first page, the database returns 20 rows incredibly fast, taking just 2 milliseconds.&lt;/p&gt;
&lt;div class=&quot;expressive-code&quot;&gt;&lt;style&gt;.expressive-code{font-family:var(--ec-uiFontFml);font-size:var(--ec-uiFontSize);font-weight:var(--ec-uiFontWg);line-height:var(--ec-uiLineHt);text-size-adjust:none;-webkit-text-size-adjust:none}.expressive-code *:not(:is(svg, svg *)){all:revert;box-sizing:border-box}.expressive-code pre{display:flex;margin:0;padding:0;border:var(--ec-brdWd) solid var(--ec-brdCol);border-radius:calc(var(--ec-brdRad) + var(--ec-brdWd));background:var(--ec-codeBg)}.expressive-code pre:focus-visible{outline:3px solid var(--ec-focusBrd);outline-offset:-3px}.expressive-code pre &gt; code{all:unset;display:block;flex:1 0 100%;padding:var(--ec-codePadBlk) 0;color:var(--ec-codeFg);font-family:var(--ec-codeFontFml);font-size:var(--ec-codeFontSize);font-weight:var(--ec-codeFontWg);line-height:var(--ec-codeLineHt)}.expressive-code pre{overflow-x:auto}.expressive-code pre.wrap .ec-line .code{white-space:pre-wrap;overflow-wrap:break-word;min-width:min(20ch, var(--ecMaxLine, 20ch))}.expressive-code pre.wrap .ec-line .code span.indent{white-space:pre}.expressive-code pre::-webkit-scrollbar,.expressive-code pre::-webkit-scrollbar-track{background-color:inherit;border-radius:calc(var(--ec-brdRad) + var(--ec-brdWd));border-top-left-radius:0;border-top-right-radius:0}.expressive-code pre::-webkit-scrollbar-thumb{background-color:var(--ec-sbThumbCol);border:4px solid transparent;background-clip:content-box;border-radius:10px}.expressive-code pre::-webkit-scrollbar-thumb:hover{background-color:var(--ec-sbThumbHoverCol)}.expressive-code pre::-webkit-scrollbar-corner{background:transparent}.expressive-code .ec-line{direction:ltr;unicode-bidi:isolate;display:grid;grid-template-areas:&apos;gutter code&apos;;grid-template-columns:auto 1fr;position:relative}.expressive-code .ec-line .gutter{grid-area:gutter;color:var(--ec-gtrFg)}.expressive-code .ec-line .gutter &gt; *{pointer-events:none;user-select:none;-webkit-user-select:none}.expressive-code .ec-line .gutter ~ .code{--ecLineBrdCol:var(--ec-gtrBrdCol)}.expressive-code .ec-line.highlight .gutter{color:var(--ec-gtrHlFg)}.expressive-code .ec-line .code{grid-area:code;position:relative;box-sizing:content-box;padding-inline-start:calc(var(--ecIndent, 0ch) + var(--ec-codePadInl) - var(--ecGtrBrdWd));padding-inline-end:var(--ec-codePadInl);text-indent:calc(var(--ecIndent, 0ch) * -1)}.expressive-code .ec-line .code::before,.expressive-code .ec-line .code::after,.expressive-code .ec-line .code :where(*){text-indent:0}.expressive-code .ec-line .code{--ecGtrBrdWd:var(--ec-gtrBrdWd);border-inline-start:var(--ecGtrBrdWd) solid var(--ecLineBrdCol, transparent)}.expressive-code .sr-only{position:absolute;width:1px;height:1px;padding:0;margin:-1px;overflow:hidden;clip:rect(0, 0, 0, 0);white-space:nowrap;border-width:0}.expressive-code .ec-line.mark{--tmLineBgCol:var(--ec-tm-markBg)}.expressive-code .ec-line.mark .code{--ecLineBrdCol:var(--ec-tm-markBrdCol)}.expressive-code .ec-line.ins{--tmLineBgCol:var(--ec-tm-insBg);--tmLabel:var(--ec-tm-insDiffIndContent)}.expressive-code .ec-line.ins .code{--ecLineBrdCol:var(--ec-tm-insBrdCol)}.expressive-code .ec-line.ins .code::before{color:var(--ec-tm-insDiffIndCol)}.expressive-code .ec-line.del{--tmLineBgCol:var(--ec-tm-delBg);--tmLabel:var(--ec-tm-delDiffIndContent)}.expressive-code .ec-line.del .code{--ecLineBrdCol:var(--ec-tm-delBrdCol)}.expressive-code .ec-line.del .code::before{color:var(--ec-tm-delDiffIndCol)}.expressive-code .ec-line.mark,.expressive-code .ec-line.ins,.expressive-code .ec-line.del{background:var(--tmLineBgCol)}.expressive-code .ec-line.mark .code,.expressive-code .ec-line.ins .code,.expressive-code .ec-line.del .code{--ecGtrBrdWd:var(--ec-tm-lineMarkerAccentWd)}.expressive-code .ec-line.mark .code::before,.expressive-code .ec-line.ins .code::before,.expressive-code .ec-line.del .code::before{display:block;position:absolute;left:0;box-sizing:border-box;content:var(--tmLabel, &apos; &apos;);padding-inline-start:var(--ec-tm-lineDiffIndMargLeft);text-align:center;white-space:pre}.expressive-code .ec-line.mark.tm-label .code::before,.expressive-code .ec-line.ins.tm-label .code::before,.expressive-code .ec-line.del.tm-label .code::before{background:var(--ecLineBrdCol);padding:0 calc(var(--ec-tm-lineMarkerLabelPadInl) + var(--ec-tm-lineMarkerAccentWd)) 0 var(--ec-tm-lineMarkerLabelPadInl);color:var(--ec-tm-lineMarkerLabelCol)}.expressive-code .ec-line mark{--tmInlineBgCol:var(--ec-tm-markBg);--tmInlineBrdCol:var(--ec-tm-markBrdCol)}.expressive-code .ec-line ins{--tmInlineBgCol:var(--ec-tm-insBg);--tmInlineBrdCol:var(--ec-tm-insBrdCol)}.expressive-code .ec-line del{--tmInlineBgCol:var(--ec-tm-delBg);--tmInlineBrdCol:var(--ec-tm-delBrdCol)}.expressive-code .ec-line mark,.expressive-code .ec-line ins,.expressive-code .ec-line del{all:unset;display:inline-block;position:relative;--tmBrdL:var(--ec-tm-inlMarkerBrdWd);--tmBrdR:var(--ec-tm-inlMarkerBrdWd);--tmRadL:var(--ec-tm-inlMarkerBrdRad);--tmRadR:var(--ec-tm-inlMarkerBrdRad);margin-inline:0.025rem;padding-inline:var(--ec-tm-inlMarkerPad);border-radius:var(--tmRadL) var(--tmRadR) var(--tmRadR) var(--tmRadL);background:var(--tmInlineBgCol);background-clip:padding-box}.expressive-code .ec-line mark.open-start,.expressive-code .ec-line ins.open-start,.expressive-code .ec-line del.open-start{margin-inline-start:0;padding-inline-start:0;--tmBrdL:0px;--tmRadL:0}.expressive-code .ec-line mark.open-end,.expressive-code .ec-line ins.open-end,.expressive-code .ec-line del.open-end{margin-inline-end:0;padding-inline-end:0;--tmBrdR:0px;--tmRadR:0}.expressive-code .ec-line mark::before,.expressive-code .ec-line ins::before,.expressive-code .ec-line del::before{content:&apos;&apos;;position:absolute;pointer-events:none;display:inline-block;inset:0;border-radius:var(--tmRadL) var(--tmRadR) var(--tmRadR) var(--tmRadL);border:var(--ec-tm-inlMarkerBrdWd) solid var(--tmInlineBrdCol);border-inline-width:var(--tmBrdL) var(--tmBrdR)}.expressive-code .frame{all:unset;position:relative;display:block;--header-border-radius:calc(var(--ec-brdRad) + var(--ec-brdWd));--tab-border-radius:calc(var(--ec-frm-edTabBrdRad) + var(--ec-brdWd));--button-spacing:0.4rem;--code-background:var(--ec-frm-edBg);border-radius:var(--header-border-radius);box-shadow:var(--ec-frm-frameBoxShdCssVal)}.expressive-code .frame .header{display:none;z-index:1;position:relative;border-radius:var(--header-border-radius) var(--header-border-radius) 0 0}.expressive-code .frame.has-title pre,.expressive-code .frame.has-title code,.expressive-code .frame.is-terminal pre,.expressive-code .frame.is-terminal code{border-top:none;border-top-left-radius:0;border-top-right-radius:0}.expressive-code .frame .title:empty:before{content:&apos;\a0&apos;}.expressive-code .frame.has-title:not(.is-terminal){--button-spacing:calc(1.9rem + 2 * (var(--ec-uiPadBlk) + var(--ec-frm-edActTabIndHt)))}.expressive-code .frame.has-title:not(.is-terminal) .title{position:relative;color:var(--ec-frm-edActTabFg);background:var(--ec-frm-edActTabBg);background-clip:padding-box;margin-block-start:var(--ec-frm-edTabsMargBlkStart);padding:calc(var(--ec-uiPadBlk) + var(--ec-frm-edActTabIndHt)) var(--ec-uiPadInl);border:var(--ec-brdWd) solid var(--ec-frm-edActTabBrdCol);border-radius:var(--tab-border-radius) var(--tab-border-radius) 0 0;border-bottom:none;overflow:hidden}.expressive-code .frame.has-title:not(.is-terminal) .title::after{content:&apos;&apos;;position:absolute;pointer-events:none;inset:0;border-top:var(--ec-frm-edActTabIndHt) solid var(--ec-frm-edActTabIndTopCol);border-bottom:var(--ec-frm-edActTabIndHt) solid var(--ec-frm-edActTabIndBtmCol)}.expressive-code .frame.has-title:not(.is-terminal) .header{display:flex;background:linear-gradient(to top, var(--ec-frm-edTabBarBrdBtmCol) var(--ec-brdWd), transparent var(--ec-brdWd)),linear-gradient(var(--ec-frm-edTabBarBg), var(--ec-frm-edTabBarBg));background-repeat:no-repeat;padding-inline-start:var(--ec-frm-edTabsMargInlStart)}.expressive-code .frame.has-title:not(.is-terminal) .header::before{content:&apos;&apos;;position:absolute;pointer-events:none;inset:0;border:var(--ec-brdWd) solid var(--ec-frm-edTabBarBrdCol);border-radius:inherit;border-bottom:none}.expressive-code .frame.is-terminal{--button-spacing:calc(1.9rem + var(--ec-brdWd) + 2 * var(--ec-uiPadBlk));--code-background:var(--ec-frm-trmBg)}.expressive-code .frame.is-terminal .header{display:flex;align-items:center;justify-content:center;padding-block:var(--ec-uiPadBlk);padding-block-end:calc(var(--ec-uiPadBlk) + var(--ec-brdWd));position:relative;font-weight:500;letter-spacing:0.025ch;color:var(--ec-frm-trmTtbFg);background:var(--ec-frm-trmTtbBg);border:var(--ec-brdWd) solid var(--ec-brdCol);border-bottom:none}.expressive-code .frame.is-terminal .header::before{content:&apos;&apos;;position:absolute;pointer-events:none;left:var(--ec-uiPadInl);width:2.1rem;height:0.56rem;line-height:0;background-color:var(--ec-frm-trmTtbDotsFg);opacity:var(--ec-frm-trmTtbDotsOpa);-webkit-mask-image:var(--ec-frm-trmIcon);-webkit-mask-repeat:no-repeat;mask-image:var(--ec-frm-trmIcon);mask-repeat:no-repeat}.expressive-code .frame.is-terminal .header::after{content:&apos;&apos;;position:absolute;pointer-events:none;inset:0;border-bottom:var(--ec-brdWd) solid var(--ec-frm-trmTtbBrdBtmCol)}.expressive-code .frame pre{background:var(--code-background)}.expressive-code .copy{display:flex;gap:0.25rem;flex-direction:row;position:absolute;inset-block-start:calc(var(--ec-brdWd) + var(--button-spacing));inset-inline-end:calc(var(--ec-brdWd) + var(--ec-uiPadInl) / 2)}@media (scripting: none){.expressive-code .copy{display:none}}.expressive-code .copy{direction:ltr;unicode-bidi:isolate}.expressive-code .copy button{position:relative;align-self:flex-end;margin:0;padding:0;border:none;border-radius:0.2rem;z-index:1;cursor:pointer;transition-property:opacity, background, border-color;transition-duration:0.2s;transition-timing-function:cubic-bezier(0.25, 0.46, 0.45, 0.94);width:2.5rem;height:2.5rem;background:var(--code-background);opacity:0.75}.expressive-code .copy button div{position:absolute;inset:0;border-radius:inherit;background:var(--ec-frm-inlBtnBg);opacity:var(--ec-frm-inlBtnBgIdleOpa);transition-property:inherit;transition-duration:inherit;transition-timing-function:inherit}.expressive-code .copy button::before{content:&apos;&apos;;position:absolute;pointer-events:none;inset:0;border-radius:inherit;border:var(--ec-brdWd) solid var(--ec-frm-inlBtnBrd);opacity:var(--ec-frm-inlBtnBrdOpa)}.expressive-code .copy button::after{content:&apos;&apos;;position:absolute;pointer-events:none;inset:0;background-color:var(--ec-frm-inlBtnFg);-webkit-mask-image:var(--ec-frm-copyIcon);-webkit-mask-repeat:no-repeat;mask-image:var(--ec-frm-copyIcon);mask-repeat:no-repeat;margin:0.475rem;line-height:0}.expressive-code .copy button:hover,.expressive-code .copy button:focus:focus-visible{opacity:1}.expressive-code .copy button:hover div,.expressive-code .copy button:focus:focus-visible div{opacity:var(--ec-frm-inlBtnBgHoverOrFocusOpa)}.expressive-code .copy button:active{opacity:1}.expressive-code .copy button:active div{opacity:var(--ec-frm-inlBtnBgActOpa)}.expressive-code .copy .feedback{--tooltip-arrow-size:0.35rem;--tooltip-bg:var(--ec-frm-tooltipSuccessBg);color:var(--ec-frm-tooltipSuccessFg);pointer-events:none;user-select:none;-webkit-user-select:none;position:relative;align-self:center;background-color:var(--tooltip-bg);z-index:99;padding:0.125rem 0.75rem;border-radius:0.2rem;margin-inline-end:var(--tooltip-arrow-size);opacity:0;transition-property:opacity, transform;transition-duration:0.2s;transition-timing-function:ease-in-out;transform:translate3d(0, 0.25rem, 0)}.expressive-code .copy .feedback::after{content:&apos;&apos;;position:absolute;pointer-events:none;top:calc(50% - var(--tooltip-arrow-size));inset-inline-end:calc(-2 * (var(--tooltip-arrow-size) - 0.5px));border:var(--tooltip-arrow-size) solid transparent;border-inline-start-color:var(--tooltip-bg)}.expressive-code .copy .feedback.show{opacity:1;transform:translate3d(0, 0, 0)}@media (hover: hover){.expressive-code{}.expressive-code .copy button{opacity:0;width:2rem;height:2rem}.expressive-code .frame:hover .copy button:not(:hover),.expressive-code .frame:focus-within :focus-visible ~ .copy button:not(:hover),.expressive-code .frame .copy .feedback.show ~ button:not(:hover){opacity:0.75}}.expressive-code :nth-child(1 of .ec-line) .code{padding-inline-end:calc(2rem + var(--ec-codePadInl))}:root{--ec-brdRad:0.75rem;--ec-brdWd:1.5px;--ec-brdCol:var(--code-line);--ec-codeFontFml:var(--font-code);--ec-codeFontSize:0.875rem;--ec-codeFontWg:400;--ec-codeLineHt:1.75;--ec-codePadBlk:1rem;--ec-codePadInl:1.125rem;--ec-codeBg:var(--code-bg);--ec-codeFg:#e6edf3;--ec-codeSelBg:#264f78;--ec-gtrFg:#6e7681;--ec-gtrBrdCol:#6e768133;--ec-gtrBrdWd:1.5px;--ec-gtrHlFg:#e6edf3;--ec-uiFontFml:var(--font-mono);--ec-uiFontSize:0.75rem;--ec-uiFontWg:400;--ec-uiLineHt:1.65;--ec-uiPadBlk:0.25rem;--ec-uiPadInl:1rem;--ec-uiSelBg:#6e768166;--ec-uiSelFg:#e6edf3;--ec-focusBrd:#1f6feb;--ec-sbThumbCol:#8b949e33;--ec-sbThumbHoverCol:#8b949e3d;--ec-tm-lineMarkerAccentMarg:0rem;--ec-tm-lineMarkerAccentWd:0.15rem;--ec-tm-lineMarkerLabelPadInl:0.2rem;--ec-tm-lineMarkerLabelCol:white;--ec-tm-lineDiffIndMargLeft:0.3rem;--ec-tm-inlMarkerBrdWd:1.5px;--ec-tm-inlMarkerBrdRad:0.2rem;--ec-tm-inlMarkerPad:0.15rem;--ec-tm-insDiffIndContent:&apos;+&apos;;--ec-tm-delDiffIndContent:&apos;-&apos;;--ec-tm-markBg:#264a8980;--ec-tm-markBrdCol:#5570b3d0;--ec-tm-insBg:#26561c80;--ec-tm-insBrdCol:#4e7e41d0;--ec-tm-insDiffIndCol:#7eb070d0;--ec-tm-delBg:#81322b80;--ec-tm-delBrdCol:#ae594fd0;--ec-tm-delDiffIndCol:#e68a7ed0;--ec-frm-shdCol:#0000005b;--ec-frm-frameBoxShdCssVal:none;--ec-frm-edActTabBg:var(--code-bg);--ec-frm-edActTabFg:var(--code-muted);--ec-frm-edActTabBrdCol:transparent;--ec-frm-edActTabIndHt:1.5px;--ec-frm-edActTabIndTopCol:transparent;--ec-frm-edActTabIndBtmCol:#0d1117;--ec-frm-edTabsMargInlStart:0;--ec-frm-edTabsMargBlkStart:0;--ec-frm-edTabBrdRad:0.75rem;--ec-frm-edTabBarBg:var(--code-bg);--ec-frm-edTabBarBrdCol:var(--code-line);--ec-frm-edTabBarBrdBtmCol:var(--code-line);--ec-frm-edBg:var(--code-bg);--ec-frm-trmTtbFg:var(--code-muted);--ec-frm-trmTtbDotsFg:var(--code-muted);--ec-frm-trmTtbDotsOpa:0.15;--ec-frm-trmTtbBg:var(--code-bg);--ec-frm-trmTtbBrdBtmCol:var(--code-line);--ec-frm-trmBg:var(--code-bg);--ec-frm-inlBtnBg:var(--code-ink);--ec-frm-inlBtnBgIdleOpa:0;--ec-frm-inlBtnBgHoverOrFocusOpa:0.2;--ec-frm-inlBtnBgActOpa:0.3;--ec-frm-inlBtnFg:var(--code-ink);--ec-frm-inlBtnBrd:var(--code-line);--ec-frm-inlBtnBrdOpa:0.4;--ec-frm-tooltipSuccessBg:var(--color-emerald);--ec-frm-tooltipSuccessFg:var(--color-bg);--ec-frm-copyIcon:url(&quot;data:image/svg+xml,%3Csvg%20xmlns%3D&apos;http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg&apos;%20viewBox%3D&apos;0%200%2024%2024&apos;%20fill%3D&apos;none&apos;%20stroke%3D&apos;black&apos;%20stroke-width%3D&apos;1.75&apos;%3E%3Cpath%20d%3D&apos;M3%2019a2%202%200%200%201-1-2V2a2%202%200%200%201%201-1h13a2%202%200%200%201%202%201&apos;%2F%3E%3Crect%20x%3D&apos;6&apos;%20y%3D&apos;5&apos;%20width%3D&apos;16&apos;%20height%3D&apos;18&apos;%20rx%3D&apos;1.5&apos;%20ry%3D&apos;1.5&apos;%2F%3E%3C%2Fsvg%3E&quot;);--ec-frm-trmIcon:url(&quot;data:image/svg+xml,%3Csvg%20xmlns%3D&apos;http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg&apos;%20viewBox%3D&apos;0%200%2060%2016&apos;%20preserveAspectRatio%3D&apos;xMidYMid%20meet&apos;%3E%3Ccircle%20cx%3D&apos;8&apos;%20cy%3D&apos;8&apos;%20r%3D&apos;8&apos;%2F%3E%3Ccircle%20cx%3D&apos;30&apos;%20cy%3D&apos;8&apos;%20r%3D&apos;8&apos;%2F%3E%3Ccircle%20cx%3D&apos;52&apos;%20cy%3D&apos;8&apos;%20r%3D&apos;8&apos;%2F%3E%3C%2Fsvg%3E&quot;)}.expressive-code .ec-line :where(span[style^=&apos;--&apos;]:not([class])){color:var(--0, inherit);background-color:var(--0bg, transparent);font-style:var(--0fs, inherit);font-weight:var(--0fw, inherit);text-decoration:var(--0td, inherit)}&lt;/style&gt;&lt;script type=&quot;module&quot; src=&quot;/_astro/ec.0vx5m.js&quot;&gt;&lt;/script&gt;&lt;figure class=&quot;frame has-title&quot;&gt;&lt;figcaption class=&quot;header&quot;&gt;&lt;span class=&quot;title&quot;&gt;SQL&lt;/span&gt;&lt;/figcaption&gt;&lt;pre data-language=&quot;sql&quot;&gt;&lt;code&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;SELECT&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; &lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;*&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;FROM&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; posts&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;ORDER BY&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; created_at &lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;DESC&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;LIMIT&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; &lt;/span&gt;&lt;span style=&quot;--0:#79C0FF&quot;&gt;20&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; OFFSET &lt;/span&gt;&lt;span style=&quot;--0:#79C0FF&quot;&gt;0&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;;&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;/code&gt;&lt;/pre&gt;&lt;div class=&quot;copy&quot;&gt;&lt;div aria-live=&quot;polite&quot;&gt;&lt;/div&gt;&lt;button title=&quot;Copy to clipboard&quot; data-copied=&quot;Copied!&quot; data-code=&quot;SELECT *FROM postsORDER BY created_at DESCLIMIT 20 OFFSET 0;&quot;&gt;&lt;div&gt;&lt;/div&gt;&lt;/button&gt;&lt;/div&gt;&lt;/figure&gt;&lt;/div&gt;
&lt;p&gt;This query performs brilliantly at first. But the real trouble begins when a user or an automated crawler tries to access a page located much deeper in the dataset.&lt;/p&gt;
&lt;div class=&quot;expressive-code&quot;&gt;&lt;figure class=&quot;frame has-title&quot;&gt;&lt;figcaption class=&quot;header&quot;&gt;&lt;span class=&quot;title&quot;&gt;SQL&lt;/span&gt;&lt;/figcaption&gt;&lt;pre data-language=&quot;sql&quot;&gt;&lt;code&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;SELECT&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; &lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;*&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;FROM&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; posts&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;ORDER BY&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; created_at &lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;DESC&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;LIMIT&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; &lt;/span&gt;&lt;span style=&quot;--0:#79C0FF&quot;&gt;20&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; OFFSET &lt;/span&gt;&lt;span style=&quot;--0:#79C0FF&quot;&gt;1000000&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;;&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;/code&gt;&lt;/pre&gt;&lt;div class=&quot;copy&quot;&gt;&lt;div aria-live=&quot;polite&quot;&gt;&lt;/div&gt;&lt;button title=&quot;Copy to clipboard&quot; data-copied=&quot;Copied!&quot; data-code=&quot;SELECT *FROM postsORDER BY created_at DESCLIMIT 20 OFFSET 1000000;&quot;&gt;&lt;div&gt;&lt;/div&gt;&lt;/button&gt;&lt;/div&gt;&lt;/figure&gt;&lt;/div&gt;
&lt;p&gt;Suddenly, your API latency skyrockets. The database CPU usage hits 100 percent, and requests start timing out one after another. You might naturally ask yourself why the query gets so slow as the page number increases, especially since the API is only returning 20 rows. It is highly important to understand why the database works so hard despite the &lt;code&gt;LIMIT 20&lt;/code&gt; clause, and why deep pagination remains expensive even when you have an index.&lt;/p&gt;
&lt;figure&gt;&lt;img src=&quot;https://raw.githubusercontent.com/rafeuddaraj/rafes-blog-assets/refs/heads/cursor-pagination-under-the-hood/assets/offset-vs-cursor-workload.svg&quot; alt=&quot;Page 1 vs Page 50,000 DB Workload&quot; loading=&quot;lazy&quot; decoding=&quot;async&quot; width=&quot;800&quot; height=&quot;400&quot;&gt;&lt;figcaption&gt;Page 1 vs Page 50,000 DB Workload&lt;/figcaption&gt;&lt;/figure&gt;
&lt;p&gt;We are going to investigate this performance incident by looking inside the database to see exactly how cursor pagination solves this problem.&lt;/p&gt;
&lt;h2 id=&quot;what-problem-does-pagination-actually-solve&quot;&gt;What Problem Does Pagination Actually Solve?&lt;/h2&gt;
&lt;p&gt;If you only view pagination as a frontend UI feature, you miss its core engineering purpose. You need to view it as a scalability boundary for both your database and your API. Imagine you have 50 million records in your system. If you try to return all that data at once, you will face three major crises:&lt;/p&gt;
&lt;ol&gt;
&lt;li&gt;&lt;strong&gt;Database Memory and I/O Saturation:&lt;/strong&gt; Your database buffer pool will run out of memory trying to load the entire table.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Network Bandwidth Choke:&lt;/strong&gt; Your network pipeline will jam up trying to transfer a gigabyte-sized JSON payload.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Client-side Browser Crash:&lt;/strong&gt; The client browser or mobile app will freeze and crash because it cannot handle that massive DOM or memory footprint.&lt;/li&gt;
&lt;/ol&gt;
&lt;p&gt;Instead, we break the entire dataset down and return it in smaller chunks. The real goal of pagination is to guarantee a bounded amount of work for the database and a bounded response size for the API. When we decide to return 20 records, the next obvious question is which 20 records. The answer to that specific question is exactly what creates strategies like offset and cursor pagination.&lt;/p&gt;
&lt;hr&gt;
&lt;h2 id=&quot;the-offset-pagination-mental-model&quot;&gt;The Offset Pagination Mental Model&lt;/h2&gt;
&lt;p&gt;Let us first talk about the model we are all most familiar with. With offset pagination, we tell the database exactly how many rows it needs to skip.&lt;/p&gt;
&lt;div class=&quot;expressive-code&quot;&gt;&lt;figure class=&quot;frame has-title&quot;&gt;&lt;figcaption class=&quot;header&quot;&gt;&lt;span class=&quot;title&quot;&gt;SQL&lt;/span&gt;&lt;/figcaption&gt;&lt;pre data-language=&quot;sql&quot;&gt;&lt;code&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;SELECT&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; &lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;*&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;FROM&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; posts&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;ORDER BY&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; created_at &lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;DESC&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;LIMIT&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; &lt;/span&gt;&lt;span style=&quot;--0:#79C0FF&quot;&gt;20&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; OFFSET &lt;/span&gt;&lt;span style=&quot;--0:#79C0FF&quot;&gt;10000&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;;&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;/code&gt;&lt;/pre&gt;&lt;div class=&quot;copy&quot;&gt;&lt;div aria-live=&quot;polite&quot;&gt;&lt;/div&gt;&lt;button title=&quot;Copy to clipboard&quot; data-copied=&quot;Copied!&quot; data-code=&quot;SELECT *FROM postsORDER BY created_at DESCLIMIT 20 OFFSET 10000;&quot;&gt;&lt;div&gt;&lt;/div&gt;&lt;/button&gt;&lt;/div&gt;&lt;/figure&gt;&lt;/div&gt;
&lt;p&gt;Many developers think &lt;code&gt;OFFSET 10000&lt;/code&gt; means the database just jumps or teleports directly to the 10,000th row. However, relational databases simply do not work that way.&lt;/p&gt;
&lt;figure&gt;&lt;img src=&quot;https://raw.githubusercontent.com/rafeuddaraj/rafes-blog-assets/refs/heads/cursor-pagination-under-the-hood/assets/offset-skipping-model.svg&quot; alt=&quot;The Offset Skipping Mental Model&quot; loading=&quot;lazy&quot; decoding=&quot;async&quot; width=&quot;800&quot; height=&quot;300&quot;&gt;&lt;figcaption&gt;The Offset Skipping Mental Model&lt;/figcaption&gt;&lt;/figure&gt;
&lt;p&gt;In reality, the database has to scan the previous 10,000 rows within the ordered result one by one, pull them into memory to count them, and then throw them away. After that, it starts from row 10,001 and returns the next 20 records as requested by the &lt;code&gt;LIMIT&lt;/code&gt; clause. This means the database actually had to process 10,020 rows just to give you 20 rows.&lt;/p&gt;
&lt;hr&gt;
&lt;h2 id=&quot;how-limit-and-offset-are-actually-different&quot;&gt;How LIMIT and OFFSET Are Actually Different&lt;/h2&gt;
&lt;p&gt;We need to build a very important mental model right here. &lt;code&gt;LIMIT&lt;/code&gt; and &lt;code&gt;OFFSET&lt;/code&gt; issue two completely different instructions to the database.&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;code&gt;LIMIT&lt;/code&gt; tells the database the maximum number of rows to return to the client.&lt;/li&gt;
&lt;li&gt;&lt;code&gt;OFFSET&lt;/code&gt; tells the database how many valid rows it must pass through before it even starts collecting data.&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;When you use &lt;code&gt;OFFSET 0&lt;/code&gt;, &lt;code&gt;OFFSET 100&lt;/code&gt;, and &lt;code&gt;OFFSET 1,000,000&lt;/code&gt;, the returned row count is always 20, but the total amount of work the database performs is entirely different. As the offset value grows, the database has to scan and discard more rows from memory, which makes the query progressively slower.&lt;/p&gt;
&lt;hr&gt;
&lt;h2 id=&quot;looking-inside-the-database-execution-plan&quot;&gt;Looking Inside the Database Execution Plan&lt;/h2&gt;
&lt;p&gt;A SQL query is just declarative syntax. The database engine transforms it into an internal execution plan. You can observe this actual behavior in PostgreSQL using the &lt;code&gt;EXPLAIN ANALYZE&lt;/code&gt; command.&lt;/p&gt;
&lt;div class=&quot;expressive-code&quot;&gt;&lt;figure class=&quot;frame has-title&quot;&gt;&lt;figcaption class=&quot;header&quot;&gt;&lt;span class=&quot;title&quot;&gt;SQL&lt;/span&gt;&lt;/figcaption&gt;&lt;pre data-language=&quot;sql&quot;&gt;&lt;code&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;EXPLAIN ANALYZE&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;SELECT&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; &lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;*&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;FROM&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; posts&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;ORDER BY&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; created_at &lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;DESC&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;LIMIT&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; &lt;/span&gt;&lt;span style=&quot;--0:#79C0FF&quot;&gt;20&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; OFFSET &lt;/span&gt;&lt;span style=&quot;--0:#79C0FF&quot;&gt;100000&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;;&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;/code&gt;&lt;/pre&gt;&lt;div class=&quot;copy&quot;&gt;&lt;div aria-live=&quot;polite&quot;&gt;&lt;/div&gt;&lt;button title=&quot;Copy to clipboard&quot; data-copied=&quot;Copied!&quot; data-code=&quot;EXPLAIN ANALYZESELECT *FROM postsORDER BY created_at DESCLIMIT 20 OFFSET 100000;&quot;&gt;&lt;div&gt;&lt;/div&gt;&lt;/button&gt;&lt;/div&gt;&lt;/figure&gt;&lt;/div&gt;
&lt;p&gt;In this execution plan, the query planner follows a specific pipeline:&lt;/p&gt;
&lt;figure&gt;&lt;img src=&quot;https://raw.githubusercontent.com/rafeuddaraj/rafes-blog-assets/refs/heads/cursor-pagination-under-the-hood/assets/db-execution-pipeline.svg&quot; alt=&quot;Database Execution Pipeline&quot; loading=&quot;lazy&quot; decoding=&quot;async&quot; width=&quot;800&quot; height=&quot;400&quot;&gt;&lt;figcaption&gt;Database Execution Pipeline&lt;/figcaption&gt;&lt;/figure&gt;
&lt;ol&gt;
&lt;li&gt;&lt;strong&gt;Access Path Selection:&lt;/strong&gt; The planner decides whether to perform an index scan or a full table scan.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Tuple Retrieval:&lt;/strong&gt; It fetches 100,020 tuples from the disk or buffer cache using the index.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Traverse and Discard:&lt;/strong&gt; It counts the first 100,000 tuples in memory and throws them away.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Limit Slice:&lt;/strong&gt; It collects the remaining 20 tuples to build the final output.&lt;/li&gt;
&lt;/ol&gt;
&lt;p&gt;When we look at the &lt;code&gt;EXPLAIN ANALYZE&lt;/code&gt; output, it becomes clear that the database spent a massive amount of CPU cycles pulling disk pages into memory just to throw that unnecessary data away.&lt;/p&gt;
&lt;hr&gt;
&lt;h2 id=&quot;does-an-index-solve-the-offset-problem&quot;&gt;Does an Index Solve the OFFSET Problem?&lt;/h2&gt;
&lt;p&gt;This is a very common misconception in backend engineering. Many developers assume that creating an index on the &lt;code&gt;created_at&lt;/code&gt; column will permanently solve the deep pagination problem.&lt;/p&gt;
&lt;div class=&quot;expressive-code&quot;&gt;&lt;figure class=&quot;frame has-title&quot;&gt;&lt;figcaption class=&quot;header&quot;&gt;&lt;span class=&quot;title&quot;&gt;SQL&lt;/span&gt;&lt;/figcaption&gt;&lt;pre data-language=&quot;sql&quot;&gt;&lt;code&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;CREATE&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; &lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;INDEX&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; &lt;/span&gt;&lt;span style=&quot;--0:#D2A8FF&quot;&gt;idx_posts_created_at&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;ON&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; posts(created_at &lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;DESC&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;);&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;/code&gt;&lt;/pre&gt;&lt;div class=&quot;copy&quot;&gt;&lt;div aria-live=&quot;polite&quot;&gt;&lt;/div&gt;&lt;button title=&quot;Copy to clipboard&quot; data-copied=&quot;Copied!&quot; data-code=&quot;CREATE INDEX idx_posts_created_atON posts(created_at DESC);&quot;&gt;&lt;div&gt;&lt;/div&gt;&lt;/button&gt;&lt;/div&gt;&lt;/figure&gt;&lt;/div&gt;
&lt;p&gt;Using an index means the database might avoid a full sequential table scan, as it can pull ordered entries directly from the index tree. However, the logical requirement of the &lt;code&gt;OFFSET&lt;/code&gt; clause does not just disappear.&lt;/p&gt;
&lt;p&gt;To reach the target position, the database still has to traverse every single preceding entry through the index leaf pages. As a result, the query execution time continues to grow linearly even with an index in place.&lt;/p&gt;
&lt;div class=&quot;callout&quot; role=&quot;note&quot; data-type=&quot;warning&quot;&gt;
&lt;p class=&quot;callout-title&quot;&gt;The O(N) Pagination Trap&lt;/p&gt;
&lt;p&gt;Even though an index scan is fast, the database still has to read N index entries to reach &lt;code&gt;OFFSET N&lt;/code&gt;. Offset-based pagination fundamentally creates O(N) time complexity, which causes catastrophic latency on large datasets.&lt;/p&gt;
&lt;/div&gt;
&lt;hr&gt;
&lt;h2 id=&quot;why-deep-offset-becomes-a-production-problem&quot;&gt;Why Deep OFFSET Becomes a Production Problem&lt;/h2&gt;
&lt;p&gt;Think about a realistic production traffic scenario. A regular user will rarely trigger a deep pagination query. But things spiral out of control when search engine bots, scrapers, or thousands of concurrent users send requests for deep pages.&lt;/p&gt;
&lt;figure&gt;&lt;img src=&quot;https://raw.githubusercontent.com/rafeuddaraj/rafes-blog-assets/refs/heads/cursor-pagination-under-the-hood/assets/concurrent-deep-offset.svg&quot; alt=&quot;Concurrent Deep Offset Workload&quot; loading=&quot;lazy&quot; decoding=&quot;async&quot; width=&quot;800&quot; height=&quot;400&quot;&gt;&lt;figcaption&gt;Concurrent Deep Offset Workload&lt;/figcaption&gt;&lt;/figure&gt;
&lt;p&gt;Multiple users requesting deep offsets creates a continuous heavy workload on the database engine. This leads to several failures:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;Database CPU usage hits 100 percent.&lt;/li&gt;
&lt;li&gt;The database connection pool gets completely exhausted.&lt;/li&gt;
&lt;li&gt;New lightweight requests get stuck in the queue, causing cascading latency.&lt;/li&gt;
&lt;li&gt;Clients experience timeouts and send automatic retries, which creates a death spiral of even more system load.&lt;/li&gt;
&lt;/ul&gt;
&lt;hr&gt;
&lt;h2 id=&quot;the-entry-point-of-cursor-pagination&quot;&gt;The Entry Point of Cursor Pagination&lt;/h2&gt;
&lt;p&gt;The concept of cursor pagination comes directly from this fundamental limitation of offset. If we stop telling the database how many rows to skip and instead tell it where we left off, the database workload changes completely.&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;Offset Approach:&lt;/strong&gt; Pass 10,000 rows and give me the next 20 rows. (The database has to look at 10,020 rows).&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Cursor Approach:&lt;/strong&gt; I have seen up to this specific record, so give me the next 20 rows after it. (The database starts right at that exact point and only reads 20 rows).&lt;/li&gt;
&lt;/ul&gt;
&lt;figure&gt;&lt;img src=&quot;https://raw.githubusercontent.com/rafeuddaraj/rafes-blog-assets/refs/heads/cursor-pagination-under-the-hood/assets/cursor-boundary-scan.svg&quot; alt=&quot;Cursor Boundary Range Scan&quot; loading=&quot;lazy&quot; decoding=&quot;async&quot; width=&quot;800&quot; height=&quot;300&quot;&gt;&lt;figcaption&gt;Cursor Boundary Range Scan&lt;/figcaption&gt;&lt;/figure&gt;
&lt;p&gt;This is the core architectural transition of cursor pagination. Instead of forcing the database to scan and discard thousands of records, we provide it with a known boundary or starting point.&lt;/p&gt;
&lt;hr&gt;
&lt;h2 id=&quot;api-cursor-vs-database-cursor&quot;&gt;API Cursor vs. Database Cursor&lt;/h2&gt;
&lt;p&gt;We need to clear up some terminology confusion right here. The cursor used in API pagination is not the same thing as the internal cursor of a database engine.&lt;/p&gt;
&lt;ol&gt;
&lt;li&gt;&lt;strong&gt;API Cursor:&lt;/strong&gt; This is a stateless token that represents the current pagination position, passed back and forth between the client and the server.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Database Cursor (PL/pgSQL / SQL Cursor):&lt;/strong&gt; This is a stateful connection-bound pointer kept open in the database server memory. Keeping this open for a long time will exhaust your connection pool.&lt;/li&gt;
&lt;/ol&gt;
&lt;p&gt;When designing web applications or distributed APIs, we always use the stateless API cursor.&lt;/p&gt;
&lt;hr&gt;
&lt;h2 id=&quot;where-keyset-pagination-comes-in&quot;&gt;Where Keyset Pagination Comes In&lt;/h2&gt;
&lt;p&gt;The terms keyset pagination and cursor pagination are often used interchangeably, but there is a subtle structural difference between them.&lt;/p&gt;
&lt;div class=&quot;expressive-code&quot;&gt;&lt;figure class=&quot;frame has-title&quot;&gt;&lt;figcaption class=&quot;header&quot;&gt;&lt;span class=&quot;title&quot;&gt;SQL&lt;/span&gt;&lt;/figcaption&gt;&lt;pre data-language=&quot;sql&quot;&gt;&lt;code&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;SELECT&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; &lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;*&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;FROM&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; posts&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;WHERE&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; id &lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;&amp;#x3C;&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; :lastId&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;ORDER BY&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; id &lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;DESC&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;LIMIT&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; &lt;/span&gt;&lt;span style=&quot;--0:#79C0FF&quot;&gt;20&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;;&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;/code&gt;&lt;/pre&gt;&lt;div class=&quot;copy&quot;&gt;&lt;div aria-live=&quot;polite&quot;&gt;&lt;/div&gt;&lt;button title=&quot;Copy to clipboard&quot; data-copied=&quot;Copied!&quot; data-code=&quot;SELECT *FROM postsWHERE id &lt; :lastIdORDER BY id DESCLIMIT 20;&quot;&gt;&lt;div&gt;&lt;/div&gt;&lt;/button&gt;&lt;/div&gt;&lt;/figure&gt;&lt;/div&gt;
&lt;p&gt;Keyset pagination is the database-level query filtering strategy, where the sorting column value acts as a boundary in the &lt;code&gt;WHERE&lt;/code&gt; clause. Cursor pagination is the API-level transport mechanism that packages these keyset values into a secure, encoded token to send to the client.&lt;/p&gt;
&lt;hr&gt;
&lt;h2 id=&quot;why-stable-ordering-is-the-core-requirement-of-cursor-pagination&quot;&gt;Why Stable Ordering is the Core Requirement of Cursor Pagination&lt;/h2&gt;
&lt;p&gt;The most fundamental requirement for cursor pagination to work correctly is deterministic and stable ordering. Sorting by a single non-unique column can lead to a disaster.&lt;/p&gt;
&lt;div class=&quot;expressive-code&quot;&gt;&lt;figure class=&quot;frame has-title&quot;&gt;&lt;figcaption class=&quot;header&quot;&gt;&lt;span class=&quot;title&quot;&gt;SQL&lt;/span&gt;&lt;/figcaption&gt;&lt;pre data-language=&quot;sql&quot;&gt;&lt;code&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;ORDER BY&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; created_at &lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;DESC&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;;&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;/code&gt;&lt;/pre&gt;&lt;div class=&quot;copy&quot;&gt;&lt;div aria-live=&quot;polite&quot;&gt;&lt;/div&gt;&lt;button title=&quot;Copy to clipboard&quot; data-copied=&quot;Copied!&quot; data-code=&quot;ORDER BY created_at DESC;&quot;&gt;&lt;div&gt;&lt;/div&gt;&lt;/button&gt;&lt;/div&gt;&lt;/figure&gt;&lt;/div&gt;
&lt;p&gt;Imagine three different posts inserted into the database at the exact same second (10:00:00). Because their &lt;code&gt;created_at&lt;/code&gt; timestamps are identical, they have no specific internal order to the database engine.&lt;/p&gt;
&lt;figure&gt;&lt;img src=&quot;https://raw.githubusercontent.com/rafeuddaraj/rafes-blog-assets/refs/heads/cursor-pagination-under-the-hood/assets/ambiguous-vs-deterministic-ordering.svg&quot; alt=&quot;Ambiguous vs Deterministic Ordering&quot; loading=&quot;lazy&quot; decoding=&quot;async&quot; width=&quot;800&quot; height=&quot;350&quot;&gt;&lt;figcaption&gt;Ambiguous vs Deterministic Ordering&lt;/figcaption&gt;&lt;/figure&gt;
&lt;p&gt;The database gives no guarantee about which two records will appear on the first page and which one will end up on the second page. This means some records might show up as duplicates, while others might be skipped forever. To solve this problem, you must always use a unique column as a tie-breaker.&lt;/p&gt;
&lt;div class=&quot;expressive-code&quot;&gt;&lt;figure class=&quot;frame has-title&quot;&gt;&lt;figcaption class=&quot;header&quot;&gt;&lt;span class=&quot;title&quot;&gt;SQL&lt;/span&gt;&lt;/figcaption&gt;&lt;pre data-language=&quot;sql&quot;&gt;&lt;code&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;ORDER BY&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; created_at &lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;DESC&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;, id &lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;DESC&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;;&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;/code&gt;&lt;/pre&gt;&lt;div class=&quot;copy&quot;&gt;&lt;div aria-live=&quot;polite&quot;&gt;&lt;/div&gt;&lt;button title=&quot;Copy to clipboard&quot; data-copied=&quot;Copied!&quot; data-code=&quot;ORDER BY created_at DESC, id DESC;&quot;&gt;&lt;div&gt;&lt;/div&gt;&lt;/button&gt;&lt;/div&gt;&lt;/figure&gt;&lt;/div&gt;
&lt;p&gt;Here, the &lt;code&gt;id&lt;/code&gt; column guarantees that the position of every single row is completely unique and deterministic.&lt;/p&gt;
&lt;hr&gt;
&lt;h2 id=&quot;composite-cursor-and-row-value-comparison&quot;&gt;Composite Cursor and Row Value Comparison&lt;/h2&gt;
&lt;p&gt;When you sort your pagination by multiple columns, like &lt;code&gt;created_at&lt;/code&gt; and &lt;code&gt;id&lt;/code&gt;, your cursor needs to include both of those values. This is called a composite cursor.&lt;/p&gt;
&lt;div class=&quot;expressive-code&quot;&gt;&lt;figure class=&quot;frame has-title&quot;&gt;&lt;figcaption class=&quot;header&quot;&gt;&lt;span class=&quot;title&quot;&gt;SQL&lt;/span&gt;&lt;/figcaption&gt;&lt;pre data-language=&quot;sql&quot;&gt;&lt;code&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;SELECT&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; &lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;*&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;FROM&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; posts&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;WHERE&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; (created_at, id) &lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;&amp;#x3C;&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; (:createdAt, :id)&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;ORDER BY&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; created_at &lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;DESC&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;, id &lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;DESC&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;LIMIT&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; &lt;/span&gt;&lt;span style=&quot;--0:#79C0FF&quot;&gt;20&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;;&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;/code&gt;&lt;/pre&gt;&lt;div class=&quot;copy&quot;&gt;&lt;div aria-live=&quot;polite&quot;&gt;&lt;/div&gt;&lt;button title=&quot;Copy to clipboard&quot; data-copied=&quot;Copied!&quot; data-code=&quot;SELECT *FROM postsWHERE (created_at, id) &lt; (:createdAt, :id)ORDER BY created_at DESC, id DESCLIMIT 20;&quot;&gt;&lt;div&gt;&lt;/div&gt;&lt;/button&gt;&lt;/div&gt;&lt;/figure&gt;&lt;/div&gt;
&lt;p&gt;Modern relational databases like PostgreSQL and MySQL 8+ support row value comparison, also known as tuple comparison, incredibly well. The database compares the &lt;code&gt;created_at&lt;/code&gt; values first. If two rows share the same &lt;code&gt;created_at&lt;/code&gt; time, only then does it compare the &lt;code&gt;id&lt;/code&gt; values to filter the next records.&lt;/p&gt;
&lt;p&gt;For database engines that lack tuple syntax support, you can write the equivalent logic like this:&lt;/p&gt;
&lt;div class=&quot;expressive-code&quot;&gt;&lt;figure class=&quot;frame has-title&quot;&gt;&lt;figcaption class=&quot;header&quot;&gt;&lt;span class=&quot;title&quot;&gt;SQL&lt;/span&gt;&lt;/figcaption&gt;&lt;pre data-language=&quot;sql&quot;&gt;&lt;code&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;SELECT&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; &lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;*&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;FROM&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; posts&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;WHERE&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; created_at &lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;&amp;#x3C;&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; :createdAt&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span class=&quot;indent&quot;&gt;   &lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;OR&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; (created_at &lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;=&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; :createdAt &lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;AND&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; id &lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;&amp;#x3C;&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; :id)&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;ORDER BY&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; created_at &lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;DESC&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;, id &lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;DESC&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;LIMIT&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; &lt;/span&gt;&lt;span style=&quot;--0:#79C0FF&quot;&gt;20&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;;&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;/code&gt;&lt;/pre&gt;&lt;div class=&quot;copy&quot;&gt;&lt;div aria-live=&quot;polite&quot;&gt;&lt;/div&gt;&lt;button title=&quot;Copy to clipboard&quot; data-copied=&quot;Copied!&quot; data-code=&quot;SELECT *FROM postsWHERE created_at &lt; :createdAt   OR (created_at = :createdAt AND id &lt; :id)ORDER BY created_at DESC, id DESCLIMIT 20;&quot;&gt;&lt;div&gt;&lt;/div&gt;&lt;/button&gt;&lt;/div&gt;&lt;/figure&gt;&lt;/div&gt;
&lt;div class=&quot;callout&quot; role=&quot;note&quot; data-type=&quot;tip&quot;&gt;
&lt;p class=&quot;callout-title&quot;&gt;Row Value Syntax Support&lt;/p&gt;
&lt;p&gt;Row value comparison &lt;code&gt;(A, B) &amp;#x3C; (X, Y)&lt;/code&gt; keeps your code clean and allows the SQL query optimizer to use your composite index perfectly.&lt;/p&gt;
&lt;/div&gt;
&lt;hr&gt;
&lt;h2 id=&quot;why-a-composite-index-is-critical-here&quot;&gt;Why a Composite Index is Critical Here&lt;/h2&gt;
&lt;p&gt;Running a keyset query without the right index will trigger a full table scan instead of giving you a performance boost. You must create a composite index that aligns perfectly with the filtering and ordering of your cursor query.&lt;/p&gt;
&lt;div class=&quot;expressive-code&quot;&gt;&lt;figure class=&quot;frame has-title&quot;&gt;&lt;figcaption class=&quot;header&quot;&gt;&lt;span class=&quot;title&quot;&gt;SQL&lt;/span&gt;&lt;/figcaption&gt;&lt;pre data-language=&quot;sql&quot;&gt;&lt;code&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;CREATE&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; &lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;INDEX&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; &lt;/span&gt;&lt;span style=&quot;--0:#D2A8FF&quot;&gt;idx_posts_cursor&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;ON&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; posts(created_at &lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;DESC&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;, id &lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;DESC&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;);&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;/code&gt;&lt;/pre&gt;&lt;div class=&quot;copy&quot;&gt;&lt;div aria-live=&quot;polite&quot;&gt;&lt;/div&gt;&lt;button title=&quot;Copy to clipboard&quot; data-copied=&quot;Copied!&quot; data-code=&quot;CREATE INDEX idx_posts_cursorON posts(created_at DESC, id DESC);&quot;&gt;&lt;div&gt;&lt;/div&gt;&lt;/button&gt;&lt;/div&gt;&lt;/figure&gt;&lt;/div&gt;
&lt;p&gt;Because of this index, the database engine never has to sort data in memory, and it never has to discard any rows. The engine jumps straight to the exact boundary point on the index tree and picks up the next 20 entries.&lt;/p&gt;
&lt;hr&gt;
&lt;h2 id=&quot;the-connection-between-b-trees-and-cursor-pagination&quot;&gt;The Connection Between B-Trees and Cursor Pagination&lt;/h2&gt;
&lt;p&gt;A relational database B-Tree index is essentially a balanced tree structure that always keeps your data sorted.&lt;/p&gt;
&lt;figure&gt;&lt;img src=&quot;https://raw.githubusercontent.com/rafeuddaraj/rafes-blog-assets/refs/heads/cursor-pagination-under-the-hood/assets/composite-btree-index.svg&quot; alt=&quot;Composite B-Tree Traversal&quot; loading=&quot;lazy&quot; decoding=&quot;async&quot; width=&quot;800&quot; height=&quot;400&quot;&gt;&lt;figcaption&gt;Composite B-Tree Traversal&lt;/figcaption&gt;&lt;/figure&gt;
&lt;p&gt;Notice how a cursor query executes inside a B-Tree index:&lt;/p&gt;
&lt;ol&gt;
&lt;li&gt;&lt;strong&gt;Tree Seek (O(log N)):&lt;/strong&gt; The database moves down from the root node like a binary search to find the exact leaf node matching the cursor value.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Sequential Leaf Scan (O(K)):&lt;/strong&gt; The leaf nodes are connected to each other like a doubly linked list. The database simply follows the forward pointer and reads exactly K rows based on your limit.&lt;/li&gt;
&lt;/ol&gt;
&lt;p&gt;Since K is a fixed limit like 20, the query performance stays completely flat, operating near O(1), no matter if your table has ten thousand or ten million rows.&lt;/p&gt;
&lt;hr&gt;
&lt;h2 id=&quot;concurrent-insert-and-pagination-drift&quot;&gt;Concurrent INSERT and Pagination Drift&lt;/h2&gt;
&lt;p&gt;The most severe data consistency issue with offset pagination is pagination drift, also known as data shifting.&lt;/p&gt;
&lt;figure&gt;&lt;img src=&quot;https://raw.githubusercontent.com/rafeuddaraj/rafes-blog-assets/refs/heads/cursor-pagination-under-the-hood/assets/pagination-drift-insert.svg&quot; alt=&quot;Pagination Drift from Concurrent Insert&quot; loading=&quot;lazy&quot; decoding=&quot;async&quot; width=&quot;800&quot; height=&quot;350&quot;&gt;&lt;figcaption&gt;Pagination Drift from Concurrent Insert&lt;/figcaption&gt;&lt;/figure&gt;
&lt;p&gt;Suppose a user loads page 1 and sees Post A and Post B. At that exact moment, another user inserts a new post into the system.&lt;/p&gt;
&lt;p&gt;Now, when the first user sends a &lt;code&gt;LIMIT 2 OFFSET 2&lt;/code&gt; request to view page 2, the database shifts the entire dataset backward because of that new row. As a result, the user sees Post B again on page 2 as a duplicate record. Similarly, if a row gets deleted, a different record might be skipped entirely.&lt;/p&gt;
&lt;p&gt;Cursor pagination is completely immune to this drift problem. It does not rely on imaginary row numbers; instead, it reads data by locking onto the boundary point of a specific data value.&lt;/p&gt;
&lt;hr&gt;
&lt;h2 id=&quot;immutable-vs-mutable-ordering&quot;&gt;Immutable vs. Mutable Ordering&lt;/h2&gt;
&lt;p&gt;You should ideally pick columns that never change, like &lt;code&gt;id&lt;/code&gt; or &lt;code&gt;created_at&lt;/code&gt;, for cursor pagination. But if you sort by a mutable column like &lt;code&gt;updated_at&lt;/code&gt;, you can fall into a specific concurrency trap:&lt;/p&gt;
&lt;div class=&quot;expressive-code&quot;&gt;&lt;figure class=&quot;frame has-title&quot;&gt;&lt;figcaption class=&quot;header&quot;&gt;&lt;span class=&quot;title&quot;&gt;SQL&lt;/span&gt;&lt;/figcaption&gt;&lt;pre data-language=&quot;sql&quot;&gt;&lt;code&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;ORDER BY&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; updated_at &lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;DESC&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;, id &lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;DESC&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;;&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;/code&gt;&lt;/pre&gt;&lt;div class=&quot;copy&quot;&gt;&lt;div aria-live=&quot;polite&quot;&gt;&lt;/div&gt;&lt;button title=&quot;Copy to clipboard&quot; data-copied=&quot;Copied!&quot; data-code=&quot;ORDER BY updated_at DESC, id DESC;&quot;&gt;&lt;div&gt;&lt;/div&gt;&lt;/button&gt;&lt;/div&gt;&lt;/figure&gt;&lt;/div&gt;
&lt;figure&gt;&lt;img src=&quot;https://raw.githubusercontent.com/rafeuddaraj/rafes-blog-assets/refs/heads/cursor-pagination-under-the-hood/assets/mutable-ordering-shift.svg&quot; alt=&quot;Mutable Ordering Shift&quot; loading=&quot;lazy&quot; decoding=&quot;async&quot; width=&quot;800&quot; height=&quot;350&quot;&gt;&lt;figcaption&gt;Mutable Ordering Shift&lt;/figcaption&gt;&lt;/figure&gt;
&lt;p&gt;Imagine a user reads page 1 and stops at Record B. Meanwhile, Record C, which was on page 3, gets updated. Its &lt;code&gt;updated_at&lt;/code&gt; timestamp increases, pushing it to the top above page 1. Now, when the user requests the next page starting from Record B, the database will return Record D and everything after it. As a result, the user will skip Record C completely.&lt;/p&gt;
&lt;div class=&quot;callout&quot; role=&quot;note&quot; data-type=&quot;note&quot;&gt;
&lt;p class=&quot;callout-title&quot;&gt;Mutable Column Strategy&lt;/p&gt;
&lt;p&gt;If you have to paginate on a changing column, you need to consider a real-time data sync strategy for clients or implement snapshot isolation.&lt;/p&gt;
&lt;/div&gt;
&lt;hr&gt;
&lt;h2 id=&quot;how-cursors-work-in-an-api-opaque-cursors&quot;&gt;How Cursors Work in an API (Opaque Cursors)&lt;/h2&gt;
&lt;p&gt;In a production-grade system, you should never expose your internal database schema or raw column values directly to the client.&lt;/p&gt;
&lt;div class=&quot;expressive-code&quot;&gt;&lt;figure class=&quot;frame has-title&quot;&gt;&lt;figcaption class=&quot;header&quot;&gt;&lt;span class=&quot;title&quot;&gt;JSON&lt;/span&gt;&lt;/figcaption&gt;&lt;pre data-language=&quot;json&quot;&gt;&lt;code&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;{&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span class=&quot;indent&quot;&gt;  &lt;/span&gt;&lt;span style=&quot;--0:#7EE787&quot;&gt;&quot;created_at&quot;&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;: &lt;/span&gt;&lt;span style=&quot;--0:#A5D6FF&quot;&gt;&quot;2026-09-06T01:30:00Z&quot;&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;,&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span class=&quot;indent&quot;&gt;  &lt;/span&gt;&lt;span style=&quot;--0:#7EE787&quot;&gt;&quot;id&quot;&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;: &lt;/span&gt;&lt;span style=&quot;--0:#79C0FF&quot;&gt;9842&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;}&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;/code&gt;&lt;/pre&gt;&lt;div class=&quot;copy&quot;&gt;&lt;div aria-live=&quot;polite&quot;&gt;&lt;/div&gt;&lt;button title=&quot;Copy to clipboard&quot; data-copied=&quot;Copied!&quot; data-code=&quot;{  &amp;#x22;created_at&amp;#x22;: &amp;#x22;2026-09-06T01:30:00Z&amp;#x22;,  &amp;#x22;id&amp;#x22;: 9842}&quot;&gt;&lt;div&gt;&lt;/div&gt;&lt;/button&gt;&lt;/div&gt;&lt;/figure&gt;&lt;/div&gt;
&lt;p&gt;Instead of sending raw data, the server encodes it into an opaque token to send to the client:&lt;/p&gt;
&lt;figure&gt;&lt;img src=&quot;https://raw.githubusercontent.com/rafeuddaraj/rafes-blog-assets/refs/heads/cursor-pagination-under-the-hood/assets/opaque-cursor-architecture.svg&quot; alt=&quot;Opaque Cursor Architecture&quot; loading=&quot;lazy&quot; decoding=&quot;async&quot; width=&quot;800&quot; height=&quot;250&quot;&gt;&lt;figcaption&gt;Opaque Cursor Architecture&lt;/figcaption&gt;&lt;/figure&gt;
&lt;div class=&quot;expressive-code&quot;&gt;&lt;figure class=&quot;frame has-title&quot;&gt;&lt;figcaption class=&quot;header&quot;&gt;&lt;span class=&quot;title&quot;&gt;Text&lt;/span&gt;&lt;/figcaption&gt;&lt;pre data-language=&quot;text&quot;&gt;&lt;code&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span style=&quot;--0:#e6edf3&quot;&gt;GET /api/v1/posts?cursor=eyJjcmVhdGVkX2F0IjoiMjAyNi0wOS0wNlQwMTozMDowMFoiLCJpZCI6OTg0Mn0=&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;/code&gt;&lt;/pre&gt;&lt;div class=&quot;copy&quot;&gt;&lt;div aria-live=&quot;polite&quot;&gt;&lt;/div&gt;&lt;button title=&quot;Copy to clipboard&quot; data-copied=&quot;Copied!&quot; data-code=&quot;GET /api/v1/posts?cursor=eyJjcmVhdGVkX2F0IjoiMjAyNi0wOS0wNlQwMTozMDowMFoiLCJpZCI6OTg0Mn0=&quot;&gt;&lt;div&gt;&lt;/div&gt;&lt;/button&gt;&lt;/div&gt;&lt;/figure&gt;&lt;/div&gt;
&lt;p&gt;When the API server receives the request, it decodes and validates the token to build the internal SQL query. This ensures that if you change your database schema or pagination logic later, your public API contract will not break.&lt;/p&gt;
&lt;div class=&quot;callout&quot; role=&quot;note&quot; data-type=&quot;note&quot;&gt;
&lt;p class=&quot;callout-title&quot;&gt;Security Note&lt;/p&gt;
&lt;p&gt;Base64 is an encoding mechanism, not encryption. Anyone can decode the token and read the values inside. To prevent token tampering or security risks, the best practice is to sign the cursor with an HMAC or fully encrypt it.&lt;/p&gt;
&lt;/div&gt;
&lt;hr&gt;
&lt;h2 id=&quot;how-to-figure-out-hasnextpage&quot;&gt;How to Figure Out hasNextPage&lt;/h2&gt;
&lt;p&gt;Many developers run a separate &lt;code&gt;COUNT(*)&lt;/code&gt; query just to tell the client if there is a next page. However, running a count query on a massive table is highly expensive. The smartest solution for this is the &lt;code&gt;LIMIT + 1&lt;/code&gt; trick.&lt;/p&gt;
&lt;figure&gt;&lt;img src=&quot;https://raw.githubusercontent.com/rafeuddaraj/rafes-blog-assets/refs/heads/cursor-pagination-under-the-hood/assets/limit-plus-one-hasnextpage.svg&quot; alt=&quot;LIMIT Plus One Trick for hasNextPage&quot; loading=&quot;lazy&quot; decoding=&quot;async&quot; width=&quot;800&quot; height=&quot;350&quot;&gt;&lt;figcaption&gt;LIMIT Plus One Trick for hasNextPage&lt;/figcaption&gt;&lt;/figure&gt;
&lt;p&gt;If your page size is 20, you simply query 21 records from the database using &lt;code&gt;LIMIT 21&lt;/code&gt;.&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;If the database returns exactly 21 records, it means there is still more data left, so &lt;code&gt;hasNextPage = true&lt;/code&gt;. The server removes that 21st record from the response, sends the first 20 records to the client, and uses the data from the 20th record to generate the &lt;code&gt;next_cursor&lt;/code&gt;.&lt;/li&gt;
&lt;li&gt;If the database returns 20 records or fewer, then &lt;code&gt;hasNextPage = false&lt;/code&gt; and &lt;code&gt;next_cursor = null&lt;/code&gt;.&lt;/li&gt;
&lt;/ul&gt;
&lt;hr&gt;
&lt;h2 id=&quot;forward-and-backward-pagination&quot;&gt;Forward and Backward Pagination&lt;/h2&gt;
&lt;p&gt;A complete API needs to let users go backward to previous pages, not just forward.&lt;/p&gt;
&lt;figure&gt;&lt;img src=&quot;https://raw.githubusercontent.com/rafeuddaraj/rafes-blog-assets/refs/heads/cursor-pagination-under-the-hood/assets/forward-backward-pagination.svg&quot; alt=&quot;Forward and Backward Traversal&quot; loading=&quot;lazy&quot; decoding=&quot;async&quot; width=&quot;800&quot; height=&quot;250&quot;&gt;&lt;figcaption&gt;Forward and Backward Traversal&lt;/figcaption&gt;&lt;/figure&gt;
&lt;p&gt;To support this, the API response provides two cursors: &lt;code&gt;next_cursor&lt;/code&gt; and &lt;code&gt;prev_cursor&lt;/code&gt;.&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;
&lt;p&gt;&lt;strong&gt;Forward Query:&lt;/strong&gt;&lt;/p&gt;
&lt;div class=&quot;expressive-code&quot;&gt;&lt;figure class=&quot;frame has-title&quot;&gt;&lt;figcaption class=&quot;header&quot;&gt;&lt;span class=&quot;title&quot;&gt;SQL&lt;/span&gt;&lt;/figcaption&gt;&lt;pre data-language=&quot;sql&quot;&gt;&lt;code&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;WHERE&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; (created_at, id) &lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;&amp;#x3C;&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; (:createdAt, :id)&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;ORDER BY&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; created_at &lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;DESC&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;, id &lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;DESC&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;LIMIT&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; &lt;/span&gt;&lt;span style=&quot;--0:#79C0FF&quot;&gt;21&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;;&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;/code&gt;&lt;/pre&gt;&lt;div class=&quot;copy&quot;&gt;&lt;div aria-live=&quot;polite&quot;&gt;&lt;/div&gt;&lt;button title=&quot;Copy to clipboard&quot; data-copied=&quot;Copied!&quot; data-code=&quot;WHERE (created_at, id) &lt; (:createdAt, :id)ORDER BY created_at DESC, id DESCLIMIT 21;&quot;&gt;&lt;div&gt;&lt;/div&gt;&lt;/button&gt;&lt;/div&gt;&lt;/figure&gt;&lt;/div&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;&lt;strong&gt;Backward Query:&lt;/strong&gt;&lt;/p&gt;
&lt;div class=&quot;expressive-code&quot;&gt;&lt;figure class=&quot;frame has-title&quot;&gt;&lt;figcaption class=&quot;header&quot;&gt;&lt;span class=&quot;title&quot;&gt;SQL&lt;/span&gt;&lt;/figcaption&gt;&lt;pre data-language=&quot;sql&quot;&gt;&lt;code&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;WHERE&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; (created_at, id) &lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;&gt;&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; (:createdAt, :id)&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;ORDER BY&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; created_at &lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;ASC&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;, id &lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;ASC&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;LIMIT&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; &lt;/span&gt;&lt;span style=&quot;--0:#79C0FF&quot;&gt;21&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;;&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;/code&gt;&lt;/pre&gt;&lt;div class=&quot;copy&quot;&gt;&lt;div aria-live=&quot;polite&quot;&gt;&lt;/div&gt;&lt;button title=&quot;Copy to clipboard&quot; data-copied=&quot;Copied!&quot; data-code=&quot;WHERE (created_at, id) &gt; (:createdAt, :id)ORDER BY created_at ASC, id ASCLIMIT 21;&quot;&gt;&lt;div&gt;&lt;/div&gt;&lt;/button&gt;&lt;/div&gt;&lt;/figure&gt;&lt;/div&gt;
&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;For the backward query, the database pulls the data in ascending order. The application layer then reverses that array before sending it back to the client in the expected sequence.&lt;/p&gt;
&lt;hr&gt;
&lt;h2 id=&quot;cursor-pagination-with-filtering-and-sorting&quot;&gt;Cursor Pagination with Filtering and Sorting&lt;/h2&gt;
&lt;p&gt;Real-world production APIs involve filtering and dynamic sorting:&lt;/p&gt;
&lt;div class=&quot;expressive-code&quot;&gt;&lt;figure class=&quot;frame has-title&quot;&gt;&lt;figcaption class=&quot;header&quot;&gt;&lt;span class=&quot;title&quot;&gt;Text&lt;/span&gt;&lt;/figcaption&gt;&lt;pre data-language=&quot;text&quot;&gt;&lt;code&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span style=&quot;--0:#e6edf3&quot;&gt;GET /api/v1/posts?author_id=42&amp;#x26;status=published&amp;#x26;sort=views&amp;#x26;cursor=...&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;/code&gt;&lt;/pre&gt;&lt;div class=&quot;copy&quot;&gt;&lt;div aria-live=&quot;polite&quot;&gt;&lt;/div&gt;&lt;button title=&quot;Copy to clipboard&quot; data-copied=&quot;Copied!&quot; data-code=&quot;GET /api/v1/posts?author_id=42&amp;#x26;status=published&amp;#x26;sort=views&amp;#x26;cursor=...&quot;&gt;&lt;div&gt;&lt;/div&gt;&lt;/button&gt;&lt;/div&gt;&lt;/figure&gt;&lt;/div&gt;
&lt;p&gt;You need to keep two things in mind here:&lt;/p&gt;
&lt;ol&gt;
&lt;li&gt;&lt;strong&gt;Composite Index Alignment:&lt;/strong&gt; You must have a composite index on your filter and sort columns together, such as &lt;code&gt;(author_id, status, views DESC, id DESC)&lt;/code&gt;.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Context Binding:&lt;/strong&gt; If the user changes their sort option, their previous cursor will no longer work. You should bind query parameters or a filter hash inside the cursor token. This allows you to throw a validation error if a client tries to use an old cursor with a new sorting context.&lt;/li&gt;
&lt;/ol&gt;
&lt;hr&gt;
&lt;h2 id=&quot;cursor-pagination-in-a-distributed-system&quot;&gt;Cursor Pagination in a Distributed System&lt;/h2&gt;
&lt;p&gt;Managing global pagination becomes quite a challenge when your database is divided into multiple shards or partitions, like in CockroachDB, Citus, or sharded MySQL clusters.&lt;/p&gt;
&lt;figure&gt;&lt;img src=&quot;https://raw.githubusercontent.com/rafeuddaraj/rafes-blog-assets/refs/heads/cursor-pagination-under-the-hood/assets/distributed-cursor-merge.svg&quot; alt=&quot;Distributed Cursor Merge Sort&quot; loading=&quot;lazy&quot; decoding=&quot;async&quot; width=&quot;800&quot; height=&quot;350&quot;&gt;&lt;figcaption&gt;Distributed Cursor Merge Sort&lt;/figcaption&gt;&lt;/figure&gt;
&lt;p&gt;Each database shard returns its own ordered data based on its local index. The API gateway or merge node runs a K-Way merge sort algorithm to select the top 20 records, creates a unified global cursor, and sends it back to the client.&lt;/p&gt;
&lt;hr&gt;
&lt;h2 id=&quot;performance-benchmark-and-production-architecture&quot;&gt;Performance Benchmark and Production Architecture&lt;/h2&gt;
&lt;p&gt;When a high-traffic system is migrated from deep offset to indexed cursor pagination during a production incident, the results are incredible.&lt;/p&gt;
&lt;figure&gt;&lt;img src=&quot;https://raw.githubusercontent.com/rafeuddaraj/rafes-blog-assets/refs/heads/cursor-pagination-under-the-hood/assets/incident-before-after.svg&quot; alt=&quot;Incident Architecture: Before vs After&quot; loading=&quot;lazy&quot; decoding=&quot;async&quot; width=&quot;800&quot; height=&quot;350&quot;&gt;&lt;figcaption&gt;Incident Architecture: Before vs After&lt;/figcaption&gt;&lt;/figure&gt;
&lt;figure&gt;&lt;img src=&quot;https://raw.githubusercontent.com/rafeuddaraj/rafes-blog-assets/refs/heads/cursor-pagination-under-the-hood/assets/latency-benchmark-graph.svg&quot; alt=&quot;Latency vs Pagination Depth&quot; loading=&quot;lazy&quot; decoding=&quot;async&quot; width=&quot;800&quot; height=&quot;400&quot;&gt;&lt;figcaption&gt;Latency vs Pagination Depth&lt;/figcaption&gt;&lt;/figure&gt;
&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;Offset Approach (O(N)):&lt;/strong&gt; As the page depth increases, the p95 and p99 latencies climb steeply.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Cursor Approach (O(1)):&lt;/strong&gt; The response time for the first page and the one-millionth page is exactly the same, staying completely flat under 50 milliseconds.&lt;/li&gt;
&lt;/ul&gt;
&lt;div class=&quot;callout&quot; role=&quot;note&quot; data-type=&quot;note&quot;&gt;
&lt;p class=&quot;callout-title&quot;&gt;Random Page Access Trade-off&lt;/p&gt;
&lt;p&gt;The only limitation of cursor pagination is that it does not support random access like jumping straight to page 5000. Offset is a reasonable choice for small datasets or back-office admin panels where users need to jump to specific page numbers. However, cursor pagination remains the only standard solution for infinite scrolls, content feeds, or high-scale public APIs.&lt;/p&gt;
&lt;/div&gt;
&lt;hr&gt;
&lt;h2 id=&quot;final-mental-model-and-production-checklist&quot;&gt;Final Mental Model and Production Checklist&lt;/h2&gt;
&lt;p&gt;Remember the core formula of this entire architecture:&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;The Scalability Equation:&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;Deterministic Order + Matching Composite Index + Keyset Boundary + Bounded LIMIT = O(1) Scalable Pagination.&lt;/p&gt;
&lt;figure&gt;&lt;img src=&quot;https://raw.githubusercontent.com/rafeuddaraj/rafes-blog-assets/refs/heads/cursor-pagination-under-the-hood/assets/production-api-lifecycle.svg&quot; alt=&quot;Production API Request Lifecycle&quot; loading=&quot;lazy&quot; decoding=&quot;async&quot; width=&quot;800&quot; height=&quot;500&quot;&gt;&lt;figcaption&gt;Production API Request Lifecycle&lt;/figcaption&gt;&lt;/figure&gt;
&lt;h3 id=&quot;your-production-readiness-checklist&quot;&gt;Your Production Readiness Checklist&lt;/h3&gt;
&lt;ol&gt;
&lt;li&gt;&lt;strong&gt;Deterministic Tie-Breaker:&lt;/strong&gt; Always add a unique column, like &lt;code&gt;id&lt;/code&gt; or a &lt;code&gt;uuid_v7&lt;/code&gt;, to your &lt;code&gt;ORDER BY&lt;/code&gt; clause.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Matching Index:&lt;/strong&gt; Create a composite index that matches the column sequence of your &lt;code&gt;WHERE&lt;/code&gt; and &lt;code&gt;ORDER BY&lt;/code&gt; clauses.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Opaque Tokens:&lt;/strong&gt; Hide your internal database state by using Base64 encoded or HMAC signed cursor tokens.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;LIMIT + 1 Pattern:&lt;/strong&gt; Avoid running separate &lt;code&gt;COUNT(*)&lt;/code&gt; queries and determine your next page using the &lt;code&gt;LIMIT + 1&lt;/code&gt; pattern.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Context Validation:&lt;/strong&gt; Write logic to reject old cursors if the client changes their filters or sorting.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Immutable Sort Fields:&lt;/strong&gt; Sort your pagination using immutable columns whenever possible.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;EXPLAIN Verification:&lt;/strong&gt; Before deploying to production, run &lt;code&gt;EXPLAIN ANALYZE&lt;/code&gt; to guarantee that your query is using an index scan and is not discarding unnecessary rows.&lt;/li&gt;
&lt;/ol&gt;
&lt;p&gt;Cursor pagination is not just an API pattern. It is a powerful system architecture design that forces the database engine to work in a bounded, index-friendly way.&lt;/p&gt;</content:encoded><category>Software Architecture</category><category>Database</category><category>PostgreSQL</category><category>System Design</category><category>Backend</category><category>API Architecture</category><category>Performance Optimization</category></item><item><title>How Database Connection Pools Actually Work Under the Hood (A Deep Dive)</title><link>https://www.rafeuddaraj.me/blog/how-database-connection-pools-work-under-the-hood/</link><guid isPermaLink="true">https://www.rafeuddaraj.me/blog/how-database-connection-pools-work-under-the-hood/</guid><description>A complete deep dive guide on how database connection pools work, why systems crash under heavy traffic, and how to design production scale connection management architectures.</description><pubDate>Fri, 04 Sep 2026 03:22:00 GMT</pubDate><content:encoded>&lt;p&gt;Imagine you are running a high-traffic production application. Suddenly, you notice that your API response time has jumped from 50 milliseconds to 3 or 4 seconds. System alerts start going off everywhere. Your first thought might be that the database has become slow.&lt;/p&gt;
&lt;p&gt;You quickly check the database dashboard. However, you see that the CPU usage is completely normal, memory is fine, and there are no unusual spikes in disk I/O. Next, you look at the application server, and there are no massive CPU or memory spikes there either.&lt;/p&gt;
&lt;p&gt;So where exactly are the requests getting stuck?&lt;/p&gt;
&lt;figure&gt;&lt;img src=&quot;https://raw.githubusercontent.com/rafeuddaraj/rafes-blog-assets/refs/heads/how-database-connection-pools-work-under-the-hood/assets/production-bottleneck.svg&quot; alt=&quot;The Hidden Production Bottleneck&quot; loading=&quot;lazy&quot; decoding=&quot;async&quot; width=&quot;800&quot; height=&quot;400&quot;&gt;&lt;figcaption&gt;The Hidden Production Bottleneck&lt;/figcaption&gt;&lt;/figure&gt;
&lt;p&gt;This is where our deep dive begins. Often, the real bottleneck in an application is not the database query execution time, but rather the time requests spend waiting just to get a database connection. Today, we will walk through exactly how a database connection pool works, why it is so difficult to scale, and how you can find this hidden bottleneck in your own system.&lt;/p&gt;
&lt;h2 id=&quot;mental-model-what-exactly-is-a-database-connection&quot;&gt;Mental Model: What Exactly is a Database Connection?&lt;/h2&gt;
&lt;p&gt;If you think of a database connection as just a simple TCP socket, you will miss the bigger picture. When an application creates a new connection with a database, a lot of expensive operations happen behind the scenes.&lt;/p&gt;
&lt;p&gt;First, a standard TCP 3-way handshake takes place. After that, a TLS handshake occurs for security, which involves certificate validation and symmetric key negotiation. Next, database-level authentication and authorization happen. Once the authentication is successful, the database allocates a dedicated memory context in its own memory just for this session.&lt;/p&gt;
&lt;figure&gt;&lt;img src=&quot;https://raw.githubusercontent.com/rafeuddaraj/rafes-blog-assets/refs/heads/how-database-connection-pools-work-under-the-hood/assets/connection-lifecycle.svg&quot; alt=&quot;Database Connection Creation Lifecycle&quot; loading=&quot;lazy&quot; decoding=&quot;async&quot; width=&quot;800&quot; height=&quot;300&quot;&gt;&lt;figcaption&gt;Database Connection Creation Lifecycle&lt;/figcaption&gt;&lt;/figure&gt;
&lt;p&gt;This entire process is incredibly time-consuming and resource-intensive. If your application has to go through this complete cycle for every single request, your application latency will increase drastically.&lt;/p&gt;
&lt;hr&gt;
&lt;h2 id=&quot;the-problem-with-a-pool-less-architecture&quot;&gt;The Problem with a Pool-less Architecture&lt;/h2&gt;
&lt;p&gt;First, imagine a naive architecture where there is no connection pool at all. Every incoming request creates a completely new connection just to talk to the database.&lt;/p&gt;
&lt;figure&gt;&lt;img src=&quot;https://raw.githubusercontent.com/rafeuddaraj/rafes-blog-assets/refs/heads/how-database-connection-pools-work-under-the-hood/assets/no-pool-architecture.svg&quot; alt=&quot;Architecture Without Connection Pool&quot; loading=&quot;lazy&quot; decoding=&quot;async&quot; width=&quot;800&quot; height=&quot;400&quot;&gt;&lt;figcaption&gt;Architecture Without Connection Pool&lt;/figcaption&gt;&lt;/figure&gt;
&lt;p&gt;When traffic is low, this setup works fine. But as traffic grows, the number of connection creations increases exponentially. If hundreds or thousands of concurrent requests come in, the database faces much more pressure from creating new connections than from actually executing queries. Eventually, the database stops accepting new connections, and the application crashes.&lt;/p&gt;
&lt;hr&gt;
&lt;h2 id=&quot;the-core-idea-behind-a-connection-pool&quot;&gt;The Core Idea Behind a Connection Pool&lt;/h2&gt;
&lt;p&gt;The connection pool was created specifically to solve this exact problem. A connection pool essentially creates and holds a number of database connections ahead of time. It acts as a shared, reusable resource manager.&lt;/p&gt;
&lt;figure&gt;&lt;img src=&quot;https://raw.githubusercontent.com/rafeuddaraj/rafes-blog-assets/refs/heads/how-database-connection-pools-work-under-the-hood/assets/pool-concept.svg&quot; alt=&quot;Connection Pool Reusability Concept&quot; loading=&quot;lazy&quot; decoding=&quot;async&quot; width=&quot;800&quot; height=&quot;350&quot;&gt;&lt;figcaption&gt;Connection Pool Reusability Concept&lt;/figcaption&gt;&lt;/figure&gt;
&lt;p&gt;When a request needs database access, it does not create a new connection. Instead, it borrows an existing connection from the pool. Once the database work is done, the request does not destroy the connection. It returns the connection back to the pool. As a result, a single connection can sequentially process thousands of requests throughout the day.&lt;/p&gt;
&lt;p&gt;We can use a great analogy here. Imagine you visit a library. The library has 10 chairs for reading. You sit in one of the chairs to read. When you finish reading, you do not break the chair. Instead, you leave the chair so someone else can sit down. A connection pool works exactly like this.&lt;/p&gt;
&lt;hr&gt;
&lt;h2 id=&quot;pool-internal-architecture&quot;&gt;Pool Internal Architecture&lt;/h2&gt;
&lt;p&gt;The internal state of a real-world connection pool can be quite complex. The pool generally manages four types of states: &lt;code&gt;min connections&lt;/code&gt;, &lt;code&gt;max connections&lt;/code&gt;, &lt;code&gt;idle connections&lt;/code&gt;, and &lt;code&gt;active connections&lt;/code&gt;.&lt;/p&gt;
&lt;figure&gt;&lt;img src=&quot;https://raw.githubusercontent.com/rafeuddaraj/rafes-blog-assets/refs/heads/how-database-connection-pools-work-under-the-hood/assets/pool-internal-state.svg&quot; alt=&quot;Connection Pool Internal State&quot; loading=&quot;lazy&quot; decoding=&quot;async&quot; width=&quot;800&quot; height=&quot;400&quot;&gt;&lt;figcaption&gt;Connection Pool Internal State&lt;/figcaption&gt;&lt;/figure&gt;
&lt;p&gt;The pool does not just store connections. It strictly manages the lifecycle of connection allocation and release. Among these, the most important parameter is &lt;code&gt;max connections&lt;/code&gt;. This parameter determines the absolute maximum number of database operations your application can run at the exact same time.&lt;/p&gt;
&lt;hr&gt;
&lt;h2 id=&quot;connection-acquire-and-the-hidden-queue&quot;&gt;Connection Acquire and the Hidden Queue&lt;/h2&gt;
&lt;p&gt;When a request wants to talk to the database, it first asks the pool for a connection using &lt;code&gt;pool.acquire()&lt;/code&gt;. The pool checks if it has any idle connections available. If it does, it hands the connection to the request immediately.&lt;/p&gt;
&lt;p&gt;If there are no idle connections, the pool checks if it has the capacity to create a new one. This means it checks if the &lt;code&gt;max connections&lt;/code&gt; limit has been reached. If there is capacity, a new connection is created. But if the capacity is completely exhausted, the request is pushed into a hidden waiting queue.&lt;/p&gt;
&lt;figure&gt;&lt;img src=&quot;https://raw.githubusercontent.com/rafeuddaraj/rafes-blog-assets/refs/heads/how-database-connection-pools-work-under-the-hood/assets/connection-acquire-flow.svg&quot; alt=&quot;Connection Acquire Flowchart&quot; loading=&quot;lazy&quot; decoding=&quot;async&quot; width=&quot;800&quot; height=&quot;500&quot;&gt;&lt;figcaption&gt;Connection Acquire Flowchart&lt;/figcaption&gt;&lt;/figure&gt;
&lt;p&gt;This queue is the primary cause of high latency in heavy-traffic systems. When 100 requests arrive at the same time and the pool size is only 10, the remaining 90 requests have to stand in line.&lt;/p&gt;
&lt;figure&gt;&lt;img src=&quot;https://raw.githubusercontent.com/rafeuddaraj/rafes-blog-assets/refs/heads/how-database-connection-pools-work-under-the-hood/assets/pool-hidden-queue.svg&quot; alt=&quot;Connection Pool Hidden Queue Under High Load&quot; loading=&quot;lazy&quot; decoding=&quot;async&quot; width=&quot;800&quot; height=&quot;400&quot;&gt;&lt;figcaption&gt;Connection Pool Hidden Queue Under High Load&lt;/figcaption&gt;&lt;/figure&gt;
&lt;div class=&quot;callout&quot; role=&quot;note&quot; data-type=&quot;tip&quot;&gt;
&lt;p class=&quot;callout-title&quot;&gt;Tip&lt;/p&gt;
&lt;p&gt;If requests get stuck in the queue for too long, your API response will become slow. You should always monitor the pool waiting queue size and the acquisition latency in your observability tools.&lt;/p&gt;
&lt;/div&gt;
&lt;hr&gt;
&lt;h2 id=&quot;connection-release-vs-close&quot;&gt;Connection Release vs Close&lt;/h2&gt;
&lt;p&gt;After a query finishes, the connection is usually not closed. Instead, it is released. This means the connection is not completely disconnected from the database, but rather returned to the idle state inside the pool.&lt;/p&gt;
&lt;p&gt;This is a critical concept for developers to understand. If an exception happens in your code and the connection is not properly released, it gets permanently lost from the pool. We call this a connection leak.&lt;/p&gt;
&lt;div class=&quot;expressive-code&quot;&gt;&lt;style&gt;.expressive-code{font-family:var(--ec-uiFontFml);font-size:var(--ec-uiFontSize);font-weight:var(--ec-uiFontWg);line-height:var(--ec-uiLineHt);text-size-adjust:none;-webkit-text-size-adjust:none}.expressive-code *:not(:is(svg, svg *)){all:revert;box-sizing:border-box}.expressive-code pre{display:flex;margin:0;padding:0;border:var(--ec-brdWd) solid var(--ec-brdCol);border-radius:calc(var(--ec-brdRad) + var(--ec-brdWd));background:var(--ec-codeBg)}.expressive-code pre:focus-visible{outline:3px solid var(--ec-focusBrd);outline-offset:-3px}.expressive-code pre &gt; code{all:unset;display:block;flex:1 0 100%;padding:var(--ec-codePadBlk) 0;color:var(--ec-codeFg);font-family:var(--ec-codeFontFml);font-size:var(--ec-codeFontSize);font-weight:var(--ec-codeFontWg);line-height:var(--ec-codeLineHt)}.expressive-code pre{overflow-x:auto}.expressive-code pre.wrap .ec-line .code{white-space:pre-wrap;overflow-wrap:break-word;min-width:min(20ch, var(--ecMaxLine, 20ch))}.expressive-code pre.wrap .ec-line .code span.indent{white-space:pre}.expressive-code pre::-webkit-scrollbar,.expressive-code pre::-webkit-scrollbar-track{background-color:inherit;border-radius:calc(var(--ec-brdRad) + var(--ec-brdWd));border-top-left-radius:0;border-top-right-radius:0}.expressive-code pre::-webkit-scrollbar-thumb{background-color:var(--ec-sbThumbCol);border:4px solid transparent;background-clip:content-box;border-radius:10px}.expressive-code pre::-webkit-scrollbar-thumb:hover{background-color:var(--ec-sbThumbHoverCol)}.expressive-code pre::-webkit-scrollbar-corner{background:transparent}.expressive-code .ec-line{direction:ltr;unicode-bidi:isolate;display:grid;grid-template-areas:&apos;gutter code&apos;;grid-template-columns:auto 1fr;position:relative}.expressive-code .ec-line .gutter{grid-area:gutter;color:var(--ec-gtrFg)}.expressive-code .ec-line .gutter &gt; *{pointer-events:none;user-select:none;-webkit-user-select:none}.expressive-code .ec-line .gutter ~ .code{--ecLineBrdCol:var(--ec-gtrBrdCol)}.expressive-code .ec-line.highlight .gutter{color:var(--ec-gtrHlFg)}.expressive-code .ec-line .code{grid-area:code;position:relative;box-sizing:content-box;padding-inline-start:calc(var(--ecIndent, 0ch) + var(--ec-codePadInl) - var(--ecGtrBrdWd));padding-inline-end:var(--ec-codePadInl);text-indent:calc(var(--ecIndent, 0ch) * -1)}.expressive-code .ec-line .code::before,.expressive-code .ec-line .code::after,.expressive-code .ec-line .code :where(*){text-indent:0}.expressive-code .ec-line .code{--ecGtrBrdWd:var(--ec-gtrBrdWd);border-inline-start:var(--ecGtrBrdWd) solid var(--ecLineBrdCol, transparent)}.expressive-code .sr-only{position:absolute;width:1px;height:1px;padding:0;margin:-1px;overflow:hidden;clip:rect(0, 0, 0, 0);white-space:nowrap;border-width:0}.expressive-code .ec-line.mark{--tmLineBgCol:var(--ec-tm-markBg)}.expressive-code .ec-line.mark .code{--ecLineBrdCol:var(--ec-tm-markBrdCol)}.expressive-code .ec-line.ins{--tmLineBgCol:var(--ec-tm-insBg);--tmLabel:var(--ec-tm-insDiffIndContent)}.expressive-code .ec-line.ins .code{--ecLineBrdCol:var(--ec-tm-insBrdCol)}.expressive-code .ec-line.ins .code::before{color:var(--ec-tm-insDiffIndCol)}.expressive-code .ec-line.del{--tmLineBgCol:var(--ec-tm-delBg);--tmLabel:var(--ec-tm-delDiffIndContent)}.expressive-code .ec-line.del .code{--ecLineBrdCol:var(--ec-tm-delBrdCol)}.expressive-code .ec-line.del .code::before{color:var(--ec-tm-delDiffIndCol)}.expressive-code .ec-line.mark,.expressive-code .ec-line.ins,.expressive-code .ec-line.del{background:var(--tmLineBgCol)}.expressive-code .ec-line.mark .code,.expressive-code .ec-line.ins .code,.expressive-code .ec-line.del .code{--ecGtrBrdWd:var(--ec-tm-lineMarkerAccentWd)}.expressive-code .ec-line.mark .code::before,.expressive-code .ec-line.ins .code::before,.expressive-code .ec-line.del .code::before{display:block;position:absolute;left:0;box-sizing:border-box;content:var(--tmLabel, &apos; &apos;);padding-inline-start:var(--ec-tm-lineDiffIndMargLeft);text-align:center;white-space:pre}.expressive-code .ec-line.mark.tm-label .code::before,.expressive-code .ec-line.ins.tm-label .code::before,.expressive-code .ec-line.del.tm-label .code::before{background:var(--ecLineBrdCol);padding:0 calc(var(--ec-tm-lineMarkerLabelPadInl) + var(--ec-tm-lineMarkerAccentWd)) 0 var(--ec-tm-lineMarkerLabelPadInl);color:var(--ec-tm-lineMarkerLabelCol)}.expressive-code .ec-line mark{--tmInlineBgCol:var(--ec-tm-markBg);--tmInlineBrdCol:var(--ec-tm-markBrdCol)}.expressive-code .ec-line ins{--tmInlineBgCol:var(--ec-tm-insBg);--tmInlineBrdCol:var(--ec-tm-insBrdCol)}.expressive-code .ec-line del{--tmInlineBgCol:var(--ec-tm-delBg);--tmInlineBrdCol:var(--ec-tm-delBrdCol)}.expressive-code .ec-line mark,.expressive-code .ec-line ins,.expressive-code .ec-line del{all:unset;display:inline-block;position:relative;--tmBrdL:var(--ec-tm-inlMarkerBrdWd);--tmBrdR:var(--ec-tm-inlMarkerBrdWd);--tmRadL:var(--ec-tm-inlMarkerBrdRad);--tmRadR:var(--ec-tm-inlMarkerBrdRad);margin-inline:0.025rem;padding-inline:var(--ec-tm-inlMarkerPad);border-radius:var(--tmRadL) var(--tmRadR) var(--tmRadR) var(--tmRadL);background:var(--tmInlineBgCol);background-clip:padding-box}.expressive-code .ec-line mark.open-start,.expressive-code .ec-line ins.open-start,.expressive-code .ec-line del.open-start{margin-inline-start:0;padding-inline-start:0;--tmBrdL:0px;--tmRadL:0}.expressive-code .ec-line mark.open-end,.expressive-code .ec-line ins.open-end,.expressive-code .ec-line del.open-end{margin-inline-end:0;padding-inline-end:0;--tmBrdR:0px;--tmRadR:0}.expressive-code .ec-line mark::before,.expressive-code .ec-line ins::before,.expressive-code .ec-line del::before{content:&apos;&apos;;position:absolute;pointer-events:none;display:inline-block;inset:0;border-radius:var(--tmRadL) var(--tmRadR) var(--tmRadR) var(--tmRadL);border:var(--ec-tm-inlMarkerBrdWd) solid var(--tmInlineBrdCol);border-inline-width:var(--tmBrdL) var(--tmBrdR)}.expressive-code .frame{all:unset;position:relative;display:block;--header-border-radius:calc(var(--ec-brdRad) + var(--ec-brdWd));--tab-border-radius:calc(var(--ec-frm-edTabBrdRad) + var(--ec-brdWd));--button-spacing:0.4rem;--code-background:var(--ec-frm-edBg);border-radius:var(--header-border-radius);box-shadow:var(--ec-frm-frameBoxShdCssVal)}.expressive-code .frame .header{display:none;z-index:1;position:relative;border-radius:var(--header-border-radius) var(--header-border-radius) 0 0}.expressive-code .frame.has-title pre,.expressive-code .frame.has-title code,.expressive-code .frame.is-terminal pre,.expressive-code .frame.is-terminal code{border-top:none;border-top-left-radius:0;border-top-right-radius:0}.expressive-code .frame .title:empty:before{content:&apos;\a0&apos;}.expressive-code .frame.has-title:not(.is-terminal){--button-spacing:calc(1.9rem + 2 * (var(--ec-uiPadBlk) + var(--ec-frm-edActTabIndHt)))}.expressive-code .frame.has-title:not(.is-terminal) .title{position:relative;color:var(--ec-frm-edActTabFg);background:var(--ec-frm-edActTabBg);background-clip:padding-box;margin-block-start:var(--ec-frm-edTabsMargBlkStart);padding:calc(var(--ec-uiPadBlk) + var(--ec-frm-edActTabIndHt)) var(--ec-uiPadInl);border:var(--ec-brdWd) solid var(--ec-frm-edActTabBrdCol);border-radius:var(--tab-border-radius) var(--tab-border-radius) 0 0;border-bottom:none;overflow:hidden}.expressive-code .frame.has-title:not(.is-terminal) .title::after{content:&apos;&apos;;position:absolute;pointer-events:none;inset:0;border-top:var(--ec-frm-edActTabIndHt) solid var(--ec-frm-edActTabIndTopCol);border-bottom:var(--ec-frm-edActTabIndHt) solid var(--ec-frm-edActTabIndBtmCol)}.expressive-code .frame.has-title:not(.is-terminal) .header{display:flex;background:linear-gradient(to top, var(--ec-frm-edTabBarBrdBtmCol) var(--ec-brdWd), transparent var(--ec-brdWd)),linear-gradient(var(--ec-frm-edTabBarBg), var(--ec-frm-edTabBarBg));background-repeat:no-repeat;padding-inline-start:var(--ec-frm-edTabsMargInlStart)}.expressive-code .frame.has-title:not(.is-terminal) .header::before{content:&apos;&apos;;position:absolute;pointer-events:none;inset:0;border:var(--ec-brdWd) solid var(--ec-frm-edTabBarBrdCol);border-radius:inherit;border-bottom:none}.expressive-code .frame.is-terminal{--button-spacing:calc(1.9rem + var(--ec-brdWd) + 2 * var(--ec-uiPadBlk));--code-background:var(--ec-frm-trmBg)}.expressive-code .frame.is-terminal .header{display:flex;align-items:center;justify-content:center;padding-block:var(--ec-uiPadBlk);padding-block-end:calc(var(--ec-uiPadBlk) + var(--ec-brdWd));position:relative;font-weight:500;letter-spacing:0.025ch;color:var(--ec-frm-trmTtbFg);background:var(--ec-frm-trmTtbBg);border:var(--ec-brdWd) solid var(--ec-brdCol);border-bottom:none}.expressive-code .frame.is-terminal .header::before{content:&apos;&apos;;position:absolute;pointer-events:none;left:var(--ec-uiPadInl);width:2.1rem;height:0.56rem;line-height:0;background-color:var(--ec-frm-trmTtbDotsFg);opacity:var(--ec-frm-trmTtbDotsOpa);-webkit-mask-image:var(--ec-frm-trmIcon);-webkit-mask-repeat:no-repeat;mask-image:var(--ec-frm-trmIcon);mask-repeat:no-repeat}.expressive-code .frame.is-terminal .header::after{content:&apos;&apos;;position:absolute;pointer-events:none;inset:0;border-bottom:var(--ec-brdWd) solid var(--ec-frm-trmTtbBrdBtmCol)}.expressive-code .frame pre{background:var(--code-background)}.expressive-code .copy{display:flex;gap:0.25rem;flex-direction:row;position:absolute;inset-block-start:calc(var(--ec-brdWd) + var(--button-spacing));inset-inline-end:calc(var(--ec-brdWd) + var(--ec-uiPadInl) / 2)}@media (scripting: none){.expressive-code .copy{display:none}}.expressive-code .copy{direction:ltr;unicode-bidi:isolate}.expressive-code .copy button{position:relative;align-self:flex-end;margin:0;padding:0;border:none;border-radius:0.2rem;z-index:1;cursor:pointer;transition-property:opacity, background, border-color;transition-duration:0.2s;transition-timing-function:cubic-bezier(0.25, 0.46, 0.45, 0.94);width:2.5rem;height:2.5rem;background:var(--code-background);opacity:0.75}.expressive-code .copy button div{position:absolute;inset:0;border-radius:inherit;background:var(--ec-frm-inlBtnBg);opacity:var(--ec-frm-inlBtnBgIdleOpa);transition-property:inherit;transition-duration:inherit;transition-timing-function:inherit}.expressive-code .copy button::before{content:&apos;&apos;;position:absolute;pointer-events:none;inset:0;border-radius:inherit;border:var(--ec-brdWd) solid var(--ec-frm-inlBtnBrd);opacity:var(--ec-frm-inlBtnBrdOpa)}.expressive-code .copy button::after{content:&apos;&apos;;position:absolute;pointer-events:none;inset:0;background-color:var(--ec-frm-inlBtnFg);-webkit-mask-image:var(--ec-frm-copyIcon);-webkit-mask-repeat:no-repeat;mask-image:var(--ec-frm-copyIcon);mask-repeat:no-repeat;margin:0.475rem;line-height:0}.expressive-code .copy button:hover,.expressive-code .copy button:focus:focus-visible{opacity:1}.expressive-code .copy button:hover div,.expressive-code .copy button:focus:focus-visible div{opacity:var(--ec-frm-inlBtnBgHoverOrFocusOpa)}.expressive-code .copy button:active{opacity:1}.expressive-code .copy button:active div{opacity:var(--ec-frm-inlBtnBgActOpa)}.expressive-code .copy .feedback{--tooltip-arrow-size:0.35rem;--tooltip-bg:var(--ec-frm-tooltipSuccessBg);color:var(--ec-frm-tooltipSuccessFg);pointer-events:none;user-select:none;-webkit-user-select:none;position:relative;align-self:center;background-color:var(--tooltip-bg);z-index:99;padding:0.125rem 0.75rem;border-radius:0.2rem;margin-inline-end:var(--tooltip-arrow-size);opacity:0;transition-property:opacity, transform;transition-duration:0.2s;transition-timing-function:ease-in-out;transform:translate3d(0, 0.25rem, 0)}.expressive-code .copy .feedback::after{content:&apos;&apos;;position:absolute;pointer-events:none;top:calc(50% - var(--tooltip-arrow-size));inset-inline-end:calc(-2 * (var(--tooltip-arrow-size) - 0.5px));border:var(--tooltip-arrow-size) solid transparent;border-inline-start-color:var(--tooltip-bg)}.expressive-code .copy .feedback.show{opacity:1;transform:translate3d(0, 0, 0)}@media (hover: hover){.expressive-code{}.expressive-code .copy button{opacity:0;width:2rem;height:2rem}.expressive-code .frame:hover .copy button:not(:hover),.expressive-code .frame:focus-within :focus-visible ~ .copy button:not(:hover),.expressive-code .frame .copy .feedback.show ~ button:not(:hover){opacity:0.75}}.expressive-code :nth-child(1 of .ec-line) .code{padding-inline-end:calc(2rem + var(--ec-codePadInl))}:root{--ec-brdRad:0.75rem;--ec-brdWd:1.5px;--ec-brdCol:var(--code-line);--ec-codeFontFml:var(--font-code);--ec-codeFontSize:0.875rem;--ec-codeFontWg:400;--ec-codeLineHt:1.75;--ec-codePadBlk:1rem;--ec-codePadInl:1.125rem;--ec-codeBg:var(--code-bg);--ec-codeFg:#e6edf3;--ec-codeSelBg:#264f78;--ec-gtrFg:#6e7681;--ec-gtrBrdCol:#6e768133;--ec-gtrBrdWd:1.5px;--ec-gtrHlFg:#e6edf3;--ec-uiFontFml:var(--font-mono);--ec-uiFontSize:0.75rem;--ec-uiFontWg:400;--ec-uiLineHt:1.65;--ec-uiPadBlk:0.25rem;--ec-uiPadInl:1rem;--ec-uiSelBg:#6e768166;--ec-uiSelFg:#e6edf3;--ec-focusBrd:#1f6feb;--ec-sbThumbCol:#8b949e33;--ec-sbThumbHoverCol:#8b949e3d;--ec-tm-lineMarkerAccentMarg:0rem;--ec-tm-lineMarkerAccentWd:0.15rem;--ec-tm-lineMarkerLabelPadInl:0.2rem;--ec-tm-lineMarkerLabelCol:white;--ec-tm-lineDiffIndMargLeft:0.3rem;--ec-tm-inlMarkerBrdWd:1.5px;--ec-tm-inlMarkerBrdRad:0.2rem;--ec-tm-inlMarkerPad:0.15rem;--ec-tm-insDiffIndContent:&apos;+&apos;;--ec-tm-delDiffIndContent:&apos;-&apos;;--ec-tm-markBg:#264a8980;--ec-tm-markBrdCol:#5570b3d0;--ec-tm-insBg:#26561c80;--ec-tm-insBrdCol:#4e7e41d0;--ec-tm-insDiffIndCol:#7eb070d0;--ec-tm-delBg:#81322b80;--ec-tm-delBrdCol:#ae594fd0;--ec-tm-delDiffIndCol:#e68a7ed0;--ec-frm-shdCol:#0000005b;--ec-frm-frameBoxShdCssVal:none;--ec-frm-edActTabBg:var(--code-bg);--ec-frm-edActTabFg:var(--code-muted);--ec-frm-edActTabBrdCol:transparent;--ec-frm-edActTabIndHt:1.5px;--ec-frm-edActTabIndTopCol:transparent;--ec-frm-edActTabIndBtmCol:#0d1117;--ec-frm-edTabsMargInlStart:0;--ec-frm-edTabsMargBlkStart:0;--ec-frm-edTabBrdRad:0.75rem;--ec-frm-edTabBarBg:var(--code-bg);--ec-frm-edTabBarBrdCol:var(--code-line);--ec-frm-edTabBarBrdBtmCol:var(--code-line);--ec-frm-edBg:var(--code-bg);--ec-frm-trmTtbFg:var(--code-muted);--ec-frm-trmTtbDotsFg:var(--code-muted);--ec-frm-trmTtbDotsOpa:0.15;--ec-frm-trmTtbBg:var(--code-bg);--ec-frm-trmTtbBrdBtmCol:var(--code-line);--ec-frm-trmBg:var(--code-bg);--ec-frm-inlBtnBg:var(--code-ink);--ec-frm-inlBtnBgIdleOpa:0;--ec-frm-inlBtnBgHoverOrFocusOpa:0.2;--ec-frm-inlBtnBgActOpa:0.3;--ec-frm-inlBtnFg:var(--code-ink);--ec-frm-inlBtnBrd:var(--code-line);--ec-frm-inlBtnBrdOpa:0.4;--ec-frm-tooltipSuccessBg:var(--color-emerald);--ec-frm-tooltipSuccessFg:var(--color-bg);--ec-frm-copyIcon:url(&quot;data:image/svg+xml,%3Csvg%20xmlns%3D&apos;http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg&apos;%20viewBox%3D&apos;0%200%2024%2024&apos;%20fill%3D&apos;none&apos;%20stroke%3D&apos;black&apos;%20stroke-width%3D&apos;1.75&apos;%3E%3Cpath%20d%3D&apos;M3%2019a2%202%200%200%201-1-2V2a2%202%200%200%201%201-1h13a2%202%200%200%201%202%201&apos;%2F%3E%3Crect%20x%3D&apos;6&apos;%20y%3D&apos;5&apos;%20width%3D&apos;16&apos;%20height%3D&apos;18&apos;%20rx%3D&apos;1.5&apos;%20ry%3D&apos;1.5&apos;%2F%3E%3C%2Fsvg%3E&quot;);--ec-frm-trmIcon:url(&quot;data:image/svg+xml,%3Csvg%20xmlns%3D&apos;http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg&apos;%20viewBox%3D&apos;0%200%2060%2016&apos;%20preserveAspectRatio%3D&apos;xMidYMid%20meet&apos;%3E%3Ccircle%20cx%3D&apos;8&apos;%20cy%3D&apos;8&apos;%20r%3D&apos;8&apos;%2F%3E%3Ccircle%20cx%3D&apos;30&apos;%20cy%3D&apos;8&apos;%20r%3D&apos;8&apos;%2F%3E%3Ccircle%20cx%3D&apos;52&apos;%20cy%3D&apos;8&apos;%20r%3D&apos;8&apos;%2F%3E%3C%2Fsvg%3E&quot;)}.expressive-code .ec-line :where(span[style^=&apos;--&apos;]:not([class])){color:var(--0, inherit);background-color:var(--0bg, transparent);font-style:var(--0fs, inherit);font-weight:var(--0fw, inherit);text-decoration:var(--0td, inherit)}&lt;/style&gt;&lt;script type=&quot;module&quot; src=&quot;/_astro/ec.0vx5m.js&quot;&gt;&lt;/script&gt;&lt;figure class=&quot;frame has-title&quot;&gt;&lt;figcaption class=&quot;header&quot;&gt;&lt;span class=&quot;title&quot;&gt;JavaScript&lt;/span&gt;&lt;/figcaption&gt;&lt;pre data-language=&quot;javascript&quot;&gt;&lt;code&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;const&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; &lt;/span&gt;&lt;span style=&quot;--0:#79C0FF&quot;&gt;connection&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; &lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;=&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; &lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;await&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; pool.&lt;/span&gt;&lt;span style=&quot;--0:#D2A8FF&quot;&gt;acquire&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;();&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;
&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;try&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; {&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span class=&quot;indent&quot;&gt;  &lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;await&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; connection.&lt;/span&gt;&lt;span style=&quot;--0:#D2A8FF&quot;&gt;query&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;(&lt;/span&gt;&lt;span style=&quot;--0:#A5D6FF&quot;&gt;&apos;SELECT * FROM users&apos;&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;);&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;} &lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;finally&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; {&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span class=&quot;indent&quot;&gt;  &lt;/span&gt;&lt;span style=&quot;--0:#8B949E&quot;&gt;// Even if an error occurs, the connection must be returned to the pool&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span class=&quot;indent&quot;&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;  &lt;/span&gt;&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;connection.&lt;/span&gt;&lt;span style=&quot;--0:#D2A8FF&quot;&gt;release&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;();&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;}&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;/code&gt;&lt;/pre&gt;&lt;div class=&quot;copy&quot;&gt;&lt;div aria-live=&quot;polite&quot;&gt;&lt;/div&gt;&lt;button title=&quot;Copy to clipboard&quot; data-copied=&quot;Copied!&quot; data-code=&quot;const connection = await pool.acquire();try {  await connection.query(&amp;#x27;SELECT * FROM users&amp;#x27;);} finally {  // Even if an error occurs, the connection must be returned to the pool  connection.release();}&quot;&gt;&lt;div&gt;&lt;/div&gt;&lt;/button&gt;&lt;/div&gt;&lt;/figure&gt;&lt;/div&gt;
&lt;hr&gt;
&lt;h2 id=&quot;wait-time-vs-query-time&quot;&gt;Wait Time vs Query Time&lt;/h2&gt;
&lt;p&gt;The total database latency for a request is basically the sum of a few different parts. Let us say one of your requests took 830 milliseconds to fetch data from the database. You might think your query is just very slow.&lt;/p&gt;
&lt;figure&gt;&lt;img src=&quot;https://raw.githubusercontent.com/rafeuddaraj/rafes-blog-assets/refs/heads/how-database-connection-pools-work-under-the-hood/assets/request-latency-timeline.svg&quot; alt=&quot;Request Latency Timeline Breakdown&quot; loading=&quot;lazy&quot; decoding=&quot;async&quot; width=&quot;800&quot; height=&quot;250&quot;&gt;&lt;figcaption&gt;Request Latency Timeline Breakdown&lt;/figcaption&gt;&lt;/figure&gt;
&lt;p&gt;But if you break it down deeply, you might see that the request waited in the pool queue for 800 milliseconds just to get a connection. The actual query execution only took 30 milliseconds. Even though the whole experience feels slow to the user, the database itself is not slow at all. The real problem here is resource starvation.&lt;/p&gt;
&lt;div class=&quot;callout&quot; role=&quot;note&quot; data-type=&quot;warning&quot;&gt;
&lt;p class=&quot;callout-title&quot;&gt;Warning&lt;/p&gt;
&lt;p&gt;If you only look at query execution latency in production, you have a high chance of missing the actual bottleneck. Always measure connection wait time separately.&lt;/p&gt;
&lt;/div&gt;
&lt;hr&gt;
&lt;h2 id=&quot;why-a-larger-pool-does-not-mean-better-performance&quot;&gt;Why a Larger Pool Does Not Mean Better Performance&lt;/h2&gt;
&lt;p&gt;Many people assume that increasing the pool size from 10 to 100 or 500 will automatically make the application much faster. The reality is entirely different.&lt;/p&gt;
&lt;figure&gt;&lt;img src=&quot;https://raw.githubusercontent.com/rafeuddaraj/rafes-blog-assets/refs/heads/how-database-connection-pools-work-under-the-hood/assets/pool-size-performance-curve.svg&quot; alt=&quot;Pool Size vs Performance Curve&quot; loading=&quot;lazy&quot; decoding=&quot;async&quot; width=&quot;800&quot; height=&quot;400&quot;&gt;&lt;figcaption&gt;Pool Size vs Performance Curve&lt;/figcaption&gt;&lt;/figure&gt;
&lt;p&gt;More connections mean more concurrent tasks hitting the database. For every concurrent task, the database has to share CPU time, memory, locks, and disk I/O. When the number of concurrent tasks pushes past the processing capacity of the database, the overall performance drops massively due to internal contention and context switching. This is known as the saturation point.&lt;/p&gt;
&lt;hr&gt;
&lt;h2 id=&quot;the-multi-instance-production-trap&quot;&gt;The Multi-Instance Production Trap&lt;/h2&gt;
&lt;p&gt;In a local development environment, you might only run a single application instance. If your pool size is 20 there, everything will feel absolutely perfect. But when you scale your application horizontally in production, the math completely changes.&lt;/p&gt;
&lt;figure&gt;&lt;img src=&quot;https://raw.githubusercontent.com/rafeuddaraj/rafes-blog-assets/refs/heads/how-database-connection-pools-work-under-the-hood/assets/multi-instance-connection-growth.svg&quot; alt=&quot;Multi-Instance Connection Growth&quot; loading=&quot;lazy&quot; decoding=&quot;async&quot; width=&quot;800&quot; height=&quot;400&quot;&gt;&lt;figcaption&gt;Multi-Instance Connection Growth&lt;/figcaption&gt;&lt;/figure&gt;
&lt;p&gt;Let us say you are running 20 instances in production. If every instance has a pool size of 20, the theoretical maximum number of connections hitting your database becomes 400 (20 x 20). With autoscaling enabled in systems like Kubernetes, your instance count grows as traffic increases. This causes your database connections to multiply exponentially. While it is very easy to scale an application, your database simply cannot scale the exact same way.&lt;/p&gt;
&lt;hr&gt;
&lt;h2 id=&quot;the-cost-of-database-side-connections&quot;&gt;The Cost of Database-Side Connections&lt;/h2&gt;
&lt;p&gt;Now that we understand the application-side pool, let us look at it from the database perspective. PostgreSQL forks a separate OS process for every single connection. It also maintains session-related memory context and temporary tables for each one.&lt;/p&gt;
&lt;figure&gt;&lt;img src=&quot;https://raw.githubusercontent.com/rafeuddaraj/rafes-blog-assets/refs/heads/how-database-connection-pools-work-under-the-hood/assets/db-side-connection-cost.svg&quot; alt=&quot;Database-Side Resource Cost per Connection&quot; loading=&quot;lazy&quot; decoding=&quot;async&quot; width=&quot;800&quot; height=&quot;400&quot;&gt;&lt;figcaption&gt;Database-Side Resource Cost per Connection&lt;/figcaption&gt;&lt;/figure&gt;
&lt;p&gt;This means that as the connection count goes up, it is not just network traffic that increases. The database consumes its own memory and processing power as well. If the connection count gets too high, the database ends up spending more time managing connections than actually processing queries.&lt;/p&gt;
&lt;hr&gt;
&lt;h2 id=&quot;pool-exhaustion-and-cascading-failures&quot;&gt;Pool Exhaustion and Cascading Failures&lt;/h2&gt;
&lt;p&gt;Pool exhaustion happens when every connection in the pool is busy and there are no available connections for incoming requests. At this point, new requests start piling up in the queue.&lt;/p&gt;
&lt;figure&gt;&lt;img src=&quot;https://raw.githubusercontent.com/rafeuddaraj/rafes-blog-assets/refs/heads/how-database-connection-pools-work-under-the-hood/assets/pool-exhaustion-flow.svg&quot; alt=&quot;Pool Exhaustion to Cascading Failure Flow&quot; loading=&quot;lazy&quot; decoding=&quot;async&quot; width=&quot;800&quot; height=&quot;400&quot;&gt;&lt;figcaption&gt;Pool Exhaustion to Cascading Failure Flow&lt;/figcaption&gt;&lt;/figure&gt;
&lt;p&gt;As the queue grows larger, the wait time to get a connection keeps increasing. Eventually, the pool times out and the requests fail. If a slow query keeps running on the database for some reason, it holds onto its connection. As a result, other completely unrelated fast queries get stuck simply because they cannot get a connection.&lt;/p&gt;
&lt;figure&gt;&lt;img src=&quot;https://raw.githubusercontent.com/rafeuddaraj/rafes-blog-assets/refs/heads/how-database-connection-pools-work-under-the-hood/assets/slow-query-cascade.svg&quot; alt=&quot;Slow Query Cascading Failure&quot; loading=&quot;lazy&quot; decoding=&quot;async&quot; width=&quot;800&quot; height=&quot;350&quot;&gt;&lt;figcaption&gt;Slow Query Cascading Failure&lt;/figcaption&gt;&lt;/figure&gt;
&lt;div class=&quot;callout&quot; role=&quot;note&quot; data-type=&quot;danger&quot;&gt;
&lt;p class=&quot;callout-title&quot;&gt;Error&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Pool Leaks and Cascading Failures:&lt;/strong&gt; If you do not release a connection in a &lt;code&gt;finally&lt;/code&gt; block after acquiring it, your pool slowly dies. Everything might look fine at first, but after a while, your entire system can come to a complete halt.&lt;/p&gt;
&lt;/div&gt;
&lt;hr&gt;
&lt;h2 id=&quot;transactions-and-connection-affinity&quot;&gt;Transactions and Connection Affinity&lt;/h2&gt;
&lt;p&gt;Compared to regular queries, transactions put a much heavier load on database connections. Once a transaction starts with &lt;code&gt;BEGIN&lt;/code&gt;, it must hold onto the exact same connection for the entire duration until it hits &lt;code&gt;COMMIT&lt;/code&gt; or &lt;code&gt;ROLLBACK&lt;/code&gt;.&lt;/p&gt;
&lt;figure&gt;&lt;img src=&quot;https://raw.githubusercontent.com/rafeuddaraj/rafes-blog-assets/refs/heads/how-database-connection-pools-work-under-the-hood/assets/transaction-lifecycle.svg&quot; alt=&quot;Transaction Lifecycle on a Single Connection&quot; loading=&quot;lazy&quot; decoding=&quot;async&quot; width=&quot;800&quot; height=&quot;250&quot;&gt;&lt;figcaption&gt;Transaction Lifecycle on a Single Connection&lt;/figcaption&gt;&lt;/figure&gt;
&lt;p&gt;As long as the transaction stays open, that specific connection remains unavailable to any other request. This concept is called connection affinity. If you send a &lt;code&gt;BEGIN&lt;/code&gt; statement on one connection and a &lt;code&gt;COMMIT&lt;/code&gt; statement on a totally different connection, the transaction semantics will completely break down.&lt;/p&gt;
&lt;figure&gt;&lt;img src=&quot;https://raw.githubusercontent.com/rafeuddaraj/rafes-blog-assets/refs/heads/how-database-connection-pools-work-under-the-hood/assets/connection-affinity-semantics.svg&quot; alt=&quot;Connection Affinity Correct vs Wrong Semantics&quot; loading=&quot;lazy&quot; decoding=&quot;async&quot; width=&quot;800&quot; height=&quot;350&quot;&gt;&lt;figcaption&gt;Connection Affinity Correct vs Wrong Semantics&lt;/figcaption&gt;&lt;/figure&gt;
&lt;hr&gt;
&lt;h2 id=&quot;timeouts-and-connection-lifecycle&quot;&gt;Timeouts and Connection Lifecycle&lt;/h2&gt;
&lt;p&gt;Managing timeouts in production systems is a highly critical task. Not all timeouts are the same, and they need to follow a clear hierarchy.&lt;/p&gt;
&lt;figure&gt;&lt;img src=&quot;https://raw.githubusercontent.com/rafeuddaraj/rafes-blog-assets/refs/heads/how-database-connection-pools-work-under-the-hood/assets/timeout-hierarchy.svg&quot; alt=&quot;Production Timeout Hierarchy&quot; loading=&quot;lazy&quot; decoding=&quot;async&quot; width=&quot;800&quot; height=&quot;250&quot;&gt;&lt;figcaption&gt;Production Timeout Hierarchy&lt;/figcaption&gt;&lt;/figure&gt;
&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;Request Timeout:&lt;/strong&gt; The maximum time a client or gateway will wait for the entire request.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Transaction Timeout:&lt;/strong&gt; The maximum time a database transaction is allowed to stay open.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Pool Wait Timeout:&lt;/strong&gt; The maximum time a request will wait to get a connection from the pool.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Query Timeout:&lt;/strong&gt; The maximum time a single query is allowed to run inside the database.&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;Connections do not live forever. They can drop because of network failures or database restarts. The pool needs to routinely check idle connections using health checks like &lt;code&gt;SELECT 1&lt;/code&gt;. It must discard stale connections and create fresh ones.&lt;/p&gt;
&lt;figure&gt;&lt;img src=&quot;https://raw.githubusercontent.com/rafeuddaraj/rafes-blog-assets/refs/heads/how-database-connection-pools-work-under-the-hood/assets/stale-connection-detection.svg&quot; alt=&quot;Stale Connection Detection and Recovery&quot; loading=&quot;lazy&quot; decoding=&quot;async&quot; width=&quot;800&quot; height=&quot;400&quot;&gt;&lt;figcaption&gt;Stale Connection Detection and Recovery&lt;/figcaption&gt;&lt;/figure&gt;
&lt;p&gt;When a connection is reused across different requests, the state from the previous session can accidentally affect the next request. Things like &lt;code&gt;SET statement_timeout&lt;/code&gt; or temporary tables can cause silent bugs in production if they bleed over.&lt;/p&gt;
&lt;figure&gt;&lt;img src=&quot;https://raw.githubusercontent.com/rafeuddaraj/rafes-blog-assets/refs/heads/how-database-connection-pools-work-under-the-hood/assets/session-state-reuse.svg&quot; alt=&quot;The Danger of Session State Reuse&quot; loading=&quot;lazy&quot; decoding=&quot;async&quot; width=&quot;800&quot; height=&quot;350&quot;&gt;&lt;figcaption&gt;The Danger of Session State Reuse&lt;/figcaption&gt;&lt;/figure&gt;
&lt;div class=&quot;callout&quot; role=&quot;note&quot; data-type=&quot;note&quot;&gt;
&lt;p class=&quot;callout-title&quot;&gt;Info&lt;/p&gt;
&lt;p&gt;Before reusing a connection, make sure all session variables and states are completely reset using commands like &lt;code&gt;DISCARD ALL&lt;/code&gt; or &lt;code&gt;RESET ALL&lt;/code&gt;.&lt;/p&gt;
&lt;/div&gt;
&lt;hr&gt;
&lt;h2 id=&quot;pgbouncer-and-serverless-architectures&quot;&gt;PgBouncer and Serverless Architectures&lt;/h2&gt;
&lt;p&gt;In large-scale production environments, an application-side pool alone is not enough. For PostgreSQL, an external connection pooler like PgBouncer is heavily used. It acts as a central proxy layer in front of the database. It multiplexes thousands of application connections down into a very small number of actual database connections.&lt;/p&gt;
&lt;figure&gt;&lt;img src=&quot;https://raw.githubusercontent.com/rafeuddaraj/rafes-blog-assets/refs/heads/how-database-connection-pools-work-under-the-hood/assets/pgbouncer-architecture.svg&quot; alt=&quot;PgBouncer Architecture&quot; loading=&quot;lazy&quot; decoding=&quot;async&quot; width=&quot;800&quot; height=&quot;400&quot;&gt;&lt;figcaption&gt;PgBouncer Architecture&lt;/figcaption&gt;&lt;/figure&gt;
&lt;p&gt;In serverless architectures like AWS Lambda, this problem gets much worse. During a traffic spike, hundreds of short-lived execution instances spin up. If every single one tries to create its own connection, the database connections will instantly explode and crash the system.&lt;/p&gt;
&lt;figure&gt;&lt;img src=&quot;https://raw.githubusercontent.com/rafeuddaraj/rafes-blog-assets/refs/heads/how-database-connection-pools-work-under-the-hood/assets/serverless-connection-explosion.svg&quot; alt=&quot;Serverless Connection Explosion Problem&quot; loading=&quot;lazy&quot; decoding=&quot;async&quot; width=&quot;800&quot; height=&quot;350&quot;&gt;&lt;figcaption&gt;Serverless Connection Explosion Problem&lt;/figcaption&gt;&lt;/figure&gt;
&lt;hr&gt;
&lt;h2 id=&quot;connection-storms-and-retries&quot;&gt;Connection Storms and Retries&lt;/h2&gt;
&lt;p&gt;Imagine your database restarts and goes down for 10 seconds. Your application instances will lose their connections. When the database comes back online, if all the instances suddenly try to reconnect at the exact same time, it hits the database with a massive shock. We call this a connection storm.&lt;/p&gt;
&lt;p&gt;You can help the database recover safely by spreading out these retries over time using exponential backoff and jitter.&lt;/p&gt;
&lt;figure&gt;&lt;img src=&quot;https://raw.githubusercontent.com/rafeuddaraj/rafes-blog-assets/refs/heads/how-database-connection-pools-work-under-the-hood/assets/connection-storm-recovery.svg&quot; alt=&quot;Connection Storm Recovery with Jitter&quot; loading=&quot;lazy&quot; decoding=&quot;async&quot; width=&quot;800&quot; height=&quot;400&quot;&gt;&lt;figcaption&gt;Connection Storm Recovery with Jitter&lt;/figcaption&gt;&lt;/figure&gt;
&lt;p&gt;On top of that, if the database is slow and your application keeps sending aggressive retries, the workload on the database increases even more. This traps your system in a deadly feedback loop.&lt;/p&gt;
&lt;figure&gt;&lt;img src=&quot;https://raw.githubusercontent.com/rafeuddaraj/rafes-blog-assets/refs/heads/how-database-connection-pools-work-under-the-hood/assets/retry-cascading-failure.svg&quot; alt=&quot;Retry Cascading Failure Feedback Loop&quot; loading=&quot;lazy&quot; decoding=&quot;async&quot; width=&quot;800&quot; height=&quot;400&quot;&gt;&lt;figcaption&gt;Retry Cascading Failure Feedback Loop&lt;/figcaption&gt;&lt;/figure&gt;
&lt;hr&gt;
&lt;h2 id=&quot;production-observability-and-debugging&quot;&gt;Production Observability and Debugging&lt;/h2&gt;
&lt;p&gt;To find problems in a production system, looking at query latency alone is never enough. You have to measure how busy the pool is, how many requests are waiting for a connection, and what the acquisition latency looks like.&lt;/p&gt;
&lt;figure&gt;&lt;img src=&quot;https://raw.githubusercontent.com/rafeuddaraj/rafes-blog-assets/refs/heads/how-database-connection-pools-work-under-the-hood/assets/pool-metrics-dashboard.svg&quot; alt=&quot;Production Observability Metrics Dashboard&quot; loading=&quot;lazy&quot; decoding=&quot;async&quot; width=&quot;800&quot; height=&quot;400&quot;&gt;&lt;figcaption&gt;Production Observability Metrics Dashboard&lt;/figcaption&gt;&lt;/figure&gt;
&lt;p&gt;When debugging, do not rely on guesses. Investigate the issue by following this triage tree:&lt;/p&gt;
&lt;figure&gt;&lt;img src=&quot;https://raw.githubusercontent.com/rafeuddaraj/rafes-blog-assets/refs/heads/how-database-connection-pools-work-under-the-hood/assets/production-debugging-tree.svg&quot; alt=&quot;Production Debugging Decision Tree&quot; loading=&quot;lazy&quot; decoding=&quot;async&quot; width=&quot;800&quot; height=&quot;500&quot;&gt;&lt;figcaption&gt;Production Debugging Decision Tree&lt;/figcaption&gt;&lt;/figure&gt;
&lt;hr&gt;
&lt;h2 id=&quot;understanding-capacity-with-queueing-theory&quot;&gt;Understanding Capacity with Queueing Theory&lt;/h2&gt;
&lt;p&gt;Figuring out the size of your connection pool is not a guessing game. You can get a mathematical estimate using Little&apos;s Law:&lt;/p&gt;
&lt;span class=&quot;katex-display&quot;&gt;&lt;span class=&quot;katex&quot;&gt;&lt;span class=&quot;katex-html&quot; aria-hidden=&quot;true&quot;&gt;&lt;span class=&quot;base&quot;&gt;&lt;span class=&quot;strut&quot; style=&quot;height:0.8778em;vertical-align:-0.1944em;&quot;&gt;&lt;/span&gt;&lt;span class=&quot;mord text&quot;&gt;&lt;span class=&quot;mord&quot;&gt;Concurrency&lt;/span&gt;&lt;/span&gt;&lt;span class=&quot;mspace&quot; style=&quot;margin-right:0.2778em;&quot;&gt;&lt;/span&gt;&lt;span class=&quot;mrel&quot;&gt;≈&lt;/span&gt;&lt;span class=&quot;mspace&quot; style=&quot;margin-right:0.2778em;&quot;&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class=&quot;base&quot;&gt;&lt;span class=&quot;strut&quot; style=&quot;height:0.8889em;vertical-align:-0.1944em;&quot;&gt;&lt;/span&gt;&lt;span class=&quot;mord text&quot;&gt;&lt;span class=&quot;mord&quot;&gt;Throughput&lt;/span&gt;&lt;/span&gt;&lt;span class=&quot;mspace&quot; style=&quot;margin-right:0.2222em;&quot;&gt;&lt;/span&gt;&lt;span class=&quot;mbin&quot;&gt;×&lt;/span&gt;&lt;span class=&quot;mspace&quot; style=&quot;margin-right:0.2222em;&quot;&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class=&quot;base&quot;&gt;&lt;span class=&quot;strut&quot; style=&quot;height:0.8778em;vertical-align:-0.1944em;&quot;&gt;&lt;/span&gt;&lt;span class=&quot;mord text&quot;&gt;&lt;span class=&quot;mord&quot;&gt;Latency&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;
&lt;p&gt;If your system receives 500 requests per second and each connection is busy for an average of 0.1 seconds, your required concurrency will be 50 connections.&lt;/p&gt;
&lt;figure&gt;&lt;img src=&quot;https://raw.githubusercontent.com/rafeuddaraj/rafes-blog-assets/refs/heads/how-database-connection-pools-work-under-the-hood/assets/queueing-theory-concurrency.svg&quot; alt=&quot;Queueing Theory and Little&amp;#x27;s Law for Connection Pools&quot; loading=&quot;lazy&quot; decoding=&quot;async&quot; width=&quot;800&quot; height=&quot;350&quot;&gt;&lt;figcaption&gt;Queueing Theory and Little&apos;s Law for Connection Pools&lt;/figcaption&gt;&lt;/figure&gt;
&lt;p&gt;If your queries or transactions start taking longer, you will need exponentially more connections to handle that exact same amount of traffic.&lt;/p&gt;
&lt;hr&gt;
&lt;h2 id=&quot;balanced-production-architecture&quot;&gt;Balanced Production Architecture&lt;/h2&gt;
&lt;p&gt;When we bring all these concepts together, we get a balanced, production-ready architecture. This setup includes multiple application instances, each with its own bounded connection pool. A central pooler like PgBouncer sits in the middle, and the database connection capacity remains strictly controlled.&lt;/p&gt;
&lt;figure&gt;&lt;img src=&quot;https://raw.githubusercontent.com/rafeuddaraj/rafes-blog-assets/refs/heads/how-database-connection-pools-work-under-the-hood/assets/balanced-production-architecture.svg&quot; alt=&quot;Balanced Production Architecture&quot; loading=&quot;lazy&quot; decoding=&quot;async&quot; width=&quot;800&quot; height=&quot;500&quot;&gt;&lt;figcaption&gt;Balanced Production Architecture&lt;/figcaption&gt;&lt;/figure&gt;
&lt;p&gt;To prevent the entire system from crashing during an incident, you need active circuit breaker policies, timeouts, and retries with jitter at every single layer.&lt;/p&gt;
&lt;figure&gt;&lt;img src=&quot;https://raw.githubusercontent.com/rafeuddaraj/rafes-blog-assets/refs/heads/how-database-connection-pools-work-under-the-hood/assets/full-incident-timeline.svg&quot; alt=&quot;Full Incident Timeline&quot; loading=&quot;lazy&quot; decoding=&quot;async&quot; width=&quot;800&quot; height=&quot;400&quot;&gt;&lt;figcaption&gt;Full Incident Timeline&lt;/figcaption&gt;&lt;/figure&gt;
&lt;hr&gt;
&lt;h2 id=&quot;final-developer-checklist&quot;&gt;Final Developer Checklist&lt;/h2&gt;
&lt;p&gt;To size your pool correctly and keep your system stable, you should follow a solid decision framework and checklist:&lt;/p&gt;
&lt;figure&gt;&lt;img src=&quot;https://raw.githubusercontent.com/rafeuddaraj/rafes-blog-assets/refs/heads/how-database-connection-pools-work-under-the-hood/assets/pool-sizing-framework.svg&quot; alt=&quot;Pool Sizing Decision Framework&quot; loading=&quot;lazy&quot; decoding=&quot;async&quot; width=&quot;800&quot; height=&quot;500&quot;&gt;&lt;figcaption&gt;Pool Sizing Decision Framework&lt;/figcaption&gt;&lt;/figure&gt;
&lt;ul&gt;
&lt;li&gt;Calculate the total number of application instances before setting your &lt;code&gt;pool.max&lt;/code&gt; value.&lt;/li&gt;
&lt;li&gt;Monitor your connection acquisition latency and pool waiting queue regularly on your dashboards.&lt;/li&gt;
&lt;li&gt;Make absolutely sure you &lt;code&gt;release()&lt;/code&gt; your connection in a &lt;code&gt;finally&lt;/code&gt; block as soon as the database work is done.&lt;/li&gt;
&lt;li&gt;Keep your transactions as short as possible.&lt;/li&gt;
&lt;li&gt;Never place external API calls inside a database transaction.&lt;/li&gt;
&lt;li&gt;Configure your pool timeout, query timeout, and request timeout separately.&lt;/li&gt;
&lt;li&gt;If you are running in a serverless environment, make sure to use PgBouncer or an RDS Proxy.&lt;/li&gt;
&lt;li&gt;Implement a reconnect strategy with exponential backoff and jitter to prepare for database restarts and network failures.&lt;/li&gt;
&lt;/ul&gt;
&lt;h3 id=&quot;the-ultimate-mental-model&quot;&gt;The Ultimate Mental Model&lt;/h3&gt;
&lt;p&gt;It is a mistake to think of a connection pool as just a tool for reusing connections. It is essentially a concurrency control layer that sits between your application and your database. It controls exactly how many operations can apply pressure on the database at the exact same time.&lt;/p&gt;
&lt;figure&gt;&lt;img src=&quot;https://raw.githubusercontent.com/rafeuddaraj/rafes-blog-assets/refs/heads/how-database-connection-pools-work-under-the-hood/assets/pool-concurrency-mental-model.svg&quot; alt=&quot;Pool as a Concurrency Control Layer&quot; loading=&quot;lazy&quot; decoding=&quot;async&quot; width=&quot;800&quot; height=&quot;400&quot;&gt;&lt;figcaption&gt;Pool as a Concurrency Control Layer&lt;/figcaption&gt;&lt;/figure&gt;
&lt;p&gt;A database connection is a highly limited resource. Without proper architecture and management, no application can successfully scale in a production environment.&lt;/p&gt;</content:encoded><category>System Architecture</category><category>Database</category><category>Backend Architecture</category><category>Connection Pooling</category><category>Performance Optimization</category><category>Node.js</category><category>PostgreSQL</category><category>System Design</category><category>Under the hood</category></item><item><title>Distributed Locks Under the Hood: Redlock, Fencing Tokens and the Split-Brain Problem</title><link>https://www.rafeuddaraj.me/blog/distributed-locks-redlock-fencing-tokens-explained/</link><guid isPermaLink="true">https://www.rafeuddaraj.me/blog/distributed-locks-redlock-fencing-tokens-explained/</guid><description>A deep architectural dive into why standard Redis locks fail in distributed systems, covering lease expiries, paused processes, and how database-level fencing tokens guarantee absolute correctness.</description><pubDate>Tue, 01 Sep 2026 19:18:32 GMT</pubDate><content:encoded>&lt;p&gt;Imagine a production system where multiple Node.js servers run simultaneously. Let us say you have a background job running every night that executes &lt;code&gt;generateMonthlyInvoices()&lt;/code&gt;. Suddenly, you notice two servers executed the same job at the exact same time, and a customer got billed twice. Or maybe a payment processed twice, or two different workers updated a shared inventory row at once. In these situations, the most obvious solution that comes to an engineer&apos;s mind is placing a Redis lock right before the critical section. At first glance, putting a Redis coordination point between Worker A and Worker B seems to solve the problem. But the real question is, what actually happens if Worker A grabs the lock but fails to finish the work before the lock&apos;s TTL expires? This single question begins a journey into one of the most complex architectures in distributed systems.&lt;/p&gt;
&lt;h2 id=&quot;the-real-objective-behind-locking&quot;&gt;The Real Objective Behind Locking&lt;/h2&gt;
&lt;p&gt;We first need to understand what a lock actually tries to solve. Defining the engineering requirement is more important here than worrying about the code. Our main goal is to ensure only one valid worker can perform a critical operation at a time. Along with this, if a worker crashes, another worker should eventually be able to take over the job. Also, the system must not enter an unsafe state even if the infrastructure fails. These three properties are known as safety, liveness, and fault tolerance. Safety ensures two workers cannot perform conflicting operations on a protected resource at the same time. Liveness guarantees that if a worker crashes, the entire system does not stay stuck forever. Fault tolerance ensures the system behaves predictably even if a Redis node, network, or application instance fails. A lock does not just control concurrency; it also requires designing for failure recovery.&lt;/p&gt;
&lt;p&gt;Because of horizontal scaling, running multiple instances of the same application is perfectly normal. Multiple workers can easily try to process the same job or resource. A database transaction cannot always protect the entire distributed workflow, so a Redis lock initially feels like an easy solution. But if an old worker continues its task after the lock expires, a new worker might grab the lock. The stale operation from the old worker can then cause severe damage to the entire system.&lt;/p&gt;
&lt;figure&gt;&lt;img src=&quot;https://raw.githubusercontent.com/rafeuddaraj/rafes-blog-assets/refs/heads/distributed-locks-redlock-fencing-tokens-explained/assets/distributed-lock-contention.svg&quot; alt=&quot;Distributed Lock Contention&quot; loading=&quot;lazy&quot; decoding=&quot;async&quot; width=&quot;800&quot; height=&quot;400&quot;&gt;&lt;figcaption&gt;Distributed Lock Contention&lt;/figcaption&gt;&lt;/figure&gt;
&lt;div class=&quot;callout&quot; role=&quot;note&quot; data-type=&quot;note&quot;&gt;
&lt;p class=&quot;callout-title&quot;&gt;Mental Model Context&lt;/p&gt;
&lt;p&gt;A process staying alive and a lock staying alive are two completely different things. A worker might be alive in memory and keep an active network connection, but its lock authority could have expired a long time ago.&lt;/p&gt;
&lt;/div&gt;
&lt;h2 id=&quot;from-locks-to-time-bound-leases&quot;&gt;From Locks to Time-Bound Leases&lt;/h2&gt;
&lt;p&gt;To understand this simply, we can use the analogy of a single access card for a warehouse. Imagine a special room inside a warehouse where only one operator can enter at a time. An operator takes an access card and starts working inside, but the security system states this card will automatically become invalid after thirty minutes. If the operator works for forty-five minutes, a second operator will get a new card after thirty minutes and enter the room. The first operator is still inside working. The security system never guaranteed that only one person would be in the room. It only guaranteed that the first operator&apos;s access would remain valid for a specific timeframe. This exact concept is the origin of the lease.&lt;/p&gt;
&lt;p&gt;When we run the &lt;code&gt;SET resource:123 worker-token NX PX 30000&lt;/code&gt; command in Redis, &lt;code&gt;NX&lt;/code&gt; ensures the key only sets if it does not already exist, and &lt;code&gt;PX 30000&lt;/code&gt; ensures the key expires after thirty seconds. As a reader, you might think this is the perfect solution because one person taking the lock prevents others from entering. But if Worker A crashes after taking the lock and the lock has no expiration, that lock stays there forever. Worker B will never be able to acquire the resource. This is exactly why we need a TTL or Time To Live. Using a long TTL makes crash recovery very slow, while a short TTL creates the risk of the work outliving the lease. The TTL actually gives the lock a time-bound ownership, which we call a lease. A lease means you have authority over this resource, but it is not indefinite. It is only valid for a specific duration. From the worker&apos;s perspective, it feels like acquiring a lock. However, from the system&apos;s perspective, that authority is strictly limited to the lease expiration time.&lt;/p&gt;
&lt;h2 id=&quot;the-race-condition-in-lock-release&quot;&gt;The Race Condition in Lock Release&lt;/h2&gt;
&lt;p&gt;After understanding the lease concept, we need to discuss the internal race condition of the lock release mechanism. Imagine Worker A acquires a lock and then pauses for a long time for some reason. Thirty seconds later, the lock expires, and Worker B acquires a new lock. Right at this moment, Worker A resumes and directly executes the &lt;code&gt;DEL resource:123&lt;/code&gt; command. A catastrophic event happens here. Worker A is not actually deleting its own lock; it is deleting Worker B&apos;s brand new lock. As a result, Worker B&apos;s lock disappears, and the system enters a completely unsafe state.&lt;/p&gt;
&lt;figure&gt;&lt;img src=&quot;https://raw.githubusercontent.com/rafeuddaraj/rafes-blog-assets/refs/heads/distributed-locks-redlock-fencing-tokens-explained/assets/lock-release-race-condition.svg&quot; alt=&quot;Lock Release Race Condition&quot; loading=&quot;lazy&quot; decoding=&quot;async&quot; width=&quot;800&quot; height=&quot;450&quot;&gt;&lt;figcaption&gt;Lock Release Race Condition&lt;/figcaption&gt;&lt;/figure&gt;
&lt;p&gt;To avoid this type of production bug, you must use a unique ownership token or a random lock token with the lock. A random string is set as the lock value. When releasing it, the logic checks if the current lock value matches the worker&apos;s token. If they match, the lock is deleted. Otherwise, the operation is rejected. We usually use a Lua script or an atomic conditional operation to handle this release process safely:&lt;/p&gt;
&lt;div class=&quot;expressive-code&quot;&gt;&lt;style&gt;.expressive-code{font-family:var(--ec-uiFontFml);font-size:var(--ec-uiFontSize);font-weight:var(--ec-uiFontWg);line-height:var(--ec-uiLineHt);text-size-adjust:none;-webkit-text-size-adjust:none}.expressive-code *:not(:is(svg, svg *)){all:revert;box-sizing:border-box}.expressive-code pre{display:flex;margin:0;padding:0;border:var(--ec-brdWd) solid var(--ec-brdCol);border-radius:calc(var(--ec-brdRad) + var(--ec-brdWd));background:var(--ec-codeBg)}.expressive-code pre:focus-visible{outline:3px solid var(--ec-focusBrd);outline-offset:-3px}.expressive-code pre &gt; code{all:unset;display:block;flex:1 0 100%;padding:var(--ec-codePadBlk) 0;color:var(--ec-codeFg);font-family:var(--ec-codeFontFml);font-size:var(--ec-codeFontSize);font-weight:var(--ec-codeFontWg);line-height:var(--ec-codeLineHt)}.expressive-code pre{overflow-x:auto}.expressive-code pre.wrap .ec-line .code{white-space:pre-wrap;overflow-wrap:break-word;min-width:min(20ch, var(--ecMaxLine, 20ch))}.expressive-code pre.wrap .ec-line .code span.indent{white-space:pre}.expressive-code pre::-webkit-scrollbar,.expressive-code pre::-webkit-scrollbar-track{background-color:inherit;border-radius:calc(var(--ec-brdRad) + var(--ec-brdWd));border-top-left-radius:0;border-top-right-radius:0}.expressive-code pre::-webkit-scrollbar-thumb{background-color:var(--ec-sbThumbCol);border:4px solid transparent;background-clip:content-box;border-radius:10px}.expressive-code pre::-webkit-scrollbar-thumb:hover{background-color:var(--ec-sbThumbHoverCol)}.expressive-code pre::-webkit-scrollbar-corner{background:transparent}.expressive-code .ec-line{direction:ltr;unicode-bidi:isolate;display:grid;grid-template-areas:&apos;gutter code&apos;;grid-template-columns:auto 1fr;position:relative}.expressive-code .ec-line .gutter{grid-area:gutter;color:var(--ec-gtrFg)}.expressive-code .ec-line .gutter &gt; *{pointer-events:none;user-select:none;-webkit-user-select:none}.expressive-code .ec-line .gutter ~ .code{--ecLineBrdCol:var(--ec-gtrBrdCol)}.expressive-code .ec-line.highlight .gutter{color:var(--ec-gtrHlFg)}.expressive-code .ec-line .code{grid-area:code;position:relative;box-sizing:content-box;padding-inline-start:calc(var(--ecIndent, 0ch) + var(--ec-codePadInl) - var(--ecGtrBrdWd));padding-inline-end:var(--ec-codePadInl);text-indent:calc(var(--ecIndent, 0ch) * -1)}.expressive-code .ec-line .code::before,.expressive-code .ec-line .code::after,.expressive-code .ec-line .code :where(*){text-indent:0}.expressive-code .ec-line .code{--ecGtrBrdWd:var(--ec-gtrBrdWd);border-inline-start:var(--ecGtrBrdWd) solid var(--ecLineBrdCol, transparent)}.expressive-code .sr-only{position:absolute;width:1px;height:1px;padding:0;margin:-1px;overflow:hidden;clip:rect(0, 0, 0, 0);white-space:nowrap;border-width:0}.expressive-code .ec-line.mark{--tmLineBgCol:var(--ec-tm-markBg)}.expressive-code .ec-line.mark .code{--ecLineBrdCol:var(--ec-tm-markBrdCol)}.expressive-code .ec-line.ins{--tmLineBgCol:var(--ec-tm-insBg);--tmLabel:var(--ec-tm-insDiffIndContent)}.expressive-code .ec-line.ins .code{--ecLineBrdCol:var(--ec-tm-insBrdCol)}.expressive-code .ec-line.ins .code::before{color:var(--ec-tm-insDiffIndCol)}.expressive-code .ec-line.del{--tmLineBgCol:var(--ec-tm-delBg);--tmLabel:var(--ec-tm-delDiffIndContent)}.expressive-code .ec-line.del .code{--ecLineBrdCol:var(--ec-tm-delBrdCol)}.expressive-code .ec-line.del .code::before{color:var(--ec-tm-delDiffIndCol)}.expressive-code .ec-line.mark,.expressive-code .ec-line.ins,.expressive-code .ec-line.del{background:var(--tmLineBgCol)}.expressive-code .ec-line.mark .code,.expressive-code .ec-line.ins .code,.expressive-code .ec-line.del .code{--ecGtrBrdWd:var(--ec-tm-lineMarkerAccentWd)}.expressive-code .ec-line.mark .code::before,.expressive-code .ec-line.ins .code::before,.expressive-code .ec-line.del .code::before{display:block;position:absolute;left:0;box-sizing:border-box;content:var(--tmLabel, &apos; &apos;);padding-inline-start:var(--ec-tm-lineDiffIndMargLeft);text-align:center;white-space:pre}.expressive-code .ec-line.mark.tm-label .code::before,.expressive-code .ec-line.ins.tm-label .code::before,.expressive-code .ec-line.del.tm-label .code::before{background:var(--ecLineBrdCol);padding:0 calc(var(--ec-tm-lineMarkerLabelPadInl) + var(--ec-tm-lineMarkerAccentWd)) 0 var(--ec-tm-lineMarkerLabelPadInl);color:var(--ec-tm-lineMarkerLabelCol)}.expressive-code .ec-line mark{--tmInlineBgCol:var(--ec-tm-markBg);--tmInlineBrdCol:var(--ec-tm-markBrdCol)}.expressive-code .ec-line ins{--tmInlineBgCol:var(--ec-tm-insBg);--tmInlineBrdCol:var(--ec-tm-insBrdCol)}.expressive-code .ec-line del{--tmInlineBgCol:var(--ec-tm-delBg);--tmInlineBrdCol:var(--ec-tm-delBrdCol)}.expressive-code .ec-line mark,.expressive-code .ec-line ins,.expressive-code .ec-line del{all:unset;display:inline-block;position:relative;--tmBrdL:var(--ec-tm-inlMarkerBrdWd);--tmBrdR:var(--ec-tm-inlMarkerBrdWd);--tmRadL:var(--ec-tm-inlMarkerBrdRad);--tmRadR:var(--ec-tm-inlMarkerBrdRad);margin-inline:0.025rem;padding-inline:var(--ec-tm-inlMarkerPad);border-radius:var(--tmRadL) var(--tmRadR) var(--tmRadR) var(--tmRadL);background:var(--tmInlineBgCol);background-clip:padding-box}.expressive-code .ec-line mark.open-start,.expressive-code .ec-line ins.open-start,.expressive-code .ec-line del.open-start{margin-inline-start:0;padding-inline-start:0;--tmBrdL:0px;--tmRadL:0}.expressive-code .ec-line mark.open-end,.expressive-code .ec-line ins.open-end,.expressive-code .ec-line del.open-end{margin-inline-end:0;padding-inline-end:0;--tmBrdR:0px;--tmRadR:0}.expressive-code .ec-line mark::before,.expressive-code .ec-line ins::before,.expressive-code .ec-line del::before{content:&apos;&apos;;position:absolute;pointer-events:none;display:inline-block;inset:0;border-radius:var(--tmRadL) var(--tmRadR) var(--tmRadR) var(--tmRadL);border:var(--ec-tm-inlMarkerBrdWd) solid var(--tmInlineBrdCol);border-inline-width:var(--tmBrdL) var(--tmBrdR)}.expressive-code .frame{all:unset;position:relative;display:block;--header-border-radius:calc(var(--ec-brdRad) + var(--ec-brdWd));--tab-border-radius:calc(var(--ec-frm-edTabBrdRad) + var(--ec-brdWd));--button-spacing:0.4rem;--code-background:var(--ec-frm-edBg);border-radius:var(--header-border-radius);box-shadow:var(--ec-frm-frameBoxShdCssVal)}.expressive-code .frame .header{display:none;z-index:1;position:relative;border-radius:var(--header-border-radius) var(--header-border-radius) 0 0}.expressive-code .frame.has-title pre,.expressive-code .frame.has-title code,.expressive-code .frame.is-terminal pre,.expressive-code .frame.is-terminal code{border-top:none;border-top-left-radius:0;border-top-right-radius:0}.expressive-code .frame .title:empty:before{content:&apos;\a0&apos;}.expressive-code .frame.has-title:not(.is-terminal){--button-spacing:calc(1.9rem + 2 * (var(--ec-uiPadBlk) + var(--ec-frm-edActTabIndHt)))}.expressive-code .frame.has-title:not(.is-terminal) .title{position:relative;color:var(--ec-frm-edActTabFg);background:var(--ec-frm-edActTabBg);background-clip:padding-box;margin-block-start:var(--ec-frm-edTabsMargBlkStart);padding:calc(var(--ec-uiPadBlk) + var(--ec-frm-edActTabIndHt)) var(--ec-uiPadInl);border:var(--ec-brdWd) solid var(--ec-frm-edActTabBrdCol);border-radius:var(--tab-border-radius) var(--tab-border-radius) 0 0;border-bottom:none;overflow:hidden}.expressive-code .frame.has-title:not(.is-terminal) .title::after{content:&apos;&apos;;position:absolute;pointer-events:none;inset:0;border-top:var(--ec-frm-edActTabIndHt) solid var(--ec-frm-edActTabIndTopCol);border-bottom:var(--ec-frm-edActTabIndHt) solid var(--ec-frm-edActTabIndBtmCol)}.expressive-code .frame.has-title:not(.is-terminal) .header{display:flex;background:linear-gradient(to top, var(--ec-frm-edTabBarBrdBtmCol) var(--ec-brdWd), transparent var(--ec-brdWd)),linear-gradient(var(--ec-frm-edTabBarBg), var(--ec-frm-edTabBarBg));background-repeat:no-repeat;padding-inline-start:var(--ec-frm-edTabsMargInlStart)}.expressive-code .frame.has-title:not(.is-terminal) .header::before{content:&apos;&apos;;position:absolute;pointer-events:none;inset:0;border:var(--ec-brdWd) solid var(--ec-frm-edTabBarBrdCol);border-radius:inherit;border-bottom:none}.expressive-code .frame.is-terminal{--button-spacing:calc(1.9rem + var(--ec-brdWd) + 2 * var(--ec-uiPadBlk));--code-background:var(--ec-frm-trmBg)}.expressive-code .frame.is-terminal .header{display:flex;align-items:center;justify-content:center;padding-block:var(--ec-uiPadBlk);padding-block-end:calc(var(--ec-uiPadBlk) + var(--ec-brdWd));position:relative;font-weight:500;letter-spacing:0.025ch;color:var(--ec-frm-trmTtbFg);background:var(--ec-frm-trmTtbBg);border:var(--ec-brdWd) solid var(--ec-brdCol);border-bottom:none}.expressive-code .frame.is-terminal .header::before{content:&apos;&apos;;position:absolute;pointer-events:none;left:var(--ec-uiPadInl);width:2.1rem;height:0.56rem;line-height:0;background-color:var(--ec-frm-trmTtbDotsFg);opacity:var(--ec-frm-trmTtbDotsOpa);-webkit-mask-image:var(--ec-frm-trmIcon);-webkit-mask-repeat:no-repeat;mask-image:var(--ec-frm-trmIcon);mask-repeat:no-repeat}.expressive-code .frame.is-terminal .header::after{content:&apos;&apos;;position:absolute;pointer-events:none;inset:0;border-bottom:var(--ec-brdWd) solid var(--ec-frm-trmTtbBrdBtmCol)}.expressive-code .frame pre{background:var(--code-background)}.expressive-code .copy{display:flex;gap:0.25rem;flex-direction:row;position:absolute;inset-block-start:calc(var(--ec-brdWd) + var(--button-spacing));inset-inline-end:calc(var(--ec-brdWd) + var(--ec-uiPadInl) / 2)}@media (scripting: none){.expressive-code .copy{display:none}}.expressive-code .copy{direction:ltr;unicode-bidi:isolate}.expressive-code .copy button{position:relative;align-self:flex-end;margin:0;padding:0;border:none;border-radius:0.2rem;z-index:1;cursor:pointer;transition-property:opacity, background, border-color;transition-duration:0.2s;transition-timing-function:cubic-bezier(0.25, 0.46, 0.45, 0.94);width:2.5rem;height:2.5rem;background:var(--code-background);opacity:0.75}.expressive-code .copy button div{position:absolute;inset:0;border-radius:inherit;background:var(--ec-frm-inlBtnBg);opacity:var(--ec-frm-inlBtnBgIdleOpa);transition-property:inherit;transition-duration:inherit;transition-timing-function:inherit}.expressive-code .copy button::before{content:&apos;&apos;;position:absolute;pointer-events:none;inset:0;border-radius:inherit;border:var(--ec-brdWd) solid var(--ec-frm-inlBtnBrd);opacity:var(--ec-frm-inlBtnBrdOpa)}.expressive-code .copy button::after{content:&apos;&apos;;position:absolute;pointer-events:none;inset:0;background-color:var(--ec-frm-inlBtnFg);-webkit-mask-image:var(--ec-frm-copyIcon);-webkit-mask-repeat:no-repeat;mask-image:var(--ec-frm-copyIcon);mask-repeat:no-repeat;margin:0.475rem;line-height:0}.expressive-code .copy button:hover,.expressive-code .copy button:focus:focus-visible{opacity:1}.expressive-code .copy button:hover div,.expressive-code .copy button:focus:focus-visible div{opacity:var(--ec-frm-inlBtnBgHoverOrFocusOpa)}.expressive-code .copy button:active{opacity:1}.expressive-code .copy button:active div{opacity:var(--ec-frm-inlBtnBgActOpa)}.expressive-code .copy .feedback{--tooltip-arrow-size:0.35rem;--tooltip-bg:var(--ec-frm-tooltipSuccessBg);color:var(--ec-frm-tooltipSuccessFg);pointer-events:none;user-select:none;-webkit-user-select:none;position:relative;align-self:center;background-color:var(--tooltip-bg);z-index:99;padding:0.125rem 0.75rem;border-radius:0.2rem;margin-inline-end:var(--tooltip-arrow-size);opacity:0;transition-property:opacity, transform;transition-duration:0.2s;transition-timing-function:ease-in-out;transform:translate3d(0, 0.25rem, 0)}.expressive-code .copy .feedback::after{content:&apos;&apos;;position:absolute;pointer-events:none;top:calc(50% - var(--tooltip-arrow-size));inset-inline-end:calc(-2 * (var(--tooltip-arrow-size) - 0.5px));border:var(--tooltip-arrow-size) solid transparent;border-inline-start-color:var(--tooltip-bg)}.expressive-code .copy .feedback.show{opacity:1;transform:translate3d(0, 0, 0)}@media (hover: hover){.expressive-code{}.expressive-code .copy button{opacity:0;width:2rem;height:2rem}.expressive-code .frame:hover .copy button:not(:hover),.expressive-code .frame:focus-within :focus-visible ~ .copy button:not(:hover),.expressive-code .frame .copy .feedback.show ~ button:not(:hover){opacity:0.75}}.expressive-code :nth-child(1 of .ec-line) .code{padding-inline-end:calc(2rem + var(--ec-codePadInl))}:root{--ec-brdRad:0.75rem;--ec-brdWd:1.5px;--ec-brdCol:var(--code-line);--ec-codeFontFml:var(--font-code);--ec-codeFontSize:0.875rem;--ec-codeFontWg:400;--ec-codeLineHt:1.75;--ec-codePadBlk:1rem;--ec-codePadInl:1.125rem;--ec-codeBg:var(--code-bg);--ec-codeFg:#e6edf3;--ec-codeSelBg:#264f78;--ec-gtrFg:#6e7681;--ec-gtrBrdCol:#6e768133;--ec-gtrBrdWd:1.5px;--ec-gtrHlFg:#e6edf3;--ec-uiFontFml:var(--font-mono);--ec-uiFontSize:0.75rem;--ec-uiFontWg:400;--ec-uiLineHt:1.65;--ec-uiPadBlk:0.25rem;--ec-uiPadInl:1rem;--ec-uiSelBg:#6e768166;--ec-uiSelFg:#e6edf3;--ec-focusBrd:#1f6feb;--ec-sbThumbCol:#8b949e33;--ec-sbThumbHoverCol:#8b949e3d;--ec-tm-lineMarkerAccentMarg:0rem;--ec-tm-lineMarkerAccentWd:0.15rem;--ec-tm-lineMarkerLabelPadInl:0.2rem;--ec-tm-lineMarkerLabelCol:white;--ec-tm-lineDiffIndMargLeft:0.3rem;--ec-tm-inlMarkerBrdWd:1.5px;--ec-tm-inlMarkerBrdRad:0.2rem;--ec-tm-inlMarkerPad:0.15rem;--ec-tm-insDiffIndContent:&apos;+&apos;;--ec-tm-delDiffIndContent:&apos;-&apos;;--ec-tm-markBg:#264a8980;--ec-tm-markBrdCol:#5570b3d0;--ec-tm-insBg:#26561c80;--ec-tm-insBrdCol:#4e7e41d0;--ec-tm-insDiffIndCol:#7eb070d0;--ec-tm-delBg:#81322b80;--ec-tm-delBrdCol:#ae594fd0;--ec-tm-delDiffIndCol:#e68a7ed0;--ec-frm-shdCol:#0000005b;--ec-frm-frameBoxShdCssVal:none;--ec-frm-edActTabBg:var(--code-bg);--ec-frm-edActTabFg:var(--code-muted);--ec-frm-edActTabBrdCol:transparent;--ec-frm-edActTabIndHt:1.5px;--ec-frm-edActTabIndTopCol:transparent;--ec-frm-edActTabIndBtmCol:#0d1117;--ec-frm-edTabsMargInlStart:0;--ec-frm-edTabsMargBlkStart:0;--ec-frm-edTabBrdRad:0.75rem;--ec-frm-edTabBarBg:var(--code-bg);--ec-frm-edTabBarBrdCol:var(--code-line);--ec-frm-edTabBarBrdBtmCol:var(--code-line);--ec-frm-edBg:var(--code-bg);--ec-frm-trmTtbFg:var(--code-muted);--ec-frm-trmTtbDotsFg:var(--code-muted);--ec-frm-trmTtbDotsOpa:0.15;--ec-frm-trmTtbBg:var(--code-bg);--ec-frm-trmTtbBrdBtmCol:var(--code-line);--ec-frm-trmBg:var(--code-bg);--ec-frm-inlBtnBg:var(--code-ink);--ec-frm-inlBtnBgIdleOpa:0;--ec-frm-inlBtnBgHoverOrFocusOpa:0.2;--ec-frm-inlBtnBgActOpa:0.3;--ec-frm-inlBtnFg:var(--code-ink);--ec-frm-inlBtnBrd:var(--code-line);--ec-frm-inlBtnBrdOpa:0.4;--ec-frm-tooltipSuccessBg:var(--color-emerald);--ec-frm-tooltipSuccessFg:var(--color-bg);--ec-frm-copyIcon:url(&quot;data:image/svg+xml,%3Csvg%20xmlns%3D&apos;http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg&apos;%20viewBox%3D&apos;0%200%2024%2024&apos;%20fill%3D&apos;none&apos;%20stroke%3D&apos;black&apos;%20stroke-width%3D&apos;1.75&apos;%3E%3Cpath%20d%3D&apos;M3%2019a2%202%200%200%201-1-2V2a2%202%200%200%201%201-1h13a2%202%200%200%201%202%201&apos;%2F%3E%3Crect%20x%3D&apos;6&apos;%20y%3D&apos;5&apos;%20width%3D&apos;16&apos;%20height%3D&apos;18&apos;%20rx%3D&apos;1.5&apos;%20ry%3D&apos;1.5&apos;%2F%3E%3C%2Fsvg%3E&quot;);--ec-frm-trmIcon:url(&quot;data:image/svg+xml,%3Csvg%20xmlns%3D&apos;http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg&apos;%20viewBox%3D&apos;0%200%2060%2016&apos;%20preserveAspectRatio%3D&apos;xMidYMid%20meet&apos;%3E%3Ccircle%20cx%3D&apos;8&apos;%20cy%3D&apos;8&apos;%20r%3D&apos;8&apos;%2F%3E%3Ccircle%20cx%3D&apos;30&apos;%20cy%3D&apos;8&apos;%20r%3D&apos;8&apos;%2F%3E%3Ccircle%20cx%3D&apos;52&apos;%20cy%3D&apos;8&apos;%20r%3D&apos;8&apos;%2F%3E%3C%2Fsvg%3E&quot;)}.expressive-code .ec-line :where(span[style^=&apos;--&apos;]:not([class])){color:var(--0, inherit);background-color:var(--0bg, transparent);font-style:var(--0fs, inherit);font-weight:var(--0fw, inherit);text-decoration:var(--0td, inherit)}&lt;/style&gt;&lt;script type=&quot;module&quot; src=&quot;/_astro/ec.0vx5m.js&quot;&gt;&lt;/script&gt;&lt;figure class=&quot;frame has-title&quot;&gt;&lt;figcaption class=&quot;header&quot;&gt;&lt;span class=&quot;title&quot;&gt;Lua&lt;/span&gt;&lt;/figcaption&gt;&lt;pre data-language=&quot;lua&quot;&gt;&lt;code&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;if&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; redis.&lt;/span&gt;&lt;span style=&quot;--0:#79C0FF&quot;&gt;call&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;(&lt;/span&gt;&lt;span style=&quot;--0:#A5D6FF&quot;&gt;&quot;get&quot;&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;, KEYS[&lt;/span&gt;&lt;span style=&quot;--0:#79C0FF&quot;&gt;1&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;]) &lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;==&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; ARGV[&lt;/span&gt;&lt;span style=&quot;--0:#79C0FF&quot;&gt;1&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;] &lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;then&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span class=&quot;indent&quot;&gt;    &lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;return&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; redis.&lt;/span&gt;&lt;span style=&quot;--0:#79C0FF&quot;&gt;call&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;(&lt;/span&gt;&lt;span style=&quot;--0:#A5D6FF&quot;&gt;&quot;del&quot;&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;, KEYS[&lt;/span&gt;&lt;span style=&quot;--0:#79C0FF&quot;&gt;1&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;])&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;else&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span class=&quot;indent&quot;&gt;    &lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;return&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; &lt;/span&gt;&lt;span style=&quot;--0:#79C0FF&quot;&gt;0&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;end&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;/code&gt;&lt;/pre&gt;&lt;div class=&quot;copy&quot;&gt;&lt;div aria-live=&quot;polite&quot;&gt;&lt;/div&gt;&lt;button title=&quot;Copy to clipboard&quot; data-copied=&quot;Copied!&quot; data-code=&quot;if redis.call(&amp;#x22;get&amp;#x22;, KEYS[1]) == ARGV[1] then    return redis.call(&amp;#x22;del&amp;#x22;, KEYS[1])else    return 0end&quot;&gt;&lt;div&gt;&lt;/div&gt;&lt;/button&gt;&lt;/div&gt;&lt;/figure&gt;&lt;/div&gt;
&lt;p&gt;But you need to keep a very subtle difference in mind here. A random lock token only identifies ownership. It cannot prevent a stale worker from executing.&lt;/p&gt;
&lt;div class=&quot;callout&quot; role=&quot;note&quot; data-type=&quot;warning&quot;&gt;
&lt;p class=&quot;callout-title&quot;&gt;Dangerous Assumption&lt;/p&gt;
&lt;p&gt;A random lock token only guarantees a safe unlock. It never guarantees that your worker&apos;s execution context is still valid.&lt;/p&gt;
&lt;/div&gt;
&lt;h2 id=&quot;redis-failover-and-the-split-brain-problem&quot;&gt;Redis Failover and the Split-Brain Problem&lt;/h2&gt;
&lt;p&gt;Up to this point, our architecture relied on a single Redis instance. However, Redis itself can fail in a production system. Let us assume your architecture has a Redis primary and a Redis replica. Worker A takes a lock from the primary node, but the primary node crashes immediately after. Before the lock data synchronizes or replicates to the replica, the replica node promotes itself to the new primary. In this state, Worker B sends a request to the new primary node and successfully acquires the lock. Now Worker A thinks it owns the lock, and Worker B also thinks it owns the lock. This is the most dangerous failure mode in distributed locking, known as the split-brain problem.&lt;/p&gt;
&lt;figure&gt;&lt;img src=&quot;https://raw.githubusercontent.com/rafeuddaraj/rafes-blog-assets/refs/heads/distributed-locks-redlock-fencing-tokens-explained/assets/redis-failover-split-brain.svg&quot; alt=&quot;Redis Failover Split Brain&quot; loading=&quot;lazy&quot; decoding=&quot;async&quot; width=&quot;1600&quot; height=&quot;900&quot;&gt;&lt;figcaption&gt;Redis Failover Split Brain&lt;/figcaption&gt;&lt;/figure&gt;
&lt;p&gt;We need to establish a critical engineering principle here. High availability does not mean correctness. A Redis replica failover certainly helps keep your system available, but if the lock state is not perfectly preserved, this very process of increasing availability can break your system&apos;s safety. We actually want a locking mechanism where, even if the infrastructure fails, two workers can never simultaneously become valid owners.&lt;/p&gt;
&lt;h2 id=&quot;redlock-and-the-illusion-of-time&quot;&gt;Redlock and the Illusion of Time&lt;/h2&gt;
&lt;p&gt;The Redlock algorithm was introduced to handle the failure of a single Redis node. Redlock essentially uses multiple independent Redis instances instead of just one. Imagine you have five independent Redis nodes. A worker will try to acquire a lock on all five of these nodes. It will only consider the lock valid if it successfully acquires it on a majority, or at least three nodes. If two workers try to get the lock at the same time, their majority sets will always share at least one common node. This allows the distributed quorum concept to work. But getting a majority is not enough on its own. The time spent on the acquisition is also incredibly important.&lt;/p&gt;
&lt;p&gt;According to the Redlock acquisition flow, the worker first records a start timestamp and tries to lock the five nodes one by one. After getting a majority, it checks how much total time it took to acquire the lock. The lock is only considered acquired if there is still validity remaining after subtracting the elapsed time. But this is exactly where the biggest hidden assumption of Redlock lies, and that is time. Redlock&apos;s validity relies entirely on time measurement. In a real production environment, countless things can happen, such as network delays, clock drift, process scheduling, garbage collection pauses, CPU starvation, VM pauses, container throttling, or network partitions. A worker might think its lock is still valid from its own perspective, but from the perspective of other parts of the distributed system, that lease might have expired a long time ago.&lt;/p&gt;
&lt;div class=&quot;callout&quot; role=&quot;note&quot; data-type=&quot;warning&quot;&gt;
&lt;p class=&quot;callout-title&quot;&gt;Redlock Vulnerability&lt;/p&gt;
&lt;p&gt;Majority intersection alone cannot solve the entire correctness problem. Timing and network delays are always unpredictable in distributed systems.&lt;/p&gt;
&lt;/div&gt;
&lt;h2 id=&quot;the-most-dangerous-failure-paused-worker&quot;&gt;The Most Dangerous Failure: Paused Worker&lt;/h2&gt;
&lt;p&gt;The most central failure scenario of the entire distributed locking architecture is the paused worker. Imagine Worker A successfully acquires a lock and starts working. Suddenly, Worker A suffers a long garbage collection pause, CPU starvation, VM suspension, or network stall and pauses completely. During this pause, its lock lease expires. Following the system rules, Worker B acquires a new lock and successfully finishes its job. A little while later, Worker A finishes its pause and resumes. Worker A has no idea that it was paused. It still thinks it owns the lock and tries to write its old operation to the database.&lt;/p&gt;
&lt;figure&gt;&lt;img src=&quot;https://raw.githubusercontent.com/rafeuddaraj/rafes-blog-assets/refs/heads/distributed-locks-redlock-fencing-tokens-explained/assets/paused-worker-timeline.svg&quot; alt=&quot;Paused Worker Timeline&quot; loading=&quot;lazy&quot; decoding=&quot;async&quot; width=&quot;800&quot; height=&quot;450&quot;&gt;&lt;figcaption&gt;Paused Worker Timeline&lt;/figcaption&gt;&lt;/figure&gt;
&lt;p&gt;The real problem here is that nobody stopped the old worker. A lock expiring does not mean Worker A&apos;s process will automatically stop. A lock release or expiration only changes the system&apos;s state; it cannot physically kill a running code execution. This is a fundamental truth of distributed systems.&lt;/p&gt;
&lt;h2 id=&quot;fencing-tokens-the-ultimate-correctness-guarantee&quot;&gt;Fencing Tokens: The Ultimate Correctness Guarantee&lt;/h2&gt;
&lt;p&gt;We need to introduce the fencing token concept to solve this terrifying problem of the paused worker. When Worker A takes a lock, it does not just receive a lock. The lock service also gives it a monotonically increasing number, like Token 33. A while later, when the lease expires and Worker B takes a new lock, it gets Token 34. The resource itself now knows that the last accepted token it received was 34. If Worker A comes back from its pause and tries to write using Token 33, the resource will see that 33 is smaller than the current 34. It will reject the operation immediately. On the other hand, Worker B&apos;s token is 34, so the system will accept it without any issue.&lt;/p&gt;
&lt;figure&gt;&lt;img src=&quot;https://raw.githubusercontent.com/rafeuddaraj/rafes-blog-assets/refs/heads/distributed-locks-redlock-fencing-tokens-explained/assets/complete-failure-timeline.svg&quot; alt=&quot;Complete Failure Timeline&quot; loading=&quot;lazy&quot; decoding=&quot;async&quot; width=&quot;900&quot; height=&quot;300&quot;&gt;&lt;figcaption&gt;Complete Failure Timeline&lt;/figcaption&gt;&lt;/figure&gt;
&lt;p&gt;The core idea here is that even if the old worker&apos;s process remains alive, its authority has become obsolete. It is very important to clearly understand the difference between a random lock token and a fencing token. A random lock token can only provide uniqueness, but it cannot provide ordering. A fencing token has an ordering that proves which owner is newer. The random lock token answers who owns this lock, while the fencing token answers which owner is newer.&lt;/p&gt;
&lt;div class=&quot;callout&quot; role=&quot;note&quot; data-type=&quot;note&quot;&gt;
&lt;p class=&quot;callout-title&quot;&gt;Fencing Rule&lt;/p&gt;
&lt;p&gt;Generating the token is a coordination problem itself. You have to create this monotonically increasing token using a database sequence, a ZooKeeper version, or a consensus-backed counter.&lt;/p&gt;
&lt;/div&gt;
&lt;h2 id=&quot;database-level-fencing-enforcement&quot;&gt;Database-Level Fencing Enforcement&lt;/h2&gt;
&lt;p&gt;To utilize the fencing token correctly, you must avoid a common architectural mistake. If the worker takes the token from the lock service and writes directly to the database, and the database knows nothing about the token, then the fencing token is completely useless. The correct architecture requires the database or the resource itself to reject stale operations.&lt;/p&gt;
&lt;p&gt;Think of a practical PostgreSQL example. We can create a table with columns named &lt;code&gt;id&lt;/code&gt;, &lt;code&gt;value&lt;/code&gt;, and &lt;code&gt;last_fencing_token&lt;/code&gt;. When the worker writes, it will also send its token. The query will look something like this:&lt;/p&gt;
&lt;div class=&quot;expressive-code&quot;&gt;&lt;figure class=&quot;frame has-title&quot;&gt;&lt;figcaption class=&quot;header&quot;&gt;&lt;span class=&quot;title&quot;&gt;SQL&lt;/span&gt;&lt;/figcaption&gt;&lt;pre data-language=&quot;sql&quot;&gt;&lt;code&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;UPDATE&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; resources&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;SET&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span class=&quot;indent&quot;&gt;    &lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;value&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; &lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;=&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; $&lt;/span&gt;&lt;span style=&quot;--0:#79C0FF&quot;&gt;1&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;,&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span class=&quot;indent&quot;&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;    &lt;/span&gt;&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;last_fencing_token &lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;=&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; $&lt;/span&gt;&lt;span style=&quot;--0:#79C0FF&quot;&gt;2&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;WHERE&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; id &lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;=&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; $&lt;/span&gt;&lt;span style=&quot;--0:#79C0FF&quot;&gt;3&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span class=&quot;indent&quot;&gt;  &lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;AND&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; last_fencing_token &lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;&amp;#x3C;&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; $&lt;/span&gt;&lt;span style=&quot;--0:#79C0FF&quot;&gt;2&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;;&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;/code&gt;&lt;/pre&gt;&lt;div class=&quot;copy&quot;&gt;&lt;div aria-live=&quot;polite&quot;&gt;&lt;/div&gt;&lt;button title=&quot;Copy to clipboard&quot; data-copied=&quot;Copied!&quot; data-code=&quot;UPDATE resourcesSET    value = $1,    last_fencing_token = $2WHERE id = $3  AND last_fencing_token &lt; $2;&quot;&gt;&lt;div&gt;&lt;/div&gt;&lt;/button&gt;&lt;/div&gt;&lt;/figure&gt;&lt;/div&gt;
&lt;p&gt;Here, the database itself checks if the incoming token is larger than the current token. If Worker A brings Token 103, but the database&apos;s current token is 104, the condition will not match and the update will fail. The database update must be designed so that even if a stale worker creates a bug at the application level, the database level still rejects it. You should always enforce correctness-critical validation at the authoritative resource.&lt;/p&gt;
&lt;figure&gt;&lt;img src=&quot;https://raw.githubusercontent.com/rafeuddaraj/rafes-blog-assets/refs/heads/distributed-locks-redlock-fencing-tokens-explained/assets/fencing-token-database.svg&quot; alt=&quot;Fencing Token Database&quot; loading=&quot;lazy&quot; decoding=&quot;async&quot; width=&quot;800&quot; height=&quot;400&quot;&gt;&lt;figcaption&gt;Fencing Token Database&lt;/figcaption&gt;&lt;/figure&gt;
&lt;h2 id=&quot;architectural-recap-and-production-checklist&quot;&gt;Architectural Recap and Production Checklist&lt;/h2&gt;
&lt;p&gt;Understanding the trade-off between safety and availability during a network partition or node failure is the job of an elite architect. A distributed lock is never just a &quot;lock acquired&quot; boolean; it also involves a failure model. For long-running operations, workers can extend the lease with a heartbeat. However, while lease renewal can reduce premature expirations, it cannot eliminate the stale worker problem. It is highly normal for failed requests to retry in distributed systems, so you have to design locks alongside fencing, idempotency, and atomic resource updates.&lt;/p&gt;
&lt;p&gt;Using Redis locks everywhere is not a good practice. Native database mechanisms like unique constraints, database transactions, &lt;code&gt;SELECT ... FOR UPDATE&lt;/code&gt;, advisory locks, or optimistic concurrency control can often provide better coordination. If your only goal is to reduce duplicate work, a simple Redis lock is enough. But if correctness is critical, fencing is absolutely necessary.&lt;/p&gt;
&lt;p&gt;You must review the following checklist before designing any distributed lock in production:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;Which exact resource are you protecting?&lt;/li&gt;
&lt;li&gt;What happens if the worker crashes or the lease expires while work is ongoing?&lt;/li&gt;
&lt;li&gt;Can a stale worker still execute and write data?&lt;/li&gt;
&lt;li&gt;Who is generating the fencing token, and is the resource validating it?&lt;/li&gt;
&lt;li&gt;How will the system behave during a network partition, Redis failover, process pause, or client retry?&lt;/li&gt;
&lt;li&gt;Can the operation be made idempotent, and can the database solve this problem on its own?&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;A lock dictates who can enter a critical section. A lease dictates how long that permission is valid. Redlock tries to establish a distributed lease using multiple nodes. Finally, a fencing token ensures that an old stale worker can never corrupt the resource under any circumstances. A lock does not stop a paused process, a TTL does not kill a stale worker, and a random lock ID does not establish ordering. Being able to identify and separate these layers in production distributed systems is the most important engineering skill.&lt;/p&gt;</content:encoded><category>System Design</category><category>Distributed Systems</category><category>Redis</category><category>Architecture</category><category>Node.js</category><category>Redlock</category><category>System Design</category></item><item><title>OOP vs Functional Programming Architectural Trade-offs</title><link>https://www.rafeuddaraj.me/blog/deep-dive-oop-vs-functional-programming-architecture/</link><guid isPermaLink="true">https://www.rafeuddaraj.me/blog/deep-dive-oop-vs-functional-programming-architecture/</guid><description>An in-depth, under-the-hood analysis of Object-Oriented Programming vs Functional Programming for resolving state management crises and making scalable architectural decisions.</description><pubDate>Fri, 31 Jul 2026 10:58:32 GMT</pubDate><content:encoded>&lt;p&gt;When working on scaled production systems, you might have noticed a common pattern. In large projects, nearly 80 percent of critical bugs come from internal state mutations and uncontrolled side effects within objects. Developers often mistake Object-Oriented Programming (OOP) and Functional Programming (FP) as just a cultural war or a syntax choice. The real difference is not in the syntax. The core difference lies in how these two paradigms handle memory, state variability, and control flow. Making the wrong state management choice can introduce concurrency race conditions, heavy garbage collection pressure, and scalability bottlenecks into your system. The main goal of this deep dive is to look past the dogma and break down the under-the-hood memory and architectural workflows. This will give you a clear guideline to make the right design decisions for your project.&lt;/p&gt;
&lt;h2 id=&quot;1-the-foundational-mental-model-and-analogy&quot;&gt;1. The Foundational Mental Model and Analogy&lt;/h2&gt;
&lt;p&gt;Before jumping into low-level architecture, we need to understand the high-level theory of state and transformation. You can think of the OOP mental model as an independent entity or a bank vault. The data is locked inside this vault, and you can only change the internal state through specific methods or interfaces. On the other hand, the FP mental model is like an assembly line or a water purifier. Data flows through this pipeline, and instead of modifying the existing data, each function generates and outputs data in a completely new format.&lt;/p&gt;
&lt;p&gt;To make this clearer, we can use a real-world analogy. For OOP, think of a smart car class. The car&apos;s gear, engine, and current speed are its internal private state. You can call an accelerate method, but you cannot go directly into memory and change the speed value yourself. The car manages its own state. For FP, imagine a digital passport validation pipeline. The original passport always remains exactly the same, completely immutable. The validation functions read the passport as an input and return a new validation report without modifying the original document. The data flows, but the original source of truth never mutates.&lt;/p&gt;
&lt;h2 id=&quot;2-under-the-hood-architecture-the-core-deep-dive&quot;&gt;2. Under-The-Hood Architecture (The Core Deep Dive)&lt;/h2&gt;
&lt;p&gt;Now let us break down how memory allocation and execution models work at the engine level. Under the hood, OOP relies on heap allocation, object reference graphs, and pointer traversal. When you create an object, the engine allocates a block of memory in the heap. Later, when you change its state, the engine uses the pointer to write directly in place within that memory. To boost performance, modern runtimes like the V8 engine use inline caches and Vtables to optimize these method calls.&lt;/p&gt;
&lt;p&gt;The under-the-hood mechanism of FP is entirely different. It relies heavily on immutable data structures and structural sharing. When you update a state, FP does not copy the entire memory block. Instead, it uses persistent data structures like Trie trees. The engine only allocates new memory for the specific nodes that changed, while the unchanged nodes share their previous references. Combined with pure functions and call stack frames, this creates an architecture where no function knows about the state outside of itself.&lt;/p&gt;
&lt;figure&gt;&lt;img src=&quot;https://raw.githubusercontent.com/rafeuddaraj/rafes-blog-assets/refs/heads/deep-dive-oop-vs-functional-programming-architecture/assets/oop-vs-fp-memory-workflow.svg&quot; alt=&quot;OOP vs FP Memory Workflow&quot; loading=&quot;lazy&quot; decoding=&quot;async&quot; width=&quot;1000&quot; height=&quot;500&quot;&gt;&lt;figcaption&gt;OOP vs FP Memory Workflow&lt;/figcaption&gt;&lt;/figure&gt;
&lt;p&gt;When it comes to concurrency and thread safety mechanics, this architectural difference has a massive impact. Because OOP relies on shared mutable state, race conditions occur when multiple threads try to write to the same memory reference at the same time. To prevent this, you have to use locks or mutexes, which severely increases latency. FP, however, uses stateless flow and immutable data to guarantee zero side effects. As a result, you can easily achieve lock-free thread safety and safe parallel execution.&lt;/p&gt;
&lt;figure&gt;&lt;img src=&quot;https://raw.githubusercontent.com/rafeuddaraj/rafes-blog-assets/refs/heads/deep-dive-oop-vs-functional-programming-architecture/assets/concurrency-race-condition-vs-pure-pipeline.svg&quot; alt=&quot;Concurrency Race Condition vs Pure Pipeline&quot; loading=&quot;lazy&quot; decoding=&quot;async&quot; width=&quot;1000&quot; height=&quot;500&quot;&gt;&lt;figcaption&gt;Concurrency Race Condition vs Pure Pipeline&lt;/figcaption&gt;&lt;/figure&gt;
&lt;h2 id=&quot;3-step-by-step-execution-trace-and-code-mechanics&quot;&gt;3. Step-by-Step Execution Trace and Code Mechanics&lt;/h2&gt;
&lt;p&gt;To understand how these architectural concepts work at the code level, we will analyze the execution trace of a user email update.&lt;/p&gt;
&lt;p&gt;First, consider Scenario A, the OOP state mutation execution trace. When you call &lt;code&gt;new User()&lt;/code&gt;, the engine allocates memory in the heap and creates an instance. Then, you invoke the &lt;code&gt;user.updateEmail(&quot;new@email.com&quot;)&lt;/code&gt; method. At this exact moment, an execution context is created in the call stack, and the engine resolves the actual field in heap memory using the &lt;code&gt;this&lt;/code&gt; pointer. The engine performs a direct in-place memory write, meaning the original data is mutated. If there is a database sync call inside this setter, it triggers a side effect. Later on, debugging or backtracking this side effect becomes incredibly difficult because the historical state no longer exists in memory.&lt;/p&gt;
&lt;p&gt;Now look at Scenario B, the FP immutable transformation execution trace. Here, the original &lt;code&gt;user&lt;/code&gt; object sits in memory completely frozen and immutable. When you call the pure function &lt;code&gt;updateEmail(user, &quot;new@email.com&quot;)&lt;/code&gt;, a completely isolated execution frame is created in the call stack. The engine uses structural sharing to create a new reference only for the email field that changed, reusing the rest of the fields from the old object. Finally, the function returns the new immutable object. Zero memory collisions happen here, and the return value of the function is always reproducible.&lt;/p&gt;
&lt;div class=&quot;callout&quot; role=&quot;note&quot; data-type=&quot;note&quot;&gt;
&lt;p class=&quot;callout-title&quot;&gt;Important&lt;/p&gt;
&lt;p&gt;The main strength of OOP is encapsulation. But when multiple services call methods on the same class and change its internal state, it turns into shared mutable state. This shared state is the leading cause of race conditions in distributed systems.&lt;/p&gt;
&lt;/div&gt;
&lt;div class=&quot;callout&quot; role=&quot;note&quot; data-type=&quot;warning&quot;&gt;
&lt;p class=&quot;callout-title&quot;&gt;Warning&lt;/p&gt;
&lt;p&gt;Immutability in FP makes your code extremely predictable. However, if you are not careful with excessive object allocations and copy-on-write patterns, you can introduce high garbage collection overhead and pause times in high-throughput systems. This will cause noticeable latency spikes.&lt;/p&gt;
&lt;/div&gt;
&lt;h2 id=&quot;4-edge-cases-pitfalls-and-trade-offs&quot;&gt;4. Edge Cases, Pitfalls, and Trade-offs&lt;/h2&gt;
&lt;p&gt;Every system architecture has a trade-off between performance and maintainability. In FP, constantly creating new objects increases the memory allocation rate, which puts heavy pressure on garbage collection. While persistent data structures and structural sharing reduce this overhead significantly, it can still be an issue for highly memory-sensitive or CPU-bound algorithms. In those specific cases, in-place mutation or an imperative approach performs much faster.&lt;/p&gt;
&lt;p&gt;On the flip side, the biggest trap in OOP is deep inheritance hell or tightly coupled object relationships. Joe Armstrong famously called this the banana-gorilla problem, where trying to extract a simple object forces you to pull in its entire environment. Contrast this with FP, where concepts like monads or currying are incredibly powerful, but their steep learning curve can make onboarding a new team very challenging. As an architect, you have to look at the size of your project, your team&apos;s capability, and your scalability requirements before making a decision.&lt;/p&gt;
&lt;div class=&quot;callout&quot; role=&quot;note&quot; data-type=&quot;tip&quot;&gt;
&lt;p class=&quot;callout-title&quot;&gt;Tip&lt;/p&gt;
&lt;p&gt;The architectural sweet spot: Use Domain-Driven Design (OOP) for module levels and service boundaries. This keeps your structure clean. Then, use pure functions (FP) for the internal business logic and data processing within those services.&lt;/p&gt;
&lt;/div&gt;
&lt;h2 id=&quot;5-practical-use-case-decision-matrix-and-summary&quot;&gt;5. Practical Use-Case Decision Matrix and Summary&lt;/h2&gt;
&lt;p&gt;In modern architecture, the days of blindly following a single paradigm are over. You need to take a hybrid approach based on your actual requirements. Here is a quick decision matrix to help you choose:&lt;/p&gt;
&lt;ol&gt;
&lt;li&gt;&lt;strong&gt;GUI, Game Engines, and Complex Domain Entities:&lt;/strong&gt; Use OOP here. It is the most natural fit to encapsulate the interactive object&apos;s state, lifecycle, and in-place memory update methods all together.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Data Pipelines, ETL, and Analytics Infrastructure:&lt;/strong&gt; Use FP here. In data stream transformations, pure functions and immutability completely remove side effects and make pipelining much easier.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;High-Concurrency and Distributed Microservices:&lt;/strong&gt; FP architecture performs best here as well. Without shared state, thread safety is guaranteed, and parallel processing is possible without deadlocks or race conditions.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Enterprise Business Applications (CRUD / Domain Boundary):&lt;/strong&gt; The hybrid pattern is the most effective approach here. You should use OOP modules for domain boundaries and dependency injection, and FP principles for internal business transformations.&lt;/li&gt;
&lt;/ol&gt;
&lt;p&gt;The multiparadigm approach is now the core foundation of modern engineering. Modern languages like TypeScript, Rust, and Kotlin beautifully merge the best concepts of both OOP and FP. So, when setting up your project architecture, use OOP at the macro level to define service interfaces, and use FP at the micro level for data transformation.&lt;/p&gt;
&lt;p&gt;Finally, as an engineer, ask yourself three questions whenever you make an architectural decision. First, are you building a system where the state of complex entities needs to be updated in-place frequently? Second, is high concurrency and multi-threaded processing a top priority in your application? Third, what is the learning curve and maintainability capacity of your team? Answering these questions will guide you directly to the right architectural paradigm.&lt;/p&gt;</content:encoded><category>Software Architecture</category><category>Deep Dive</category><category>Architecture</category><category>Under the hood</category><category>OOP</category><category>Functional Programming</category><category>System Design</category><category>Concurrency</category><category>V8 Engine</category></item><item><title>RFC 10008 and the HTTP QUERY Method: A Complete Engineering Handbook for Building Framework-Agnostic Search APIs</title><link>https://www.rafeuddaraj.me/blog/http-query-method-rfc-10008-complete-engineering-handbook/</link><guid isPermaLink="true">https://www.rafeuddaraj.me/blog/http-query-method-rfc-10008-complete-engineering-handbook/</guid><description>Explore how RFC 10008 solves the 16-year-old HTTP query limitation. This comprehensive handbook covers framework-agnostic implementation principles, a reference FastAPI backend, Uvicorn parser gotchas, client-side fetch quirks, caching realities, security concerns, and production adoption status.</description><pubDate>Fri, 24 Jul 2026 22:30:16 GMT</pubDate><content:encoded>&lt;h2 id=&quot;introduction-an-awkward-gap-left-open-for-16-years&quot;&gt;Introduction: An Awkward Gap Left Open for 16 Years&lt;/h2&gt;
&lt;p&gt;Welcome, everyone! Today, we are going to have an informal chat about a fascinating topic in backend engineering. Are you ready?&lt;/p&gt;
&lt;p&gt;Believe me, while working on backend systems, I have run into this frustration more times than I can count. There comes a day in every backend engineer&apos;s career when you have to build a complex, heavily customized search or filtering API. That is exactly when you collide with an old, awkward limitation in the HTTP protocol.&lt;/p&gt;
&lt;p&gt;As we all know, the GET method follows the rules strictly. It is safe and idempotent like a well-behaved student, and you can cache its responses easily. The real problem is that you are forced to cram every single piece of data into a tiny URL string. On the other hand, the POST method is a bit of a rebel that breaks the usual reading rules by allowing you to send as much data as you want inside the request body. However, according to standard HTTP semantics, POST is designed for changing server state, not for read-only search operations, right?&lt;/p&gt;
&lt;p&gt;This article is not just a dry theoretical lecture. It is a complete engineering handbook! We will break down every practical detail of RFC 10008, framework-agnostic implementation principles, a real-world reference implementation using Python and FastAPI, actual infrastructure limitations, security considerations, and the current adoption status across the tech ecosystem. No matter which programming language or framework you use daily, you will be able to implement this method in your own projects after reading this guide.&lt;/p&gt;
&lt;h3 id=&quot;where-exactly-do-get-and-post-fail-us&quot;&gt;Where Exactly Do GET and POST Fail Us?&lt;/h3&gt;
&lt;p&gt;Why do we actually need something new? Let us break down the reasoning. RFC 10008 outlines four concrete reasons why the GET method falls short for complex queries:&lt;/p&gt;
&lt;ol&gt;
&lt;li&gt;&lt;strong&gt;Uncertain URL Length Limits:&lt;/strong&gt; When a request travels to your server, it passes through multiple proxies, load balancers, and Content Delivery Networks along the way. Each of these intermediaries enforces its own arbitrary URL length limit. If you send a slightly larger filtering payload, one of those systems will drop your request halfway through.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Privacy Risks and Data Leaks:&lt;/strong&gt; URLs are routinely stored in plain text inside access logs, browser histories, and referrer headers. If your search filters contain sensitive customer data, that information is accidentally leaked to everywhere the URL is recorded. Does that make sense?&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Messy and Unreadable Query Strings:&lt;/strong&gt; We all know how terrible a nested filter object looks when you try to serialize it into a URL query string. Representing structures like price ranges, multiple categories, and sorting arrays in a URL makes the code almost impossible to read and maintain.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Infrastructure Confusion:&lt;/strong&gt; When you are forced to fall back on the POST method for searches, your load balancers and caching layers have no way to know whether the operation is a read or a write. As a result, critical infrastructure decisions regarding caching, automated retries, and rate limiting become completely flawed.&lt;/li&gt;
&lt;/ol&gt;
&lt;h2 id=&quot;a-bit-of-history-from-an-11-year-draft-to-an-official-rfc&quot;&gt;A Bit of History: From an 11-Year Draft to an Official RFC&lt;/h2&gt;
&lt;p&gt;Back in 2010, the PATCH method was introduced to the HTTP protocol, and 16 long years have passed since then. Can you believe it? After 16 years, this is the very first time a completely new general-purpose method has been added to HTTP!&lt;/p&gt;
&lt;p&gt;The initial draft for the QUERY method (&lt;code&gt;draft-ietf-httpbis-safe-method-w-body&lt;/code&gt;) was iterated on for years inside the HTTP Working Group. It was finally approved by the IESG on November 20, 2025, and &lt;strong&gt;on June 15, 2026, the RFC Editor officially published it as RFC 10008&lt;/strong&gt;. This document is a 24-page Proposed Standard written by &lt;a href=&quot;https://datatracker.ietf.org/person/julian.reschke@gmx.de&quot; rel=&quot;noopener noreferrer&quot;&gt;Julian Reschke (greenbytes)&lt;/a&gt;, &lt;a href=&quot;https://blog.cloudflare.com/author/jasnell/&quot; rel=&quot;noopener noreferrer&quot;&gt;James M. Snell (Cloudflare)&lt;/a&gt;, and &lt;a href=&quot;https://datatracker.ietf.org/person/mbishop@evequefou.be&quot; rel=&quot;noopener noreferrer&quot;&gt;Mike Bishop (Akamai)&lt;/a&gt;. It was truly a 16-year wait worth celebrating!&lt;/p&gt;
&lt;h2 id=&quot;exploring-the-core-of-rfc-10008&quot;&gt;Exploring the Core of RFC 10008&lt;/h2&gt;
&lt;p&gt;Let us look at the technical details. What exactly is the specification telling us to do?&lt;/p&gt;
&lt;h3 id=&quot;definition-and-iana-registration&quot;&gt;Definition and IANA Registration&lt;/h3&gt;
&lt;p&gt;According to the RFC, a QUERY request instructs a resource to process the attached content in a safe and idempotent manner, and then return the resulting output as a response. In the IANA HTTP Method Registry, it is officially recorded like this:&lt;/p&gt;
&lt;section class=&quot;table-wrap&quot; tabindex=&quot;0&quot; aria-label=&quot;Table 1&quot;&gt;
















&lt;table&gt;&lt;thead&gt;&lt;tr&gt;&lt;th&gt;Method Name&lt;/th&gt;&lt;th&gt;Safe&lt;/th&gt;&lt;th&gt;Idempotent&lt;/th&gt;&lt;th&gt;Specification&lt;/th&gt;&lt;/tr&gt;&lt;/thead&gt;&lt;tbody&gt;&lt;tr&gt;&lt;td&gt;QUERY&lt;/td&gt;&lt;td&gt;Yes&lt;/td&gt;&lt;td&gt;Yes&lt;/td&gt;&lt;td&gt;Section 2, RFC 10008&lt;/td&gt;&lt;/tr&gt;&lt;/tbody&gt;&lt;/table&gt;&lt;/section&gt;
&lt;p&gt;What do safe and idempotent actually mean? Think of an idempotent operation like a gentle, well-behaved child in a house. No matter how many times you ask them to perform the same task, they will never break any furniture or disrupt the room, which means the server state remains completely unchanged. Your networking infrastructure now knows for certain that this request will cause no harm. If a network connection drops halfway through, you do not need to worry because the request can be safely retried automatically, exactly like a GET request!&lt;/p&gt;
&lt;h3 id=&quot;a-request-body-does-not-mean-json-content-type-is-king&quot;&gt;A Request Body Does Not Mean JSON: Content-Type is King&lt;/h3&gt;
&lt;p&gt;This is exactly where most developers make a common mistake. Everyone assumes that having a request body means you must send JSON. That is simply not true! Understanding this concept is crucial if you want to build framework-agnostic systems.&lt;/p&gt;
&lt;p&gt;The RFC does not enforce any strict format for the body of a QUERY request. The payload body and the &lt;code&gt;Content-Type&lt;/code&gt; header work together to define the exact query structure. This means you can send JSON, &lt;code&gt;application/x-www-form-urlencoded&lt;/code&gt;, standard GraphQL syntax, or even a custom SQL-like domain-specific language that you designed yourself! The only requirement is that both the client and the server must understand and agree on that specific &lt;code&gt;Content-Type&lt;/code&gt;. Take a look at this excellent example provided directly in the RFC:&lt;/p&gt;
&lt;div class=&quot;expressive-code&quot;&gt;&lt;style&gt;.expressive-code{font-family:var(--ec-uiFontFml);font-size:var(--ec-uiFontSize);font-weight:var(--ec-uiFontWg);line-height:var(--ec-uiLineHt);text-size-adjust:none;-webkit-text-size-adjust:none}.expressive-code *:not(:is(svg, svg *)){all:revert;box-sizing:border-box}.expressive-code pre{display:flex;margin:0;padding:0;border:var(--ec-brdWd) solid var(--ec-brdCol);border-radius:calc(var(--ec-brdRad) + var(--ec-brdWd));background:var(--ec-codeBg)}.expressive-code pre:focus-visible{outline:3px solid var(--ec-focusBrd);outline-offset:-3px}.expressive-code pre &gt; code{all:unset;display:block;flex:1 0 100%;padding:var(--ec-codePadBlk) 0;color:var(--ec-codeFg);font-family:var(--ec-codeFontFml);font-size:var(--ec-codeFontSize);font-weight:var(--ec-codeFontWg);line-height:var(--ec-codeLineHt)}.expressive-code pre{overflow-x:auto}.expressive-code pre.wrap .ec-line .code{white-space:pre-wrap;overflow-wrap:break-word;min-width:min(20ch, var(--ecMaxLine, 20ch))}.expressive-code pre.wrap .ec-line .code span.indent{white-space:pre}.expressive-code pre::-webkit-scrollbar,.expressive-code pre::-webkit-scrollbar-track{background-color:inherit;border-radius:calc(var(--ec-brdRad) + var(--ec-brdWd));border-top-left-radius:0;border-top-right-radius:0}.expressive-code pre::-webkit-scrollbar-thumb{background-color:var(--ec-sbThumbCol);border:4px solid transparent;background-clip:content-box;border-radius:10px}.expressive-code pre::-webkit-scrollbar-thumb:hover{background-color:var(--ec-sbThumbHoverCol)}.expressive-code pre::-webkit-scrollbar-corner{background:transparent}.expressive-code .ec-line{direction:ltr;unicode-bidi:isolate;display:grid;grid-template-areas:&apos;gutter code&apos;;grid-template-columns:auto 1fr;position:relative}.expressive-code .ec-line .gutter{grid-area:gutter;color:var(--ec-gtrFg)}.expressive-code .ec-line .gutter &gt; *{pointer-events:none;user-select:none;-webkit-user-select:none}.expressive-code .ec-line .gutter ~ .code{--ecLineBrdCol:var(--ec-gtrBrdCol)}.expressive-code .ec-line.highlight .gutter{color:var(--ec-gtrHlFg)}.expressive-code .ec-line .code{grid-area:code;position:relative;box-sizing:content-box;padding-inline-start:calc(var(--ecIndent, 0ch) + var(--ec-codePadInl) - var(--ecGtrBrdWd));padding-inline-end:var(--ec-codePadInl);text-indent:calc(var(--ecIndent, 0ch) * -1)}.expressive-code .ec-line .code::before,.expressive-code .ec-line .code::after,.expressive-code .ec-line .code :where(*){text-indent:0}.expressive-code .ec-line .code{--ecGtrBrdWd:var(--ec-gtrBrdWd);border-inline-start:var(--ecGtrBrdWd) solid var(--ecLineBrdCol, transparent)}.expressive-code .sr-only{position:absolute;width:1px;height:1px;padding:0;margin:-1px;overflow:hidden;clip:rect(0, 0, 0, 0);white-space:nowrap;border-width:0}.expressive-code .ec-line.mark{--tmLineBgCol:var(--ec-tm-markBg)}.expressive-code .ec-line.mark .code{--ecLineBrdCol:var(--ec-tm-markBrdCol)}.expressive-code .ec-line.ins{--tmLineBgCol:var(--ec-tm-insBg);--tmLabel:var(--ec-tm-insDiffIndContent)}.expressive-code .ec-line.ins .code{--ecLineBrdCol:var(--ec-tm-insBrdCol)}.expressive-code .ec-line.ins .code::before{color:var(--ec-tm-insDiffIndCol)}.expressive-code .ec-line.del{--tmLineBgCol:var(--ec-tm-delBg);--tmLabel:var(--ec-tm-delDiffIndContent)}.expressive-code .ec-line.del .code{--ecLineBrdCol:var(--ec-tm-delBrdCol)}.expressive-code .ec-line.del .code::before{color:var(--ec-tm-delDiffIndCol)}.expressive-code .ec-line.mark,.expressive-code .ec-line.ins,.expressive-code .ec-line.del{background:var(--tmLineBgCol)}.expressive-code .ec-line.mark .code,.expressive-code .ec-line.ins .code,.expressive-code .ec-line.del .code{--ecGtrBrdWd:var(--ec-tm-lineMarkerAccentWd)}.expressive-code .ec-line.mark .code::before,.expressive-code .ec-line.ins .code::before,.expressive-code .ec-line.del .code::before{display:block;position:absolute;left:0;box-sizing:border-box;content:var(--tmLabel, &apos; &apos;);padding-inline-start:var(--ec-tm-lineDiffIndMargLeft);text-align:center;white-space:pre}.expressive-code .ec-line.mark.tm-label .code::before,.expressive-code .ec-line.ins.tm-label .code::before,.expressive-code .ec-line.del.tm-label .code::before{background:var(--ecLineBrdCol);padding:0 calc(var(--ec-tm-lineMarkerLabelPadInl) + var(--ec-tm-lineMarkerAccentWd)) 0 var(--ec-tm-lineMarkerLabelPadInl);color:var(--ec-tm-lineMarkerLabelCol)}.expressive-code .ec-line mark{--tmInlineBgCol:var(--ec-tm-markBg);--tmInlineBrdCol:var(--ec-tm-markBrdCol)}.expressive-code .ec-line ins{--tmInlineBgCol:var(--ec-tm-insBg);--tmInlineBrdCol:var(--ec-tm-insBrdCol)}.expressive-code .ec-line del{--tmInlineBgCol:var(--ec-tm-delBg);--tmInlineBrdCol:var(--ec-tm-delBrdCol)}.expressive-code .ec-line mark,.expressive-code .ec-line ins,.expressive-code .ec-line del{all:unset;display:inline-block;position:relative;--tmBrdL:var(--ec-tm-inlMarkerBrdWd);--tmBrdR:var(--ec-tm-inlMarkerBrdWd);--tmRadL:var(--ec-tm-inlMarkerBrdRad);--tmRadR:var(--ec-tm-inlMarkerBrdRad);margin-inline:0.025rem;padding-inline:var(--ec-tm-inlMarkerPad);border-radius:var(--tmRadL) var(--tmRadR) var(--tmRadR) var(--tmRadL);background:var(--tmInlineBgCol);background-clip:padding-box}.expressive-code .ec-line mark.open-start,.expressive-code .ec-line ins.open-start,.expressive-code .ec-line del.open-start{margin-inline-start:0;padding-inline-start:0;--tmBrdL:0px;--tmRadL:0}.expressive-code .ec-line mark.open-end,.expressive-code .ec-line ins.open-end,.expressive-code .ec-line del.open-end{margin-inline-end:0;padding-inline-end:0;--tmBrdR:0px;--tmRadR:0}.expressive-code .ec-line mark::before,.expressive-code .ec-line ins::before,.expressive-code .ec-line del::before{content:&apos;&apos;;position:absolute;pointer-events:none;display:inline-block;inset:0;border-radius:var(--tmRadL) var(--tmRadR) var(--tmRadR) var(--tmRadL);border:var(--ec-tm-inlMarkerBrdWd) solid var(--tmInlineBrdCol);border-inline-width:var(--tmBrdL) var(--tmBrdR)}.expressive-code .frame{all:unset;position:relative;display:block;--header-border-radius:calc(var(--ec-brdRad) + var(--ec-brdWd));--tab-border-radius:calc(var(--ec-frm-edTabBrdRad) + var(--ec-brdWd));--button-spacing:0.4rem;--code-background:var(--ec-frm-edBg);border-radius:var(--header-border-radius);box-shadow:var(--ec-frm-frameBoxShdCssVal)}.expressive-code .frame .header{display:none;z-index:1;position:relative;border-radius:var(--header-border-radius) var(--header-border-radius) 0 0}.expressive-code .frame.has-title pre,.expressive-code .frame.has-title code,.expressive-code .frame.is-terminal pre,.expressive-code .frame.is-terminal code{border-top:none;border-top-left-radius:0;border-top-right-radius:0}.expressive-code .frame .title:empty:before{content:&apos;\a0&apos;}.expressive-code .frame.has-title:not(.is-terminal){--button-spacing:calc(1.9rem + 2 * (var(--ec-uiPadBlk) + var(--ec-frm-edActTabIndHt)))}.expressive-code .frame.has-title:not(.is-terminal) .title{position:relative;color:var(--ec-frm-edActTabFg);background:var(--ec-frm-edActTabBg);background-clip:padding-box;margin-block-start:var(--ec-frm-edTabsMargBlkStart);padding:calc(var(--ec-uiPadBlk) + var(--ec-frm-edActTabIndHt)) var(--ec-uiPadInl);border:var(--ec-brdWd) solid var(--ec-frm-edActTabBrdCol);border-radius:var(--tab-border-radius) var(--tab-border-radius) 0 0;border-bottom:none;overflow:hidden}.expressive-code .frame.has-title:not(.is-terminal) .title::after{content:&apos;&apos;;position:absolute;pointer-events:none;inset:0;border-top:var(--ec-frm-edActTabIndHt) solid var(--ec-frm-edActTabIndTopCol);border-bottom:var(--ec-frm-edActTabIndHt) solid var(--ec-frm-edActTabIndBtmCol)}.expressive-code .frame.has-title:not(.is-terminal) .header{display:flex;background:linear-gradient(to top, var(--ec-frm-edTabBarBrdBtmCol) var(--ec-brdWd), transparent var(--ec-brdWd)),linear-gradient(var(--ec-frm-edTabBarBg), var(--ec-frm-edTabBarBg));background-repeat:no-repeat;padding-inline-start:var(--ec-frm-edTabsMargInlStart)}.expressive-code .frame.has-title:not(.is-terminal) .header::before{content:&apos;&apos;;position:absolute;pointer-events:none;inset:0;border:var(--ec-brdWd) solid var(--ec-frm-edTabBarBrdCol);border-radius:inherit;border-bottom:none}.expressive-code .frame.is-terminal{--button-spacing:calc(1.9rem + var(--ec-brdWd) + 2 * var(--ec-uiPadBlk));--code-background:var(--ec-frm-trmBg)}.expressive-code .frame.is-terminal .header{display:flex;align-items:center;justify-content:center;padding-block:var(--ec-uiPadBlk);padding-block-end:calc(var(--ec-uiPadBlk) + var(--ec-brdWd));position:relative;font-weight:500;letter-spacing:0.025ch;color:var(--ec-frm-trmTtbFg);background:var(--ec-frm-trmTtbBg);border:var(--ec-brdWd) solid var(--ec-brdCol);border-bottom:none}.expressive-code .frame.is-terminal .header::before{content:&apos;&apos;;position:absolute;pointer-events:none;left:var(--ec-uiPadInl);width:2.1rem;height:0.56rem;line-height:0;background-color:var(--ec-frm-trmTtbDotsFg);opacity:var(--ec-frm-trmTtbDotsOpa);-webkit-mask-image:var(--ec-frm-trmIcon);-webkit-mask-repeat:no-repeat;mask-image:var(--ec-frm-trmIcon);mask-repeat:no-repeat}.expressive-code .frame.is-terminal .header::after{content:&apos;&apos;;position:absolute;pointer-events:none;inset:0;border-bottom:var(--ec-brdWd) solid var(--ec-frm-trmTtbBrdBtmCol)}.expressive-code .frame pre{background:var(--code-background)}.expressive-code .copy{display:flex;gap:0.25rem;flex-direction:row;position:absolute;inset-block-start:calc(var(--ec-brdWd) + var(--button-spacing));inset-inline-end:calc(var(--ec-brdWd) + var(--ec-uiPadInl) / 2)}@media (scripting: none){.expressive-code .copy{display:none}}.expressive-code .copy{direction:ltr;unicode-bidi:isolate}.expressive-code .copy button{position:relative;align-self:flex-end;margin:0;padding:0;border:none;border-radius:0.2rem;z-index:1;cursor:pointer;transition-property:opacity, background, border-color;transition-duration:0.2s;transition-timing-function:cubic-bezier(0.25, 0.46, 0.45, 0.94);width:2.5rem;height:2.5rem;background:var(--code-background);opacity:0.75}.expressive-code .copy button div{position:absolute;inset:0;border-radius:inherit;background:var(--ec-frm-inlBtnBg);opacity:var(--ec-frm-inlBtnBgIdleOpa);transition-property:inherit;transition-duration:inherit;transition-timing-function:inherit}.expressive-code .copy button::before{content:&apos;&apos;;position:absolute;pointer-events:none;inset:0;border-radius:inherit;border:var(--ec-brdWd) solid var(--ec-frm-inlBtnBrd);opacity:var(--ec-frm-inlBtnBrdOpa)}.expressive-code .copy button::after{content:&apos;&apos;;position:absolute;pointer-events:none;inset:0;background-color:var(--ec-frm-inlBtnFg);-webkit-mask-image:var(--ec-frm-copyIcon);-webkit-mask-repeat:no-repeat;mask-image:var(--ec-frm-copyIcon);mask-repeat:no-repeat;margin:0.475rem;line-height:0}.expressive-code .copy button:hover,.expressive-code .copy button:focus:focus-visible{opacity:1}.expressive-code .copy button:hover div,.expressive-code .copy button:focus:focus-visible div{opacity:var(--ec-frm-inlBtnBgHoverOrFocusOpa)}.expressive-code .copy button:active{opacity:1}.expressive-code .copy button:active div{opacity:var(--ec-frm-inlBtnBgActOpa)}.expressive-code .copy .feedback{--tooltip-arrow-size:0.35rem;--tooltip-bg:var(--ec-frm-tooltipSuccessBg);color:var(--ec-frm-tooltipSuccessFg);pointer-events:none;user-select:none;-webkit-user-select:none;position:relative;align-self:center;background-color:var(--tooltip-bg);z-index:99;padding:0.125rem 0.75rem;border-radius:0.2rem;margin-inline-end:var(--tooltip-arrow-size);opacity:0;transition-property:opacity, transform;transition-duration:0.2s;transition-timing-function:ease-in-out;transform:translate3d(0, 0.25rem, 0)}.expressive-code .copy .feedback::after{content:&apos;&apos;;position:absolute;pointer-events:none;top:calc(50% - var(--tooltip-arrow-size));inset-inline-end:calc(-2 * (var(--tooltip-arrow-size) - 0.5px));border:var(--tooltip-arrow-size) solid transparent;border-inline-start-color:var(--tooltip-bg)}.expressive-code .copy .feedback.show{opacity:1;transform:translate3d(0, 0, 0)}@media (hover: hover){.expressive-code{}.expressive-code .copy button{opacity:0;width:2rem;height:2rem}.expressive-code .frame:hover .copy button:not(:hover),.expressive-code .frame:focus-within :focus-visible ~ .copy button:not(:hover),.expressive-code .frame .copy .feedback.show ~ button:not(:hover){opacity:0.75}}.expressive-code :nth-child(1 of .ec-line) .code{padding-inline-end:calc(2rem + var(--ec-codePadInl))}:root{--ec-brdRad:0.75rem;--ec-brdWd:1.5px;--ec-brdCol:var(--code-line);--ec-codeFontFml:var(--font-code);--ec-codeFontSize:0.875rem;--ec-codeFontWg:400;--ec-codeLineHt:1.75;--ec-codePadBlk:1rem;--ec-codePadInl:1.125rem;--ec-codeBg:var(--code-bg);--ec-codeFg:#e6edf3;--ec-codeSelBg:#264f78;--ec-gtrFg:#6e7681;--ec-gtrBrdCol:#6e768133;--ec-gtrBrdWd:1.5px;--ec-gtrHlFg:#e6edf3;--ec-uiFontFml:var(--font-mono);--ec-uiFontSize:0.75rem;--ec-uiFontWg:400;--ec-uiLineHt:1.65;--ec-uiPadBlk:0.25rem;--ec-uiPadInl:1rem;--ec-uiSelBg:#6e768166;--ec-uiSelFg:#e6edf3;--ec-focusBrd:#1f6feb;--ec-sbThumbCol:#8b949e33;--ec-sbThumbHoverCol:#8b949e3d;--ec-tm-lineMarkerAccentMarg:0rem;--ec-tm-lineMarkerAccentWd:0.15rem;--ec-tm-lineMarkerLabelPadInl:0.2rem;--ec-tm-lineMarkerLabelCol:white;--ec-tm-lineDiffIndMargLeft:0.3rem;--ec-tm-inlMarkerBrdWd:1.5px;--ec-tm-inlMarkerBrdRad:0.2rem;--ec-tm-inlMarkerPad:0.15rem;--ec-tm-insDiffIndContent:&apos;+&apos;;--ec-tm-delDiffIndContent:&apos;-&apos;;--ec-tm-markBg:#264a8980;--ec-tm-markBrdCol:#5570b3d0;--ec-tm-insBg:#26561c80;--ec-tm-insBrdCol:#4e7e41d0;--ec-tm-insDiffIndCol:#7eb070d0;--ec-tm-delBg:#81322b80;--ec-tm-delBrdCol:#ae594fd0;--ec-tm-delDiffIndCol:#e68a7ed0;--ec-frm-shdCol:#0000005b;--ec-frm-frameBoxShdCssVal:none;--ec-frm-edActTabBg:var(--code-bg);--ec-frm-edActTabFg:var(--code-muted);--ec-frm-edActTabBrdCol:transparent;--ec-frm-edActTabIndHt:1.5px;--ec-frm-edActTabIndTopCol:transparent;--ec-frm-edActTabIndBtmCol:#0d1117;--ec-frm-edTabsMargInlStart:0;--ec-frm-edTabsMargBlkStart:0;--ec-frm-edTabBrdRad:0.75rem;--ec-frm-edTabBarBg:var(--code-bg);--ec-frm-edTabBarBrdCol:var(--code-line);--ec-frm-edTabBarBrdBtmCol:var(--code-line);--ec-frm-edBg:var(--code-bg);--ec-frm-trmTtbFg:var(--code-muted);--ec-frm-trmTtbDotsFg:var(--code-muted);--ec-frm-trmTtbDotsOpa:0.15;--ec-frm-trmTtbBg:var(--code-bg);--ec-frm-trmTtbBrdBtmCol:var(--code-line);--ec-frm-trmBg:var(--code-bg);--ec-frm-inlBtnBg:var(--code-ink);--ec-frm-inlBtnBgIdleOpa:0;--ec-frm-inlBtnBgHoverOrFocusOpa:0.2;--ec-frm-inlBtnBgActOpa:0.3;--ec-frm-inlBtnFg:var(--code-ink);--ec-frm-inlBtnBrd:var(--code-line);--ec-frm-inlBtnBrdOpa:0.4;--ec-frm-tooltipSuccessBg:var(--color-emerald);--ec-frm-tooltipSuccessFg:var(--color-bg);--ec-frm-copyIcon:url(&quot;data:image/svg+xml,%3Csvg%20xmlns%3D&apos;http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg&apos;%20viewBox%3D&apos;0%200%2024%2024&apos;%20fill%3D&apos;none&apos;%20stroke%3D&apos;black&apos;%20stroke-width%3D&apos;1.75&apos;%3E%3Cpath%20d%3D&apos;M3%2019a2%202%200%200%201-1-2V2a2%202%200%200%201%201-1h13a2%202%200%200%201%202%201&apos;%2F%3E%3Crect%20x%3D&apos;6&apos;%20y%3D&apos;5&apos;%20width%3D&apos;16&apos;%20height%3D&apos;18&apos;%20rx%3D&apos;1.5&apos;%20ry%3D&apos;1.5&apos;%2F%3E%3C%2Fsvg%3E&quot;);--ec-frm-trmIcon:url(&quot;data:image/svg+xml,%3Csvg%20xmlns%3D&apos;http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg&apos;%20viewBox%3D&apos;0%200%2060%2016&apos;%20preserveAspectRatio%3D&apos;xMidYMid%20meet&apos;%3E%3Ccircle%20cx%3D&apos;8&apos;%20cy%3D&apos;8&apos;%20r%3D&apos;8&apos;%2F%3E%3Ccircle%20cx%3D&apos;30&apos;%20cy%3D&apos;8&apos;%20r%3D&apos;8&apos;%2F%3E%3Ccircle%20cx%3D&apos;52&apos;%20cy%3D&apos;8&apos;%20r%3D&apos;8&apos;%2F%3E%3C%2Fsvg%3E&quot;)}.expressive-code .ec-line :where(span[style^=&apos;--&apos;]:not([class])){color:var(--0, inherit);background-color:var(--0bg, transparent);font-style:var(--0fs, inherit);font-weight:var(--0fw, inherit);text-decoration:var(--0td, inherit)}&lt;/style&gt;&lt;script type=&quot;module&quot; src=&quot;/_astro/ec.0vx5m.js&quot;&gt;&lt;/script&gt;&lt;figure class=&quot;frame has-title&quot;&gt;&lt;figcaption class=&quot;header&quot;&gt;&lt;span class=&quot;title&quot;&gt;HTTP&lt;/span&gt;&lt;/figcaption&gt;&lt;pre data-language=&quot;http&quot;&gt;&lt;code&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;QUERY /contacts HTTP/1.1&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span style=&quot;--0:#7EE787&quot;&gt;Host&lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;:&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; &lt;/span&gt;&lt;span style=&quot;--0:#A5D6FF&quot;&gt;example.org&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span style=&quot;--0:#7EE787&quot;&gt;Content-Type&lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;:&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; &lt;/span&gt;&lt;span style=&quot;--0:#A5D6FF&quot;&gt;application/x-www-form-urlencoded&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span style=&quot;--0:#7EE787&quot;&gt;Accept&lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;:&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; &lt;/span&gt;&lt;span style=&quot;--0:#A5D6FF&quot;&gt;application/json&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;
&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;select=surname,givenname,email&amp;#x26;limit=10&amp;#x26;match=email=*@example.*&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;/code&gt;&lt;/pre&gt;&lt;div class=&quot;copy&quot;&gt;&lt;div aria-live=&quot;polite&quot;&gt;&lt;/div&gt;&lt;button title=&quot;Copy to clipboard&quot; data-copied=&quot;Copied!&quot; data-code=&quot;QUERY /contacts HTTP/1.1Host: example.orgContent-Type: application/x-www-form-urlencodedAccept: application/jsonselect=surname,givenname,email&amp;#x26;limit=10&amp;#x26;match=email=*@example.*&quot;&gt;&lt;div&gt;&lt;/div&gt;&lt;/button&gt;&lt;/div&gt;&lt;/figure&gt;&lt;/div&gt;
&lt;div class=&quot;callout&quot; role=&quot;note&quot; data-type=&quot;note&quot;&gt;
&lt;p class=&quot;callout-title&quot;&gt;Content-Type Validation is Mandatory&lt;/p&gt;
&lt;p&gt;According to the RFC, a server must reject any request that has a missing or inconsistent &lt;code&gt;Content-Type&lt;/code&gt; header. When a mismatch occurs, the server must return an appropriate HTTP error status such as &lt;code&gt;400 Bad Request&lt;/code&gt;, &lt;code&gt;415 Unsupported Media Type&lt;/code&gt;, or &lt;code&gt;422 Unprocessable Entity&lt;/code&gt;. This is not just an optional best practice; it is a strict MUST requirement defined in the specification!&lt;/p&gt;
&lt;/div&gt;
&lt;h3 id=&quot;enabling-discoverability-with-the-accept-query-header&quot;&gt;Enabling Discoverability with the Accept-Query Header&lt;/h3&gt;
&lt;p&gt;Now, you might wonder how a client actually discovers whether a resource supports the QUERY method and which Content-Type formats it accepts. To solve this discoverability challenge, the RFC defines a brand new header field called &lt;code&gt;Accept-Query&lt;/code&gt;. This header has officially been added to the IANA HTTP Field Name Registry. Servers typically send this header inside the response to an &lt;code&gt;OPTIONS&lt;/code&gt; request:&lt;/p&gt;
&lt;div class=&quot;expressive-code&quot;&gt;&lt;figure class=&quot;frame has-title&quot;&gt;&lt;figcaption class=&quot;header&quot;&gt;&lt;span class=&quot;title&quot;&gt;HTTP&lt;/span&gt;&lt;/figcaption&gt;&lt;pre data-language=&quot;http&quot;&gt;&lt;code&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;OPTIONS&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; /products &lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;HTTP&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;/&lt;/span&gt;&lt;span style=&quot;--0:#79C0FF&quot;&gt;1.1&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span style=&quot;--0:#7EE787&quot;&gt;Host&lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;:&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; &lt;/span&gt;&lt;span style=&quot;--0:#A5D6FF&quot;&gt;api.example.com&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;
&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;HTTP&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;/&lt;/span&gt;&lt;span style=&quot;--0:#79C0FF&quot;&gt;1.1&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; &lt;/span&gt;&lt;span style=&quot;--0:#79C0FF&quot;&gt;204&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; &lt;/span&gt;&lt;span style=&quot;--0:#A5D6FF&quot;&gt;No Content&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span style=&quot;--0:#7EE787&quot;&gt;Allow&lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;:&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; &lt;/span&gt;&lt;span style=&quot;--0:#A5D6FF&quot;&gt;GET, QUERY, OPTIONS&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span style=&quot;--0:#7EE787&quot;&gt;Accept-Query&lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;:&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; &lt;/span&gt;&lt;span style=&quot;--0:#A5D6FF&quot;&gt;application/json&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;/code&gt;&lt;/pre&gt;&lt;div class=&quot;copy&quot;&gt;&lt;div aria-live=&quot;polite&quot;&gt;&lt;/div&gt;&lt;button title=&quot;Copy to clipboard&quot; data-copied=&quot;Copied!&quot; data-code=&quot;OPTIONS /products HTTP/1.1Host: api.example.comHTTP/1.1 204 No ContentAllow: GET, QUERY, OPTIONSAccept-Query: application/json&quot;&gt;&lt;div&gt;&lt;/div&gt;&lt;/button&gt;&lt;/div&gt;&lt;/figure&gt;&lt;/div&gt;
&lt;h3 id=&quot;what-the-rfc-says-about-cors&quot;&gt;What the RFC Says About CORS&lt;/h3&gt;
&lt;p&gt;We all know how frustrating Cross-Origin Resource Sharing can be when connecting a frontend application to a backend server. The RFC explicitly states that the QUERY method is not included in the list of CORS-safelisted methods. That exclusive list only contains GET, HEAD, and POST methods. Therefore, sending a cross-origin QUERY request from a web browser will always trigger a mandatory preflight &lt;code&gt;OPTIONS&lt;/code&gt; request before sending the actual data. You must keep this behavior in mind when designing your API!&lt;/p&gt;
&lt;h2 id=&quot;framework-agnostic-implementation-principles-universal-rules-for-any-stack&quot;&gt;Framework-Agnostic Implementation Principles: Universal Rules for Any Stack&lt;/h2&gt;
&lt;p&gt;Truth be told, whether you build your backend with Python, Node.js, Go, Java, or Ruby, the following six foundational rules apply equally across every technology stack. Let us quickly go through them:&lt;/p&gt;
&lt;ol&gt;
&lt;li&gt;&lt;strong&gt;Accept the Raw QUERY Method at the HTTP Server Layer:&lt;/strong&gt; The low-level HTTP parser running beneath your application (such as Uvicorn, Hypercorn, the Node.js HTTP module, or Tomcat/Jetty) must recognize QUERY as a valid HTTP method. Even if your web framework supports it, an underlying transport layer that does not recognize the method will silently block or reject the request.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Parse the Body According to Content-Type:&lt;/strong&gt; Reuse your existing body-parsing logic from your POST handlers, but always validate the &lt;code&gt;Content-Type&lt;/code&gt; header to prevent format mismatches.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Keep Your Handlers Strictly Read-Only:&lt;/strong&gt; Never include any database write operations or side effects inside a QUERY handler. Because network infrastructure treats this method as safe, it may automatically retry failed requests, which could cause duplicate database entries if side effects exist.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Provide Discoverability via Accept-Query and Allow Headers:&lt;/strong&gt; Always clearly advertise in your &lt;code&gt;OPTIONS&lt;/code&gt; responses that your endpoint supports the QUERY method.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Explicitly Add QUERY to Your CORS Middleware:&lt;/strong&gt; Default CORS configurations will never allow custom HTTP methods automatically, so you must add it explicitly.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Test Using Method-Aware Tooling:&lt;/strong&gt; Tools like &lt;code&gt;curl -X QUERY&lt;/code&gt;, &lt;code&gt;httpx&lt;/code&gt;, and &lt;code&gt;k6&lt;/code&gt; natively support custom HTTP methods. However, testing tools like JMeter require additional manual property configurations to work properly.&lt;/li&gt;
&lt;/ol&gt;
&lt;h2 id=&quot;reference-implementation-building-with-python-and-fastapi&quot;&gt;Reference Implementation: Building with Python and FastAPI&lt;/h2&gt;
&lt;p&gt;Now that we have covered the architectural principles, let us write some actual code. I chose FastAPI for this example because it is currently the most popular asynchronous framework in the Python ecosystem. However, if you keep the six core principles in mind, you can easily build this same structure using Express, Spring, Django, or Go.&lt;/p&gt;
&lt;div class=&quot;expressive-code&quot;&gt;&lt;figure class=&quot;frame has-title&quot;&gt;&lt;figcaption class=&quot;header&quot;&gt;&lt;span class=&quot;title&quot;&gt;Python&lt;/span&gt;&lt;/figcaption&gt;&lt;pre data-language=&quot;python&quot;&gt;&lt;code&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span style=&quot;--0:#8B949E&quot;&gt;# main.py&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;from&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; fastapi &lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;import&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; FastAPI, Request, HTTPException&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;from&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; fastapi.middleware.cors &lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;import&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; CORSMiddleware&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;from&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; pydantic &lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;import&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; BaseModel, Field&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;from&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; typing &lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;import&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; Optional, Literal&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;
&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;app &lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;=&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; FastAPI(&lt;/span&gt;&lt;span style=&quot;--0:#FFA657&quot;&gt;title&lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;=&lt;/span&gt;&lt;span style=&quot;--0:#A5D6FF&quot;&gt;&quot;Product Search API&quot;&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;)&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;
&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span style=&quot;--0:#8B949E&quot;&gt;# Principle 5: Explicitly add QUERY to the CORS middleware&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;app.add_middleware(&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span class=&quot;indent&quot;&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;    &lt;/span&gt;&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;CORSMiddleware,&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span class=&quot;indent&quot;&gt;    &lt;/span&gt;&lt;span style=&quot;--0:#FFA657&quot;&gt;allow_origins&lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;=&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;[&lt;/span&gt;&lt;span style=&quot;--0:#A5D6FF&quot;&gt;&quot;https://yourfrontend.com&quot;&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;],&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span class=&quot;indent&quot;&gt;    &lt;/span&gt;&lt;span style=&quot;--0:#FFA657&quot;&gt;allow_methods&lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;=&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;[&lt;/span&gt;&lt;span style=&quot;--0:#A5D6FF&quot;&gt;&quot;QUERY&quot;&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;, &lt;/span&gt;&lt;span style=&quot;--0:#A5D6FF&quot;&gt;&quot;OPTIONS&quot;&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;],&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span class=&quot;indent&quot;&gt;    &lt;/span&gt;&lt;span style=&quot;--0:#FFA657&quot;&gt;allow_headers&lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;=&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;[&lt;/span&gt;&lt;span style=&quot;--0:#A5D6FF&quot;&gt;&quot;Content-Type&quot;&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;, &lt;/span&gt;&lt;span style=&quot;--0:#A5D6FF&quot;&gt;&quot;Accept&quot;&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;],&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;)&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;
&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;class&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; &lt;/span&gt;&lt;span style=&quot;--0:#FFA657&quot;&gt;PriceRange&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;(&lt;/span&gt;&lt;span style=&quot;--0:#79C0FF&quot;&gt;BaseModel&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;):&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span class=&quot;indent&quot;&gt;    &lt;/span&gt;&lt;span style=&quot;--0:#79C0FF&quot;&gt;min&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;: Optional[&lt;/span&gt;&lt;span style=&quot;--0:#79C0FF&quot;&gt;float&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;] &lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;=&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; Field(&lt;/span&gt;&lt;span style=&quot;--0:#FFA657&quot;&gt;default&lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;=&lt;/span&gt;&lt;span style=&quot;--0:#79C0FF&quot;&gt;None&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;, &lt;/span&gt;&lt;span style=&quot;--0:#FFA657&quot;&gt;ge&lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;=&lt;/span&gt;&lt;span style=&quot;--0:#79C0FF&quot;&gt;0&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;)&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span class=&quot;indent&quot;&gt;    &lt;/span&gt;&lt;span style=&quot;--0:#79C0FF&quot;&gt;max&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;: Optional[&lt;/span&gt;&lt;span style=&quot;--0:#79C0FF&quot;&gt;float&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;] &lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;=&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; Field(&lt;/span&gt;&lt;span style=&quot;--0:#FFA657&quot;&gt;default&lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;=&lt;/span&gt;&lt;span style=&quot;--0:#79C0FF&quot;&gt;None&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;, &lt;/span&gt;&lt;span style=&quot;--0:#FFA657&quot;&gt;ge&lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;=&lt;/span&gt;&lt;span style=&quot;--0:#79C0FF&quot;&gt;0&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;)&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;
&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;class&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; &lt;/span&gt;&lt;span style=&quot;--0:#FFA657&quot;&gt;ProductQuery&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;(&lt;/span&gt;&lt;span style=&quot;--0:#79C0FF&quot;&gt;BaseModel&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;):&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span class=&quot;indent&quot;&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;    &lt;/span&gt;&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;category: Optional[&lt;/span&gt;&lt;span style=&quot;--0:#79C0FF&quot;&gt;str&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;] &lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;=&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; &lt;/span&gt;&lt;span style=&quot;--0:#79C0FF&quot;&gt;None&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span class=&quot;indent&quot;&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;    &lt;/span&gt;&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;brand: Optional[&lt;/span&gt;&lt;span style=&quot;--0:#79C0FF&quot;&gt;str&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;] &lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;=&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; &lt;/span&gt;&lt;span style=&quot;--0:#79C0FF&quot;&gt;None&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span class=&quot;indent&quot;&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;    &lt;/span&gt;&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;price: Optional[PriceRange] &lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;=&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; &lt;/span&gt;&lt;span style=&quot;--0:#79C0FF&quot;&gt;None&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span class=&quot;indent&quot;&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;    &lt;/span&gt;&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;sort: Optional[Literal[&lt;/span&gt;&lt;span style=&quot;--0:#A5D6FF&quot;&gt;&quot;price&quot;&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;, &lt;/span&gt;&lt;span style=&quot;--0:#A5D6FF&quot;&gt;&quot;-price&quot;&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;, &lt;/span&gt;&lt;span style=&quot;--0:#A5D6FF&quot;&gt;&quot;name&quot;&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;, &lt;/span&gt;&lt;span style=&quot;--0:#A5D6FF&quot;&gt;&quot;-name&quot;&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;]] &lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;=&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; &lt;/span&gt;&lt;span style=&quot;--0:#79C0FF&quot;&gt;None&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span class=&quot;indent&quot;&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;    &lt;/span&gt;&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;page: &lt;/span&gt;&lt;span style=&quot;--0:#79C0FF&quot;&gt;int&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; &lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;=&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; Field(&lt;/span&gt;&lt;span style=&quot;--0:#FFA657&quot;&gt;default&lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;=&lt;/span&gt;&lt;span style=&quot;--0:#79C0FF&quot;&gt;1&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;, &lt;/span&gt;&lt;span style=&quot;--0:#FFA657&quot;&gt;ge&lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;=&lt;/span&gt;&lt;span style=&quot;--0:#79C0FF&quot;&gt;1&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;)&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span class=&quot;indent&quot;&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;    &lt;/span&gt;&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;limit: &lt;/span&gt;&lt;span style=&quot;--0:#79C0FF&quot;&gt;int&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; &lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;=&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; Field(&lt;/span&gt;&lt;span style=&quot;--0:#FFA657&quot;&gt;default&lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;=&lt;/span&gt;&lt;span style=&quot;--0:#79C0FF&quot;&gt;20&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;, &lt;/span&gt;&lt;span style=&quot;--0:#FFA657&quot;&gt;le&lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;=&lt;/span&gt;&lt;span style=&quot;--0:#79C0FF&quot;&gt;100&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;)&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;
&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span style=&quot;--0:#D2A8FF&quot;&gt;@app.api_route&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;(&lt;/span&gt;&lt;span style=&quot;--0:#A5D6FF&quot;&gt;&quot;/products&quot;&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;, &lt;/span&gt;&lt;span style=&quot;--0:#FFA657&quot;&gt;methods&lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;=&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;[&lt;/span&gt;&lt;span style=&quot;--0:#A5D6FF&quot;&gt;&quot;QUERY&quot;&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;])&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;async&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; &lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;def&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; &lt;/span&gt;&lt;span style=&quot;--0:#D2A8FF&quot;&gt;query_products&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;(request: Request, payload: ProductQuery):&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span class=&quot;indent&quot;&gt;    &lt;/span&gt;&lt;span style=&quot;--0:#8B949E&quot;&gt;# Principle 2: Validate Content-Type (do not skip this step!)&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span class=&quot;indent&quot;&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;    &lt;/span&gt;&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;content_type &lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;=&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; request.headers.get(&lt;/span&gt;&lt;span style=&quot;--0:#A5D6FF&quot;&gt;&quot;content-type&quot;&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;, &lt;/span&gt;&lt;span style=&quot;--0:#A5D6FF&quot;&gt;&quot;&quot;&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;)&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span class=&quot;indent&quot;&gt;    &lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;if&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; &lt;/span&gt;&lt;span style=&quot;--0:#A5D6FF&quot;&gt;&quot;application/json&quot;&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; &lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;not&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; &lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;in&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; content_type:&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span class=&quot;indent&quot;&gt;        &lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;raise&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; HTTPException(&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span class=&quot;indent&quot;&gt;            &lt;/span&gt;&lt;span style=&quot;--0:#FFA657&quot;&gt;status_code&lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;=&lt;/span&gt;&lt;span style=&quot;--0:#79C0FF&quot;&gt;415&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;,&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span class=&quot;indent&quot;&gt;            &lt;/span&gt;&lt;span style=&quot;--0:#FFA657&quot;&gt;detail&lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;=&lt;/span&gt;&lt;span style=&quot;--0:#A5D6FF&quot;&gt;&quot;This endpoint only accepts application/json for QUERY requests&quot;&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;,&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span class=&quot;indent&quot;&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;        &lt;/span&gt;&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;)&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;
&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span class=&quot;indent&quot;&gt;    &lt;/span&gt;&lt;span style=&quot;--0:#8B949E&quot;&gt;# Principle 3: Do not include any database write operations inside this function&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span class=&quot;indent&quot;&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;    &lt;/span&gt;&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;filtered &lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;=&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; apply_filters(payload)&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;
&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span class=&quot;indent&quot;&gt;    &lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;return&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; {&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span class=&quot;indent&quot;&gt;        &lt;/span&gt;&lt;span style=&quot;--0:#A5D6FF&quot;&gt;&quot;query&quot;&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;: payload.model_dump(&lt;/span&gt;&lt;span style=&quot;--0:#FFA657&quot;&gt;exclude_none&lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;=&lt;/span&gt;&lt;span style=&quot;--0:#79C0FF&quot;&gt;True&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;),&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span class=&quot;indent&quot;&gt;        &lt;/span&gt;&lt;span style=&quot;--0:#A5D6FF&quot;&gt;&quot;count&quot;&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;: &lt;/span&gt;&lt;span style=&quot;--0:#79C0FF&quot;&gt;len&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;(filtered),&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span class=&quot;indent&quot;&gt;        &lt;/span&gt;&lt;span style=&quot;--0:#A5D6FF&quot;&gt;&quot;results&quot;&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;: filtered,&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span class=&quot;indent&quot;&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;    &lt;/span&gt;&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;}&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;
&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span style=&quot;--0:#D2A8FF&quot;&gt;@app.options&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;(&lt;/span&gt;&lt;span style=&quot;--0:#A5D6FF&quot;&gt;&quot;/products&quot;&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;)&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;async&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; &lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;def&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; &lt;/span&gt;&lt;span style=&quot;--0:#D2A8FF&quot;&gt;products_options&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;():&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span class=&quot;indent&quot;&gt;    &lt;/span&gt;&lt;span style=&quot;--0:#8B949E&quot;&gt;# Principle 4: Enable discoverability using Accept-Query&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span class=&quot;indent&quot;&gt;    &lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;from&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; fastapi.responses &lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;import&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; Response&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;
&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span class=&quot;indent&quot;&gt;    &lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;return&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; Response(&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span class=&quot;indent&quot;&gt;        &lt;/span&gt;&lt;span style=&quot;--0:#FFA657&quot;&gt;status_code&lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;=&lt;/span&gt;&lt;span style=&quot;--0:#79C0FF&quot;&gt;204&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;,&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span class=&quot;indent&quot;&gt;        &lt;/span&gt;&lt;span style=&quot;--0:#FFA657&quot;&gt;headers&lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;=&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;{&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span class=&quot;indent&quot;&gt;            &lt;/span&gt;&lt;span style=&quot;--0:#A5D6FF&quot;&gt;&quot;Allow&quot;&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;: &lt;/span&gt;&lt;span style=&quot;--0:#A5D6FF&quot;&gt;&quot;GET, QUERY, OPTIONS&quot;&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;,&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span class=&quot;indent&quot;&gt;            &lt;/span&gt;&lt;span style=&quot;--0:#A5D6FF&quot;&gt;&quot;Accept-Query&quot;&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;: &lt;/span&gt;&lt;span style=&quot;--0:#A5D6FF&quot;&gt;&quot;application/json&quot;&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;,&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span class=&quot;indent&quot;&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;        &lt;/span&gt;&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;},&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span class=&quot;indent&quot;&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;    &lt;/span&gt;&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;)&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;
&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;def&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; &lt;/span&gt;&lt;span style=&quot;--0:#D2A8FF&quot;&gt;apply_filters&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;(query: ProductQuery) -&gt; list[&lt;/span&gt;&lt;span style=&quot;--0:#79C0FF&quot;&gt;dict&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;]:&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span class=&quot;indent&quot;&gt;    &lt;/span&gt;&lt;span style=&quot;--0:#8B949E&quot;&gt;# Your actual database query logic will go here&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span class=&quot;indent&quot;&gt;    &lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;return&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; []&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;/code&gt;&lt;/pre&gt;&lt;div class=&quot;copy&quot;&gt;&lt;div aria-live=&quot;polite&quot;&gt;&lt;/div&gt;&lt;button title=&quot;Copy to clipboard&quot; data-copied=&quot;Copied!&quot; data-code=&quot;# main.pyfrom fastapi import FastAPI, Request, HTTPExceptionfrom fastapi.middleware.cors import CORSMiddlewarefrom pydantic import BaseModel, Fieldfrom typing import Optional, Literalapp = FastAPI(title=&amp;#x22;Product Search API&amp;#x22;)# Principle 5: Explicitly add QUERY to the CORS middlewareapp.add_middleware(    CORSMiddleware,    allow_origins=[&amp;#x22;https://yourfrontend.com&amp;#x22;],    allow_methods=[&amp;#x22;QUERY&amp;#x22;, &amp;#x22;OPTIONS&amp;#x22;],    allow_headers=[&amp;#x22;Content-Type&amp;#x22;, &amp;#x22;Accept&amp;#x22;],)class PriceRange(BaseModel):    min: Optional[float] = Field(default=None, ge=0)    max: Optional[float] = Field(default=None, ge=0)class ProductQuery(BaseModel):    category: Optional[str] = None    brand: Optional[str] = None    price: Optional[PriceRange] = None    sort: Optional[Literal[&amp;#x22;price&amp;#x22;, &amp;#x22;-price&amp;#x22;, &amp;#x22;name&amp;#x22;, &amp;#x22;-name&amp;#x22;]] = None    page: int = Field(default=1, ge=1)    limit: int = Field(default=20, le=100)@app.api_route(&amp;#x22;/products&amp;#x22;, methods=[&amp;#x22;QUERY&amp;#x22;])async def query_products(request: Request, payload: ProductQuery):    # Principle 2: Validate Content-Type (do not skip this step!)    content_type = request.headers.get(&amp;#x22;content-type&amp;#x22;, &amp;#x22;&amp;#x22;)    if &amp;#x22;application/json&amp;#x22; not in content_type:        raise HTTPException(            status_code=415,            detail=&amp;#x22;This endpoint only accepts application/json for QUERY requests&amp;#x22;,        )    # Principle 3: Do not include any database write operations inside this function    filtered = apply_filters(payload)    return {        &amp;#x22;query&amp;#x22;: payload.model_dump(exclude_none=True),        &amp;#x22;count&amp;#x22;: len(filtered),        &amp;#x22;results&amp;#x22;: filtered,    }@app.options(&amp;#x22;/products&amp;#x22;)async def products_options():    # Principle 4: Enable discoverability using Accept-Query    from fastapi.responses import Response    return Response(        status_code=204,        headers={            &amp;#x22;Allow&amp;#x22;: &amp;#x22;GET, QUERY, OPTIONS&amp;#x22;,            &amp;#x22;Accept-Query&amp;#x22;: &amp;#x22;application/json&amp;#x22;,        },    )def apply_filters(query: ProductQuery) -&gt; list[dict]:    # Your actual database query logic will go here    return []&quot;&gt;&lt;div&gt;&lt;/div&gt;&lt;/button&gt;&lt;/div&gt;&lt;/figure&gt;&lt;/div&gt;
&lt;p&gt;Did you notice how we routed the handler? I used &lt;code&gt;@app.api_route&lt;/code&gt; here because FastAPI does not yet include a built-in decorator like &lt;code&gt;@app.get&lt;/code&gt; or &lt;code&gt;@app.post&lt;/code&gt; for the QUERY method. However, the &lt;code&gt;api_route&lt;/code&gt; decorator allows you to pass any arbitrary string into its &lt;code&gt;methods&lt;/code&gt; parameter. Under the hood, Starlette simply matches the &lt;code&gt;scope[&quot;method&quot;]&lt;/code&gt; of the incoming request against your provided list, which makes routing work smoothly.&lt;/p&gt;
&lt;div class=&quot;callout&quot; role=&quot;note&quot; data-type=&quot;note&quot;&gt;
&lt;p class=&quot;callout-title&quot;&gt;A Minor Limitation in OpenAPI Documentation&lt;/p&gt;
&lt;p&gt;The official OpenAPI specification method list does not yet explicitly include the QUERY method. As a result, automated documentation interfaces like Swagger UI or ReDoc might not render this endpoint correctly. Do not let this worry you! Your endpoint will function perfectly at runtime. Instead of relying on GUI documentation tools, verify your implementation directly using an HTTP client.&lt;/p&gt;
&lt;/div&gt;
&lt;h3 id=&quot;writing-automated-tests-with-pytest&quot;&gt;Writing Automated Tests with Pytest&lt;/h3&gt;
&lt;p&gt;We cannot write production code without testing it properly, right? Let us write a quick asynchronous test:&lt;/p&gt;
&lt;div class=&quot;expressive-code&quot;&gt;&lt;figure class=&quot;frame has-title&quot;&gt;&lt;figcaption class=&quot;header&quot;&gt;&lt;span class=&quot;title&quot;&gt;Python&lt;/span&gt;&lt;/figcaption&gt;&lt;pre data-language=&quot;python&quot;&gt;&lt;code&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span style=&quot;--0:#8B949E&quot;&gt;# test_products.py&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;import&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; pytest&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;from&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; httpx &lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;import&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; AsyncClient, ASGITransport&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;from&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; main &lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;import&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; app&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;
&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span style=&quot;--0:#D2A8FF&quot;&gt;@pytest.mark.asyncio&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;async&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; &lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;def&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; &lt;/span&gt;&lt;span style=&quot;--0:#D2A8FF&quot;&gt;test_query_products_success&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;():&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span class=&quot;indent&quot;&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;    &lt;/span&gt;&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;transport &lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;=&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; ASGITransport(&lt;/span&gt;&lt;span style=&quot;--0:#FFA657&quot;&gt;app&lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;=&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;app)&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span class=&quot;indent&quot;&gt;    &lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;async&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; &lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;with&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; AsyncClient(&lt;/span&gt;&lt;span style=&quot;--0:#FFA657&quot;&gt;transport&lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;=&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;transport, &lt;/span&gt;&lt;span style=&quot;--0:#FFA657&quot;&gt;base_url&lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;=&lt;/span&gt;&lt;span style=&quot;--0:#A5D6FF&quot;&gt;&quot;http://test&quot;&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;) &lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;as&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; client:&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span class=&quot;indent&quot;&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;        &lt;/span&gt;&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;response &lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;=&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; &lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;await&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; client.request(&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span class=&quot;indent&quot;&gt;            &lt;/span&gt;&lt;span style=&quot;--0:#FFA657&quot;&gt;method&lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;=&lt;/span&gt;&lt;span style=&quot;--0:#A5D6FF&quot;&gt;&quot;QUERY&quot;&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;, &lt;/span&gt;&lt;span style=&quot;--0:#FFA657&quot;&gt;url&lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;=&lt;/span&gt;&lt;span style=&quot;--0:#A5D6FF&quot;&gt;&quot;/products&quot;&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;,&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span class=&quot;indent&quot;&gt;            &lt;/span&gt;&lt;span style=&quot;--0:#FFA657&quot;&gt;json&lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;=&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;{&lt;/span&gt;&lt;span style=&quot;--0:#A5D6FF&quot;&gt;&quot;category&quot;&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;: &lt;/span&gt;&lt;span style=&quot;--0:#A5D6FF&quot;&gt;&quot;phone&quot;&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;, &lt;/span&gt;&lt;span style=&quot;--0:#A5D6FF&quot;&gt;&quot;brand&quot;&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;: &lt;/span&gt;&lt;span style=&quot;--0:#A5D6FF&quot;&gt;&quot;apple&quot;&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;},&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span class=&quot;indent&quot;&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;        &lt;/span&gt;&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;)&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span class=&quot;indent&quot;&gt;    &lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;assert&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; response.status_code &lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;==&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; &lt;/span&gt;&lt;span style=&quot;--0:#79C0FF&quot;&gt;200&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span class=&quot;indent&quot;&gt;    &lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;assert&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; response.json()[&lt;/span&gt;&lt;span style=&quot;--0:#A5D6FF&quot;&gt;&quot;query&quot;&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;][&lt;/span&gt;&lt;span style=&quot;--0:#A5D6FF&quot;&gt;&quot;category&quot;&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;] &lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;==&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; &lt;/span&gt;&lt;span style=&quot;--0:#A5D6FF&quot;&gt;&quot;phone&quot;&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;/code&gt;&lt;/pre&gt;&lt;div class=&quot;copy&quot;&gt;&lt;div aria-live=&quot;polite&quot;&gt;&lt;/div&gt;&lt;button title=&quot;Copy to clipboard&quot; data-copied=&quot;Copied!&quot; data-code=&quot;# test_products.pyimport pytestfrom httpx import AsyncClient, ASGITransportfrom main import app@pytest.mark.asyncioasync def test_query_products_success():    transport = ASGITransport(app=app)    async with AsyncClient(transport=transport, base_url=&amp;#x22;http://test&amp;#x22;) as client:        response = await client.request(            method=&amp;#x22;QUERY&amp;#x22;, url=&amp;#x22;/products&amp;#x22;,            json={&amp;#x22;category&amp;#x22;: &amp;#x22;phone&amp;#x22;, &amp;#x22;brand&amp;#x22;: &amp;#x22;apple&amp;#x22;},        )    assert response.status_code == 200    assert response.json()[&amp;#x22;query&amp;#x22;][&amp;#x22;category&amp;#x22;] == &amp;#x22;phone&amp;#x22;&quot;&gt;&lt;div&gt;&lt;/div&gt;&lt;/button&gt;&lt;/div&gt;&lt;/figure&gt;&lt;/div&gt;
&lt;p&gt;If you want to perform a manual verification from your command line using curl, run this command:&lt;/p&gt;
&lt;div class=&quot;expressive-code&quot;&gt;&lt;figure class=&quot;frame is-terminal has-title&quot;&gt;&lt;figcaption class=&quot;header&quot;&gt;&lt;span class=&quot;title&quot;&gt;Terminal&lt;/span&gt;&lt;/figcaption&gt;&lt;pre data-language=&quot;bash&quot;&gt;&lt;code&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span style=&quot;--0:#FFA657&quot;&gt;curl&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; &lt;/span&gt;&lt;span style=&quot;--0:#79C0FF&quot;&gt;-i&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; &lt;/span&gt;&lt;span style=&quot;--0:#79C0FF&quot;&gt;-X&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; &lt;/span&gt;&lt;span style=&quot;--0:#A5D6FF&quot;&gt;QUERY&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; &lt;/span&gt;&lt;span style=&quot;--0:#A5D6FF&quot;&gt;http://localhost:8000/products&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; &lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;\&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span class=&quot;indent&quot;&gt;  &lt;/span&gt;&lt;span style=&quot;--0:#79C0FF&quot;&gt;-H&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; &lt;/span&gt;&lt;span style=&quot;--0:#A5D6FF&quot;&gt;&quot;Content-Type: application/json&quot;&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; &lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;\&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span class=&quot;indent&quot;&gt;  &lt;/span&gt;&lt;span style=&quot;--0:#79C0FF&quot;&gt;-d&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; &lt;/span&gt;&lt;span style=&quot;--0:#A5D6FF&quot;&gt;&apos;{&quot;category&quot;: &quot;phone&quot;, &quot;brand&quot;: &quot;apple&quot;, &quot;price&quot;: {&quot;min&quot;: 100, &quot;max&quot;: 1000}}&apos;&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;/code&gt;&lt;/pre&gt;&lt;div class=&quot;copy&quot;&gt;&lt;div aria-live=&quot;polite&quot;&gt;&lt;/div&gt;&lt;button title=&quot;Copy to clipboard&quot; data-copied=&quot;Copied!&quot; data-code=&quot;curl -i -X QUERY http://localhost:8000/products \  -H &amp;#x22;Content-Type: application/json&amp;#x22; \  -d &amp;#x27;{&amp;#x22;category&amp;#x22;: &amp;#x22;phone&amp;#x22;, &amp;#x22;brand&amp;#x22;: &amp;#x22;apple&amp;#x22;, &amp;#x22;price&amp;#x22;: {&amp;#x22;min&amp;#x22;: 100, &amp;#x22;max&amp;#x22;: 1000}}&amp;#x27;&quot;&gt;&lt;div&gt;&lt;/div&gt;&lt;/button&gt;&lt;/div&gt;&lt;/figure&gt;&lt;/div&gt;
&lt;figure&gt;&lt;img src=&quot;https://raw.githubusercontent.com/rafeuddaraj/rafes-blog-assets/refs/heads/http-query-method-rfc-10008-complete-engineering-handbook/assets/http-query-method-comparison.svg&quot; alt=&quot;HTTP Method Semantic Comparison: GET vs POST vs QUERY method comparison for caching and database interaction&quot; loading=&quot;lazy&quot; decoding=&quot;async&quot; width=&quot;900&quot; height=&quot;560&quot;&gt;&lt;figcaption&gt;HTTP Method Semantic Comparison: GET vs POST vs QUERY method comparison for caching and database interaction&lt;/figcaption&gt;&lt;/figure&gt;
&lt;h2 id=&quot;the-server-layer-trap-uncovering-uvicorn-parser-internals&quot;&gt;The Server-Layer Trap: Uncovering Uvicorn Parser Internals&lt;/h2&gt;
&lt;p&gt;Hold on, do not rush off just yet! There is a critical production trap hidden right here. Our very first principle becomes extremely important in this scenario. While the FastAPI code above will work perfectly on your local development machine, it can fail silently once deployed to production. Do you know why that happens?&lt;/p&gt;
&lt;p&gt;Uvicorn can operate using two different underlying HTTP parsers. When you install the server using &lt;code&gt;pip install uvicorn[standard]&lt;/code&gt;, the default parser installed is &lt;code&gt;httptools&lt;/code&gt;. This is essentially a Python wrapper around the &lt;code&gt;llhttp&lt;/code&gt; parser from Node.js. Think of this parser as a strict school headmaster! It validates method names against a fixed, case-sensitive lookup table. To &lt;code&gt;httptools&lt;/code&gt;, an uppercase &lt;code&gt;&quot;QUERY&quot;&lt;/code&gt; and a lowercase &lt;code&gt;&quot;query&quot;&lt;/code&gt; are completely different strings. If a client mistakenly sends a lowercase &lt;code&gt;&quot;query&quot;&lt;/code&gt;, &lt;code&gt;httptools&lt;/code&gt; fails to recognize it and immediately rejects the request with a &lt;code&gt;400 Bad Request&lt;/code&gt; error before it ever reaches your FastAPI application code!&lt;/p&gt;
&lt;p&gt;In contrast, Uvicorn&apos;s second parsing option is &lt;code&gt;h11&lt;/code&gt;. This is a pure-Python implementation of HTTP/1.1, and it acts like a relaxed, forgiving friend. It does not complain about lowercase HTTP method names and allows the request to pass directly to your application routing layer. If the router cannot find a matching endpoint, it politely returns a &lt;code&gt;405 Method Not Allowed&lt;/code&gt; response instead of outright rejecting the protocol.&lt;/p&gt;
&lt;figure&gt;&lt;img src=&quot;https://raw.githubusercontent.com/rafeuddaraj/rafes-blog-assets/refs/heads/http-query-method-rfc-10008-complete-engineering-handbook/assets/fastapi-uvicorn-query-parser-flow.svg&quot; alt=&quot;Routing diagram of a FastAPI QUERY request returning 400 to an httptools parser and 200 to an h11 parser&quot; loading=&quot;lazy&quot; decoding=&quot;async&quot; width=&quot;900&quot; height=&quot;620&quot;&gt;&lt;figcaption&gt;Routing diagram of a FastAPI QUERY request returning 400 to an httptools parser and 200 to an h11 parser&lt;/figcaption&gt;&lt;/figure&gt;
&lt;p&gt;What is the best solution for this mismatch? You should explicitly select your parser in the terminal when launching your server:&lt;/p&gt;
&lt;div class=&quot;expressive-code&quot;&gt;&lt;figure class=&quot;frame is-terminal has-title&quot;&gt;&lt;figcaption class=&quot;header&quot;&gt;&lt;span class=&quot;title&quot;&gt;Terminal&lt;/span&gt;&lt;/figcaption&gt;&lt;pre data-language=&quot;bash&quot;&gt;&lt;code&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span style=&quot;--0:#8B949E&quot;&gt;# Explicitly select your HTTP parser&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span style=&quot;--0:#FFA657&quot;&gt;uvicorn&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; &lt;/span&gt;&lt;span style=&quot;--0:#A5D6FF&quot;&gt;main:app&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; &lt;/span&gt;&lt;span style=&quot;--0:#79C0FF&quot;&gt;--http&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; &lt;/span&gt;&lt;span style=&quot;--0:#A5D6FF&quot;&gt;httptools&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;   &lt;/span&gt;&lt;span style=&quot;--0:#8B949E&quot;&gt;# Default, faster performance, but strictly case-sensitive&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span style=&quot;--0:#FFA657&quot;&gt;uvicorn&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; &lt;/span&gt;&lt;span style=&quot;--0:#A5D6FF&quot;&gt;main:app&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; &lt;/span&gt;&lt;span style=&quot;--0:#79C0FF&quot;&gt;--http&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; &lt;/span&gt;&lt;span style=&quot;--0:#A5D6FF&quot;&gt;h11&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;         &lt;/span&gt;&lt;span style=&quot;--0:#8B949E&quot;&gt;# Slightly slower performance, but much more lenient&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;/code&gt;&lt;/pre&gt;&lt;div class=&quot;copy&quot;&gt;&lt;div aria-live=&quot;polite&quot;&gt;&lt;/div&gt;&lt;button title=&quot;Copy to clipboard&quot; data-copied=&quot;Copied!&quot; data-code=&quot;uvicorn main:app --http httptools   # Default, faster performance, but strictly case-sensitiveuvicorn main:app --http h11         # Slightly slower performance, but much more lenient&quot;&gt;&lt;div&gt;&lt;/div&gt;&lt;/button&gt;&lt;/div&gt;&lt;/figure&gt;&lt;/div&gt;
&lt;p&gt;Now, where do these lowercase method names actually come from? The answer lies on the client side of our applications!&lt;/p&gt;
&lt;h2 id=&quot;client-side-gotcha-why-browser-fetch-keeps-your-query-lowercase&quot;&gt;Client-Side Gotcha: Why Browser fetch() Keeps Your QUERY Lowercase&lt;/h2&gt;
&lt;p&gt;Would you like to hear an unusual story about browser &lt;code&gt;fetch()&lt;/code&gt; behavior? Inside the WHATWG Fetch specification, there is a specific algorithm step called &quot;normalize a method&quot;. The purpose of this step is to automatically convert HTTP method names into uppercase characters. However, realistically, it only normalizes six classic HTTP methods: &lt;code&gt;DELETE&lt;/code&gt;, &lt;code&gt;GET&lt;/code&gt;, &lt;code&gt;HEAD&lt;/code&gt;, &lt;code&gt;OPTIONS&lt;/code&gt;, &lt;code&gt;POST&lt;/code&gt;, and &lt;code&gt;PUT&lt;/code&gt;!&lt;/p&gt;
&lt;p&gt;Our new QUERY method is not on that exclusive VIP list because it was created long after those six classic methods were standardized! As a result, if a frontend developer accidentally writes &lt;code&gt;fetch(url, { method: &quot;query&quot; })&lt;/code&gt;, the browser sends the method name across the network wire in lowercase exactly as typed! This exact behavior triggered a dedicated issue on the &lt;code&gt;whatwg/fetch&lt;/code&gt; repository in June 2026, where engineers are actively discussing whether QUERY should be added to the automatic normalization list.&lt;/p&gt;
&lt;p&gt;Therefore, whenever you write client-side fetching logic, make sure you format the method correctly:&lt;/p&gt;
&lt;div class=&quot;expressive-code&quot;&gt;&lt;figure class=&quot;frame has-title&quot;&gt;&lt;figcaption class=&quot;header&quot;&gt;&lt;span class=&quot;title&quot;&gt;JavaScript&lt;/span&gt;&lt;/figcaption&gt;&lt;pre data-language=&quot;js&quot;&gt;&lt;code&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;const&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; &lt;/span&gt;&lt;span style=&quot;--0:#79C0FF&quot;&gt;response&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; &lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;=&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; &lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;await&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; &lt;/span&gt;&lt;span style=&quot;--0:#D2A8FF&quot;&gt;fetch&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;(&lt;/span&gt;&lt;span style=&quot;--0:#A5D6FF&quot;&gt;&quot;/products&quot;&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;, {&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span class=&quot;indent&quot;&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;  &lt;/span&gt;&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;method: &lt;/span&gt;&lt;span style=&quot;--0:#A5D6FF&quot;&gt;&quot;QUERY&quot;&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;, &lt;/span&gt;&lt;span style=&quot;--0:#8B949E&quot;&gt;// You must keep this in uppercase; do not forget!&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span class=&quot;indent&quot;&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;  &lt;/span&gt;&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;headers: { &lt;/span&gt;&lt;span style=&quot;--0:#A5D6FF&quot;&gt;&quot;Content-Type&quot;&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;: &lt;/span&gt;&lt;span style=&quot;--0:#A5D6FF&quot;&gt;&quot;application/json&quot;&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; },&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span class=&quot;indent&quot;&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;  &lt;/span&gt;&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;body: &lt;/span&gt;&lt;span style=&quot;--0:#79C0FF&quot;&gt;JSON&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;.&lt;/span&gt;&lt;span style=&quot;--0:#D2A8FF&quot;&gt;stringify&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;({ category: &lt;/span&gt;&lt;span style=&quot;--0:#A5D6FF&quot;&gt;&quot;phone&quot;&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;, brand: &lt;/span&gt;&lt;span style=&quot;--0:#A5D6FF&quot;&gt;&quot;apple&quot;&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; }),&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;});&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;const&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; &lt;/span&gt;&lt;span style=&quot;--0:#79C0FF&quot;&gt;data&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; &lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;=&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; &lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;await&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; response.&lt;/span&gt;&lt;span style=&quot;--0:#D2A8FF&quot;&gt;json&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;();&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;/code&gt;&lt;/pre&gt;&lt;div class=&quot;copy&quot;&gt;&lt;div aria-live=&quot;polite&quot;&gt;&lt;/div&gt;&lt;button title=&quot;Copy to clipboard&quot; data-copied=&quot;Copied!&quot; data-code=&quot;const response = await fetch(&amp;#x22;/products&amp;#x22;, {  method: &amp;#x22;QUERY&amp;#x22;, // You must keep this in uppercase; do not forget!  headers: { &amp;#x22;Content-Type&amp;#x22;: &amp;#x22;application/json&amp;#x22; },  body: JSON.stringify({ category: &amp;#x22;phone&amp;#x22;, brand: &amp;#x22;apple&amp;#x22; }),});const data = await response.json();&quot;&gt;&lt;div&gt;&lt;/div&gt;&lt;/button&gt;&lt;/div&gt;&lt;/figure&gt;&lt;/div&gt;
&lt;p&gt;If you are sending requests from a Node.js backend to another service, you will be happy to know that Node&apos;s internal &lt;code&gt;undici&lt;/code&gt; library (which powers the built-in &lt;code&gt;fetch&lt;/code&gt; API) officially added QUERY support through a merged pull request in the summer of 2026! That update also included a helpful reference implementation for generating body-aware cache keys. In addition, Node.js has natively recognized QUERY as a valid HTTP method in its core parser since early 2024, starting from versions 21.7.2 and 22+.&lt;/p&gt;
&lt;p&gt;If you prefer making requests in Python using &lt;code&gt;httpx&lt;/code&gt;, here is how you do it:&lt;/p&gt;
&lt;div class=&quot;expressive-code&quot;&gt;&lt;figure class=&quot;frame has-title&quot;&gt;&lt;figcaption class=&quot;header&quot;&gt;&lt;span class=&quot;title&quot;&gt;Python&lt;/span&gt;&lt;/figcaption&gt;&lt;pre data-language=&quot;python&quot;&gt;&lt;code&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;import&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; httpx&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;
&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;async&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; &lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;with&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; httpx.AsyncClient() &lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;as&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; client:&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span class=&quot;indent&quot;&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;    &lt;/span&gt;&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;response &lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;=&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; &lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;await&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; client.request(&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span class=&quot;indent&quot;&gt;        &lt;/span&gt;&lt;span style=&quot;--0:#FFA657&quot;&gt;method&lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;=&lt;/span&gt;&lt;span style=&quot;--0:#A5D6FF&quot;&gt;&quot;QUERY&quot;&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;,&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span class=&quot;indent&quot;&gt;        &lt;/span&gt;&lt;span style=&quot;--0:#FFA657&quot;&gt;url&lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;=&lt;/span&gt;&lt;span style=&quot;--0:#A5D6FF&quot;&gt;&quot;http://localhost:8000/products&quot;&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;,&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span class=&quot;indent&quot;&gt;        &lt;/span&gt;&lt;span style=&quot;--0:#FFA657&quot;&gt;json&lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;=&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;{&lt;/span&gt;&lt;span style=&quot;--0:#A5D6FF&quot;&gt;&quot;category&quot;&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;: &lt;/span&gt;&lt;span style=&quot;--0:#A5D6FF&quot;&gt;&quot;phone&quot;&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;, &lt;/span&gt;&lt;span style=&quot;--0:#A5D6FF&quot;&gt;&quot;brand&quot;&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;: &lt;/span&gt;&lt;span style=&quot;--0:#A5D6FF&quot;&gt;&quot;apple&quot;&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;},&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span class=&quot;indent&quot;&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;    &lt;/span&gt;&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;)&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;/code&gt;&lt;/pre&gt;&lt;div class=&quot;copy&quot;&gt;&lt;div aria-live=&quot;polite&quot;&gt;&lt;/div&gt;&lt;button title=&quot;Copy to clipboard&quot; data-copied=&quot;Copied!&quot; data-code=&quot;import httpxasync with httpx.AsyncClient() as client:    response = await client.request(        method=&amp;#x22;QUERY&amp;#x22;,        url=&amp;#x22;http://localhost:8000/products&amp;#x22;,        json={&amp;#x22;category&amp;#x22;: &amp;#x22;phone&amp;#x22;, &amp;#x22;brand&amp;#x22;: &amp;#x22;apple&amp;#x22;},    )&quot;&gt;&lt;div&gt;&lt;/div&gt;&lt;/button&gt;&lt;/div&gt;&lt;/figure&gt;&lt;/div&gt;
&lt;h2 id=&quot;caching-the-core-promise-vs-todays-reality&quot;&gt;Caching: The Core Promise vs. Today&apos;s Reality&lt;/h2&gt;
&lt;p&gt;The biggest selling point of the QUERY method was always its ability to support caching, right? According to the RFC rules, caching a QUERY response is entirely possible. However, there is a technical catch here! You cannot build your cache key using only the URL string; the request payload body must also be an essential part of that cache key. The RFC specifically warns about a critical security risk where if a caching layer incorrectly normalizes the body and creates a false positive match, one user&apos;s sensitive data could be served to a completely different user.&lt;/p&gt;
&lt;p&gt;The reality is that as of July 2026, neither Chrome nor Firefox will serve a repeated QUERY request from the browser cache! Browser-level caching for this method is still undergoing standardization discussions, and the Fetch specification has not yet finalized how it will be implemented. That is the real challenge we face today.&lt;/p&gt;
&lt;div class=&quot;callout&quot; role=&quot;note&quot; data-type=&quot;warning&quot;&gt;
&lt;p class=&quot;callout-title&quot;&gt;Be Careful When Building Custom Caching Layers&lt;/p&gt;
&lt;p&gt;If you build your own caching architecture using tools like Redis, CDN edge rules, or reverse proxies, failing to properly hash or normalize the request body can cause two distinct filter queries to share the exact same cache entry! This mistake can lead to severe vulnerabilities like cache poisoning or cache deception. The safest approach is to generate a cryptographic digest of the body (such as SHA-256, following the &lt;code&gt;Content-Digest&lt;/code&gt; header format defined in RFC 9530) and append it to your cache key. Discussions surrounding these digest-aware caching mechanisms are currently ongoing inside the IETF HTTP Working Group.&lt;/p&gt;
&lt;/div&gt;
&lt;h2 id=&quot;infrastructure-and-ecosystem-adoption-current-status&quot;&gt;Infrastructure and Ecosystem Adoption: Current Status&lt;/h2&gt;
&lt;p&gt;This table carries the most practical engineering value in our entire guide. It clearly maps out exactly where you can safely adopt this method today and where you might face technical risks:&lt;/p&gt;
&lt;section class=&quot;table-wrap&quot; tabindex=&quot;0&quot; aria-label=&quot;Table 2&quot;&gt;
















































&lt;table&gt;&lt;thead&gt;&lt;tr&gt;&lt;th&gt;Component&lt;/th&gt;&lt;th&gt;Status (July 2026)&lt;/th&gt;&lt;/tr&gt;&lt;/thead&gt;&lt;tbody&gt;&lt;tr&gt;&lt;td&gt;Node.js core HTTP parser&lt;/td&gt;&lt;td&gt;Native support available starting from Node 21.7.2 and 22+&lt;/td&gt;&lt;/tr&gt;&lt;tr&gt;&lt;td&gt;Node.js undici / fetch&lt;/td&gt;&lt;td&gt;Support merged, including reference body-aware cache keys&lt;/td&gt;&lt;/tr&gt;&lt;tr&gt;&lt;td&gt;nginx&lt;/td&gt;&lt;td&gt;Basic RFC 10008 support has been merged&lt;/td&gt;&lt;/tr&gt;&lt;tr&gt;&lt;td&gt;Chrome, Firefox (browser fetch)&lt;/td&gt;&lt;td&gt;Scripted fetch works reliably, but browser caching is not yet implemented&lt;/td&gt;&lt;/tr&gt;&lt;tr&gt;&lt;td&gt;Kong Gateway&lt;/td&gt;&lt;td&gt;Method names must be uppercase; native QUERY awareness is currently emerging&lt;/td&gt;&lt;/tr&gt;&lt;tr&gt;&lt;td&gt;AWS API Gateway&lt;/td&gt;&lt;td&gt;No native support yet; only supports GET, POST, PUT, PATCH, DELETE, HEAD, and ANY. Using the ANY workaround carries risks of body stripping or 403/405 errors&lt;/td&gt;&lt;/tr&gt;&lt;tr&gt;&lt;td&gt;Spring Framework&lt;/td&gt;&lt;td&gt;Issues and pull requests to add support remain open&lt;/td&gt;&lt;/tr&gt;&lt;tr&gt;&lt;td&gt;Ruby on Rails&lt;/td&gt;&lt;td&gt;Community proposals are under active discussion, but not yet merged&lt;/td&gt;&lt;/tr&gt;&lt;tr&gt;&lt;td&gt;Eclipse Jetty, Apache Tomcat&lt;/td&gt;&lt;td&gt;Support issues are open with active development underway&lt;/td&gt;&lt;/tr&gt;&lt;tr&gt;&lt;td&gt;OpenAPI tooling&lt;/td&gt;&lt;td&gt;Documented in OpenAPI 3.2, but Swagger UI and ReDoc rendering remains incomplete&lt;/td&gt;&lt;/tr&gt;&lt;/tbody&gt;&lt;/table&gt;&lt;/section&gt;
&lt;div class=&quot;callout&quot; role=&quot;note&quot; data-type=&quot;warning&quot;&gt;
&lt;p class=&quot;callout-title&quot;&gt;Keep Production Readiness in Mind&lt;/p&gt;
&lt;p&gt;Looking at this adoption table explains why you should not immediately migrate all your public-facing, browser-dependent traffic to QUERY today. For server-to-server communication, especially between Node.js and properly configured Python backends, it is 100% reliable right now. However, until you verify that every layer in your network infrastructure (including clients, CDNs, API Gateways, WAFs, and backends) fully supports the method, you must keep &lt;code&gt;POST /search&lt;/code&gt; available as a reliable fallback for public APIs.&lt;/p&gt;
&lt;/div&gt;
&lt;h2 id=&quot;security-considerations&quot;&gt;Security Considerations&lt;/h2&gt;
&lt;p&gt;Designating QUERY as a safe HTTP method means that many infrastructure components, such as Web Application Firewalls, rate limiters, and CSRF protection mechanisms, will automatically treat it as harmless and non-mutating, exactly like a GET request. If a flawed backend implementation accidentally includes real state mutations inside a QUERY handler, it creates a severe security vulnerability because external protection layers will treat the operation as CSRF-exempt. Additionally, older &lt;a href=&quot;/blog/block-ai-crawlers-cloudflare-waf-guide&quot;&gt;WAF&lt;/a&gt; and reverse proxies handle unfamiliar HTTP methods inconsistently. Some security systems block unrecognized methods completely, while others pass them through without inspection. Handle this architecture with extra care!&lt;/p&gt;
&lt;h2 id=&quot;migration-strategy-how-to-adopt-step-by-step&quot;&gt;Migration Strategy: How to Adopt Step by Step&lt;/h2&gt;
&lt;p&gt;You do not need to migrate your entire system in a single leap! A realistic and smart engineering approach is to implement dual-support. Your backend can expose the exact same search business logic across two distinct endpoints:&lt;/p&gt;
&lt;div class=&quot;expressive-code&quot;&gt;&lt;figure class=&quot;frame has-title&quot;&gt;&lt;figcaption class=&quot;header&quot;&gt;&lt;span class=&quot;title&quot;&gt;Python&lt;/span&gt;&lt;/figcaption&gt;&lt;pre data-language=&quot;python&quot;&gt;&lt;code&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span style=&quot;--0:#D2A8FF&quot;&gt;@app.api_route&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;(&lt;/span&gt;&lt;span style=&quot;--0:#A5D6FF&quot;&gt;&quot;/products&quot;&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;, &lt;/span&gt;&lt;span style=&quot;--0:#FFA657&quot;&gt;methods&lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;=&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;[&lt;/span&gt;&lt;span style=&quot;--0:#A5D6FF&quot;&gt;&quot;QUERY&quot;&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;])&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;async&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; &lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;def&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; &lt;/span&gt;&lt;span style=&quot;--0:#D2A8FF&quot;&gt;query_products&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;(request: Request, payload: ProductQuery):&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span class=&quot;indent&quot;&gt;    &lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;return&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; &lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;await&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; run_search(payload)&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;
&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span style=&quot;--0:#D2A8FF&quot;&gt;@app.post&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;(&lt;/span&gt;&lt;span style=&quot;--0:#A5D6FF&quot;&gt;&quot;/products/search&quot;&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;)&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;async&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; &lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;def&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; &lt;/span&gt;&lt;span style=&quot;--0:#D2A8FF&quot;&gt;post_search_fallback&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;(payload: ProductQuery):&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span class=&quot;indent&quot;&gt;    &lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;return&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; &lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;await&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; run_search(payload)&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;/code&gt;&lt;/pre&gt;&lt;div class=&quot;copy&quot;&gt;&lt;div aria-live=&quot;polite&quot;&gt;&lt;/div&gt;&lt;button title=&quot;Copy to clipboard&quot; data-copied=&quot;Copied!&quot; data-code=&quot;@app.api_route(&amp;#x22;/products&amp;#x22;, methods=[&amp;#x22;QUERY&amp;#x22;])async def query_products(request: Request, payload: ProductQuery):    return await run_search(payload)@app.post(&amp;#x22;/products/search&amp;#x22;)async def post_search_fallback(payload: ProductQuery):    return await run_search(payload)&quot;&gt;&lt;div&gt;&lt;/div&gt;&lt;/button&gt;&lt;/div&gt;&lt;/figure&gt;&lt;/div&gt;
&lt;p&gt;On the client side, start by sending an &lt;code&gt;OPTIONS /products&lt;/code&gt; request to inspect the returned &lt;code&gt;Allow&lt;/code&gt; header. If you see that QUERY is supported, go ahead and use it confidently. If it is not listed, quietly fall back to your &lt;code&gt;POST /products/search&lt;/code&gt; endpoint. This automated feature detection allows your application to migrate smoothly as the surrounding ecosystem matures, without requiring any hard cutovers!&lt;/p&gt;
&lt;h2 id=&quot;query-vs-graphql-clearing-up-a-common-misconception&quot;&gt;QUERY vs. GraphQL: Clearing Up a Common Misconception&lt;/h2&gt;
&lt;p&gt;Many developers assume that the QUERY method was designed to replace or eliminate GraphQL. That is not true at all; these two technologies operate at completely different layers of the network stack.&lt;/p&gt;
&lt;p&gt;GraphQL is a query language and schema system that typically sits on top of a single POST endpoint. In contrast, the QUERY method itself is not a query language. It is simply an HTTP protocol method at the transport layer that can transport any query language, including GraphQL, with correct HTTP semantics. In the future, GraphQL servers could choose to use QUERY instead of POST to take full advantage of HTTP caching and idempotency mechanisms. However, doing so will not change GraphQL&apos;s underlying syntax or schema design in any way. Does that distinction make sense?&lt;/p&gt;
&lt;h2 id=&quot;testing-and-tooling-checklist&quot;&gt;Testing and Tooling Checklist&lt;/h2&gt;
&lt;p&gt;Keep an eye on how the following tools handle custom methods when building your testing workflows:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;curl:&lt;/strong&gt; Supports the method directly using the &lt;code&gt;-X QUERY&lt;/code&gt; flag, making it the most reliable tool for quick command-line testing.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;httpx (Python):&lt;/strong&gt; Works smoothly when using the syntax &lt;code&gt;client.request(method=&quot;QUERY&quot;, ...)&lt;/code&gt; inside your scripts.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;k6:&lt;/strong&gt; Natively supports custom HTTP methods, making it an excellent choice for performance and load testing.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;JMeter:&lt;/strong&gt; Does not include QUERY in its default dropdown lists, requiring you to manually configure custom properties inside the HTTP sampler.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Postman and Swagger UI:&lt;/strong&gt; Current behavior remains somewhat inconsistent because OpenAPI tooling has not fully caught up yet, so avoid relying on them blindly without verification.&lt;/li&gt;
&lt;/ul&gt;
&lt;h2 id=&quot;summary-production-checklist&quot;&gt;Summary Production Checklist&lt;/h2&gt;
&lt;ul&gt;
&lt;li&gt;Explicitly configure your ASGI server HTTP parser, ensuring you use the exact same parser engine in both your testing and production environments.&lt;/li&gt;
&lt;li&gt;Always format your method name as uppercase &lt;code&gt;&quot;QUERY&quot;&lt;/code&gt; in frontend fetch requests, and thoroughly test CORS preflight behavior using appropriate &lt;code&gt;allow_methods&lt;/code&gt; configurations.&lt;/li&gt;
&lt;li&gt;Implement strict &lt;code&gt;Content-Type&lt;/code&gt; validation, rejecting invalid requests immediately with a &lt;code&gt;400&lt;/code&gt;, &lt;code&gt;415&lt;/code&gt;, or &lt;code&gt;422&lt;/code&gt; status code at the handler gate.&lt;/li&gt;
&lt;li&gt;Provide clear endpoint discoverability by returning &lt;code&gt;Accept-Query&lt;/code&gt; and &lt;code&gt;Allow&lt;/code&gt; headers inside your &lt;code&gt;OPTIONS&lt;/code&gt; responses.&lt;/li&gt;
&lt;li&gt;Never rely blindly on automatic browser caching; if you build a custom caching layer, always include a cryptographic digest of the request body inside the cache key.&lt;/li&gt;
&lt;li&gt;Verify exactly how your Web Application Firewalls, API Gateways, and CDNs handle custom methods along your network routing path, especially when using managed services like AWS API Gateway.&lt;/li&gt;
&lt;li&gt;Maintain &lt;code&gt;POST /search&lt;/code&gt; as an active fallback endpoint for public-facing APIs until every infrastructure layer in your architecture guarantees native support.&lt;/li&gt;
&lt;li&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;h2 id=&quot;a-simple-analogy-to-wrap-everything-up&quot;&gt;A Simple Analogy to Wrap Everything Up&lt;/h2&gt;
&lt;p&gt;If this entire architectural concept still feels slightly confusing, remember this simple comparison:&lt;/p&gt;
&lt;p&gt;The GET method is like sending an open postcard through the mail. Your writing space is strictly limited, and anyone along the delivery route can read what you wrote, but sending it is fundamentally safe and harmless.&lt;/p&gt;
&lt;p&gt;The POST method is like sending a tightly sealed parcel box that contains explicit instructions to create, build, or modify something at the destination.&lt;/p&gt;
&lt;p&gt;Our new friend, the QUERY method, is like submitting a detailed, multi-page book requisition form to a library reference archive! You are not asking the librarian to modify, write in, or destroy any library books; you are simply providing complex search criteria to help them locate the exact information you need. The only catch is that this archive filing system is brand new, so while some library counters are already processing the new forms smoothly, other desks have not been trained on what the form looks like yet! That makes the difference intuitive and easy to grasp, does it not?&lt;/p&gt;
&lt;h2 id=&quot;frequently-asked-questions&quot;&gt;Frequently Asked Questions&lt;/h2&gt;
&lt;p&gt;Will the QUERY method completely replace POST?&lt;/p&gt;
&lt;p&gt;Not at all! It is designed solely to fill the specific architectural gap where safe, read-only operations require a request body. For any operation that changes server state or modifies resources, classic methods like POST, PUT, PATCH, and DELETE will continue to rule as standard practice.&lt;/p&gt;
&lt;p&gt;Can we use this in production today?&lt;/p&gt;
&lt;p&gt;For server-to-server communication, especially in internal architectures where your team controls both the client sending the request and the backend server processing it, you can adopt it with 100% confidence right now. However, for public-facing APIs accessed by web browsers, you should proceed cautiously due to the infrastructure limitations outlined in our adoption table.&lt;/p&gt;
&lt;h2 id=&quot;final-thoughts-and-best-wishes&quot;&gt;Final Thoughts and Best Wishes&lt;/h2&gt;
&lt;p&gt;We have covered quite a lot of technical ground today! I hope this complete deep dive has made the mechanics of the QUERY method crystal clear for you. Seeing an elegant engineering solution finally arrive for a 16-year-old protocol limitation is truly exciting, is it not?&lt;/p&gt;
&lt;p&gt;Please let me know if you plan to experiment with the QUERY method in your next backend project! If you ran into any confusing points or have additional questions about implementation details, drop a quick comment below so we can discuss it. Thank you very much for spending your valuable time reading through this comprehensive architectural guide, and I wish you the best of luck with your software builds!&lt;/p&gt;
&lt;h2 id=&quot;references&quot;&gt;References&lt;/h2&gt;
&lt;p&gt;&lt;strong&gt;Specification:&lt;/strong&gt;&lt;/p&gt;
&lt;ol&gt;
&lt;li&gt;RFC 10008, The HTTP QUERY Method (IETF): &lt;a href=&quot;https://www.rfc-editor.org/info/rfc10008&quot; rel=&quot;noopener noreferrer&quot;&gt;https://www.rfc-editor.org/info/rfc10008&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;HTTP Semantics, RFC 9110: &lt;a href=&quot;https://www.rfc-editor.org/rfc/rfc9110.html&quot; rel=&quot;noopener noreferrer&quot;&gt;https://www.rfc-editor.org/rfc/rfc9110.html&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;Content-Digest header field, RFC 9530: &lt;a href=&quot;https://www.rfc-editor.org/rfc/rfc9530.html&quot; rel=&quot;noopener noreferrer&quot;&gt;https://www.rfc-editor.org/rfc/rfc9530.html&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;IANA HTTP Field Name Registry (Accept-Query): &lt;a href=&quot;https://www.iana.org/assignments/http-fields&quot; rel=&quot;noopener noreferrer&quot;&gt;https://www.iana.org/assignments/http-fields&lt;/a&gt;&lt;/li&gt;
&lt;/ol&gt;
&lt;p&gt;&lt;strong&gt;Implementation and Ecosystem Discussions:&lt;/strong&gt;&lt;/p&gt;
&lt;ol start=&quot;5&quot;&gt;
&lt;li&gt;FastAPI Discussion #5520, APIRouter HTTP Method Query: &lt;a href=&quot;https://github.com/fastapi/fastapi/discussions/5520&quot; rel=&quot;noopener noreferrer&quot;&gt;https://github.com/fastapi/fastapi/discussions/5520&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;Uvicorn httptools_impl.py Source Code: &lt;a href=&quot;https://github.com/Kludex/uvicorn/blob/main/uvicorn/protocols/http/httptools_impl.py&quot; rel=&quot;noopener noreferrer&quot;&gt;https://github.com/Kludex/uvicorn/blob/main/uvicorn/protocols/http/httptools_impl.py&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;Node.js undici, QUERY method support (merged PR): &lt;a href=&quot;https://github.com/nodejs/undici/pull/5459&quot; rel=&quot;noopener noreferrer&quot;&gt;https://github.com/nodejs/undici/pull/5459&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;WHATWG Fetch, Issue #1938 (method normalization, CORS, caching): &lt;a href=&quot;https://github.com/whatwg/fetch/issues/1938&quot; rel=&quot;noopener noreferrer&quot;&gt;https://github.com/whatwg/fetch/issues/1938&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;Mozilla Standards Positions, RFC 10008: &lt;a href=&quot;https://github.com/mozilla/standards-positions/issues/1430&quot; rel=&quot;noopener noreferrer&quot;&gt;https://github.com/mozilla/standards-positions/issues/1430&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;Spring Framework, QUERY method support issue: &lt;a href=&quot;https://github.com/spring-projects/spring-framework/issues/36988&quot; rel=&quot;noopener noreferrer&quot;&gt;https://github.com/spring-projects/spring-framework/issues/36988&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;Ruby on Rails, QUERY method proposal discussion: &lt;a href=&quot;https://discuss.rubyonrails.org/t/proposal-support-for-the-http-query-method-rfc-10008/91255&quot; rel=&quot;noopener noreferrer&quot;&gt;https://discuss.rubyonrails.org/t/proposal-support-for-the-http-query-method-rfc-10008/91255&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;Ecosystem Adoption Tracker, QUERY Method: &lt;a href=&quot;https://github.com/jeswr/http-query-adoption&quot; rel=&quot;noopener noreferrer&quot;&gt;https://github.com/jeswr/http-query-adoption&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;AWS re:Post, HTTP QUERY Method and API Gateway: &lt;a href=&quot;https://repost.aws/questions/QUMU66SxOLT1qXBVZaBHCtxA/http-query-method&quot; rel=&quot;noopener noreferrer&quot;&gt;https://repost.aws/questions/QUMU66SxOLT1qXBVZaBHCtxA/http-query-method&lt;/a&gt;
&lt;strong&gt;General Reference:&lt;/strong&gt;&lt;/li&gt;
&lt;li&gt;MDN Web Docs, HTTP Request Methods: &lt;a href=&quot;https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods&quot; rel=&quot;noopener noreferrer&quot;&gt;https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods&lt;/a&gt;&lt;/li&gt;
&lt;/ol&gt;</content:encoded><category>Backend Engineering</category><category>HTTP</category><category>RFC 10008</category><category>QUERY Method</category><category>API Design</category><category>FastAPI</category><category>Python</category><category>Uvicorn</category><category>Node.js</category><category>Software Architecture</category><category>Web Development</category><category>REST API</category><category>CORS</category><category>Caching</category><category>Security</category></item><item><title>QR Code Engineering Handbook: From Optical Physics to High-Concurrency Production Pipelines</title><link>https://www.rafeuddaraj.me/blog/qr-code-engineering-handbook-optical-physics-production-pipeline/</link><guid isPermaLink="true">https://www.rafeuddaraj.me/blog/qr-code-engineering-handbook-optical-physics-production-pipeline/</guid><description>An in-depth engineering handbook breaking down QR code structural layouts, optical mechanics, Reed-Solomon error correction math, and high-throughput deployment patterns using Node.js and React.</description><pubDate>Mon, 20 Jul 2026 08:03:22 GMT</pubDate><content:encoded>&lt;p&gt;When designing a modern software system, e-commerce logistics platform, or fintech payment gateway, you will face a common but complex problem: connecting physical objects to a digital database. Look at a supermarket checkout counter, a busy airport boarding gate, or a courier warehouse, and you will see thousands of packages and transactions being processed every second. If operators try to manually type serial numbers or tracking IDs during these fast-paced operations, the system will instantly suffer from high latency and human error. Optical code scanning remains the most reliable and fastest way to handle this physical-to-digital data transfer.&lt;/p&gt;
&lt;p&gt;For a long time, One-Dimensional or 1D Barcodes like UPC-A or EAN-13 handled this job. However, global supply chains eventually needed to store a batch number, manufacturing date, expiry date, and destination URL all on a single label. This demand pushed traditional 1D Barcodes past their data capacity limits. To solve this bottleneck, Masahiro Hara, a chief engineer at the Japanese company Denso Wave, designed the Two-Dimensional or 2D Matrix Code in 1994, which we know today as the QR Code.&lt;/p&gt;
&lt;p&gt;This detailed engineering handbook aims to simplify the inner workings of QR codes for everyone from junior developers to lead system architects. We will break down optical physics, memory layouts, Reed-Solomon error correction mathematics, and high-concurrency production architectures built with Node.js and React. By mastering these architectural concepts, you will move beyond simply using third-party libraries and learn to design high-performance, fault-tolerant enterprise systems from scratch.&lt;/p&gt;
&lt;h2 id=&quot;step-1-the-optical-bottleneck-and-architectural-evolution-1d-vs-2d&quot;&gt;Step 1: The Optical Bottleneck and Architectural Evolution (1D vs 2D)&lt;/h2&gt;
&lt;p&gt;An optical scanner works by measuring light reflection. When you shine a laser beam onto a traditional 1D Barcode, the black bars absorb the light while the white spaces reflect it back. The scanner sensor measures the intensity and timing of this reflected light to generate a linear, one-way binary signal of 0s and 1s. The biggest weakness of this linear scanning mechanism is its limited data capacity, topping out at around 20 to 25 Alphanumeric Characters. If you try to store more data than this, such as a full web URL or an encrypted token, the barcode grows longer horizontally. Eventually, the code becomes too long to physically print onto a small product label.&lt;/p&gt;
&lt;p&gt;A 2D Matrix Code solves this storage limitation through a spatial layout shift. Instead of confining data to a single horizontal axis, a QR code encodes information across both the horizontal (X-axis) and vertical (Y-axis) dimensions in a spatial matrix or grid. This method increases data density hundreds of times over the same print area. In fact, a maximum-version QR code can store up to 7,089 numeric characters or 4,296 alphanumeric characters without increasing its physical footprint.&lt;/p&gt;
&lt;figure&gt;&lt;img src=&quot;https://raw.githubusercontent.com/rafeuddaraj/rafes-blog-assets/refs/heads/qr-code-engineering-handbook-optical-physics-production-pipeline/assets/barcode-vs-qrcode-architecture.svg&quot; alt=&quot;1D Linear vs 2D Spatial Scanning Architecture&quot; loading=&quot;lazy&quot; decoding=&quot;async&quot; width=&quot;800&quot; height=&quot;450&quot;&gt;&lt;figcaption&gt;1D Linear vs 2D Spatial Scanning Architecture&lt;/figcaption&gt;&lt;/figure&gt;
&lt;p&gt;To make the difference between memory layouts and data densities clear for beginners, we can use a straightforward real-world analogy.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;The Chessboard vs Single-Lane Highway Analogy:&lt;/strong&gt; Imagine a single-lane highway where cars must travel back-to-back in one line. If you try to send too many cars down this road at once, traffic jams build up and the line stretches for miles. This bottleneck represents the traditional 1D Barcode. On the other hand, a QR Code works like a massive chessboard. Each square on the board functions as an independent block for storing data. You can place and move hundreds of pieces across the entire board simultaneously, scanning from left to right and top to bottom. This spatial distribution packs a huge amount of data into a tiny space and allows fast reading from any angle.&lt;/p&gt;
&lt;div class=&quot;callout&quot; role=&quot;note&quot; data-type=&quot;note&quot;&gt;
&lt;p class=&quot;callout-title&quot;&gt;Orientation Priority&lt;/p&gt;
&lt;p&gt;When Masahiro Hara designed this code for Denso Wave, his main goal was not just increasing data size. He primarily wanted robotic arms in factories to scan codes moving on fast conveyor belts from any 360-degree orientation in milliseconds.&lt;/p&gt;
&lt;/div&gt;
&lt;hr&gt;
&lt;h2 id=&quot;step-2-qr-code-matrix-anatomy-and-optical-recognition-physics&quot;&gt;Step 2: QR Code Matrix Anatomy and Optical Recognition Physics&lt;/h2&gt;
&lt;p&gt;While a QR code might look like a random box of black and white pixels from the outside, it actually follows a highly disciplined, precise engineering architecture. When analyzing this matrix from a system architecture perspective, you can divide its physical body into several distinct functional zones. Each zone passes specific messages to the camera and the decoding algorithm.&lt;/p&gt;
&lt;figure&gt;&lt;img src=&quot;https://raw.githubusercontent.com/rafeuddaraj/rafes-blog-assets/refs/heads/qr-code-engineering-handbook-optical-physics-production-pipeline/assets/qr-code-matrix-anatomy.svg&quot; alt=&quot;QR Code Anatomy and 1:1:3:1:1 Ratio Breakdown&quot; loading=&quot;lazy&quot; decoding=&quot;async&quot; width=&quot;800&quot; height=&quot;450&quot;&gt;&lt;figcaption&gt;QR Code Anatomy and 1:1:3:1:1 Ratio Breakdown&lt;/figcaption&gt;&lt;/figure&gt;
&lt;p&gt;Let us break down how these core matrix components work and why they matter to engineers:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;
&lt;p&gt;&lt;strong&gt;Quiet Zone:&lt;/strong&gt; This mandatory white border runs around the entire outside of the code and must be at least 4 modules or pixels wide. It isolates the actual code boundaries from external background noise or surrounding text.&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;&lt;strong&gt;Position Detection or Finder Patterns:&lt;/strong&gt; These three large square blocks sit in the top-left, top-right, and bottom-left corners. If you draw a straight line through the center of these blocks, you will find that the ratio of black and white pixels always measures exactly 1:1:3:1:1. This specific optical signature allows scanners to identify a QR code instantly, even in low light or at high speeds.&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;&lt;strong&gt;Alignment Patterns:&lt;/strong&gt; These smaller square blocks sit inside various zones of the code, and their count increases as the code version grows. When a code is printed on a curved surface like a bottle or can, the camera lens captures a distorted perspective. These patterns calculate that distortion and geometrically straighten the grid.&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;&lt;strong&gt;Timing Patterns:&lt;/strong&gt; These horizontal and vertical lines of alternating black and white modules run between the finder patterns. They act like a digital clock pulse for the scanner, helping it measure the physical size of individual pixels across the grid.&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;&lt;strong&gt;Format and Version Information Zones:&lt;/strong&gt; Located right next to the finder patterns, these zones contain encrypted metadata defining the Error Correction Level and the specific Masking Pattern used. Scanners read this zone first to determine the correct decoding rules.&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;&lt;strong&gt;Data and Error Correction Payload Area:&lt;/strong&gt; This zone covers the remaining internal space of the matrix. Your binary data and Reed-Solomon error correction bits are arranged here in a predefined zigzag pattern.&lt;/p&gt;
&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;We can use a modern navigation analogy to easily understand how this spatial recognition works.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;The GPS Satellite Triangulation Analogy:&lt;/strong&gt; When you open a map app on your smartphone in an unfamiliar city, your phone connects to at least three independent GPS satellites orbiting above. By cross-referencing distances from these three points, your phone calculates your exact 3D position and orientation. Similarly, when a camera sensor captures a QR code, the image processing algorithm locates the three corner Finder Patterns first. By measuring the relative distances and angles between these three points, the algorithm determines if the code is tilted or upside down, virtually straightens it, and reads the data perfectly.&lt;/p&gt;
&lt;hr&gt;
&lt;h2 id=&quot;step-3-reed-solomon-error-correction-and-galois-field-mathematics&quot;&gt;Step 3: Reed-Solomon Error Correction and Galois Field Mathematics&lt;/h2&gt;
&lt;p&gt;The most resilient and brilliant domain within QR code engineering is the Reed-Solomon Error Correction algorithm. In production environments, printed codes face harsh real-world conditions. Dust, rain, scratches, or even intentionally embedding a company logo can obscure or destroy portions of the code. A traditional barcode would fail instantly under these conditions, but a QR code can recover 100% of its data even if up to 30% of its surface is completely ruined.&lt;/p&gt;
&lt;p&gt;This error correction mechanism relies on Galois Fields or Finite Field Arithmetic. Unlike standard algebra which handles infinite numbers, a finite field or &lt;span class=&quot;katex&quot;&gt;&lt;span class=&quot;katex-html&quot; aria-hidden=&quot;true&quot;&gt;&lt;span class=&quot;base&quot;&gt;&lt;span class=&quot;strut&quot; style=&quot;height:1.0641em;vertical-align:-0.25em;&quot;&gt;&lt;/span&gt;&lt;span class=&quot;mord mathnormal&quot; style=&quot;margin-right:0.1389em;&quot;&gt;GF&lt;/span&gt;&lt;span class=&quot;mopen&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mord&quot;&gt;&lt;span class=&quot;mord&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;msupsub&quot;&gt;&lt;span class=&quot;vlist-t&quot;&gt;&lt;span class=&quot;vlist-r&quot;&gt;&lt;span class=&quot;vlist&quot; style=&quot;height:0.8141em;&quot;&gt;&lt;span style=&quot;top:-3.063em;margin-right:0.05em;&quot;&gt;&lt;span class=&quot;pstrut&quot; style=&quot;height:2.7em;&quot;&gt;&lt;/span&gt;&lt;span class=&quot;sizing reset-size6 size3 mtight&quot;&gt;&lt;span class=&quot;mord mtight&quot;&gt;8&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class=&quot;mclose&quot;&gt;)&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/span&gt; system bounds all numbers within a strict limit of 0 to 255. A QR code offers four standard Error Correction Levels that you can choose based on your application needs:&lt;/p&gt;
&lt;section class=&quot;table-wrap&quot; tabindex=&quot;0&quot; aria-label=&quot;Table 1&quot;&gt;


































&lt;table&gt;&lt;thead&gt;&lt;tr&gt;&lt;th&gt;Error Correction Level&lt;/th&gt;&lt;th&gt;Data Recovery Capacity&lt;/th&gt;&lt;th&gt;Real-world Use Case&lt;/th&gt;&lt;/tr&gt;&lt;/thead&gt;&lt;tbody&gt;&lt;tr&gt;&lt;td&gt;&lt;strong&gt;Level L (Low)&lt;/strong&gt;&lt;/td&gt;&lt;td&gt;~7% recovery&lt;/td&gt;&lt;td&gt;Best when print quality is pristine and you need maximum data storage capacity.&lt;/td&gt;&lt;/tr&gt;&lt;tr&gt;&lt;td&gt;&lt;strong&gt;Level M (Medium)&lt;/strong&gt;&lt;/td&gt;&lt;td&gt;~15% recovery&lt;/td&gt;&lt;td&gt;The industry default. Ideal for standard URLs, business cards, and marketing materials.&lt;/td&gt;&lt;/tr&gt;&lt;tr&gt;&lt;td&gt;&lt;strong&gt;Level Q (Quartile)&lt;/strong&gt;&lt;/td&gt;&lt;td&gt;~25% recovery&lt;/td&gt;&lt;td&gt;Great for industrial environments and logistics tracking where codes face rough handling.&lt;/td&gt;&lt;/tr&gt;&lt;tr&gt;&lt;td&gt;&lt;strong&gt;Level H (High)&lt;/strong&gt;&lt;/td&gt;&lt;td&gt;~30% recovery&lt;/td&gt;&lt;td&gt;Mandatory when embedding custom brand logos or using codes in extreme factory conditions.&lt;/td&gt;&lt;/tr&gt;&lt;tr&gt;&lt;td&gt;To generate error correction codewords, we use a generator polynomial &lt;span class=&quot;katex&quot;&gt;&lt;span class=&quot;katex-html&quot; aria-hidden=&quot;true&quot;&gt;&lt;span class=&quot;base&quot;&gt;&lt;span class=&quot;strut&quot; style=&quot;height:1em;vertical-align:-0.25em;&quot;&gt;&lt;/span&gt;&lt;span class=&quot;mord mathnormal&quot; style=&quot;margin-right:0.0359em;&quot;&gt;g&lt;/span&gt;&lt;span class=&quot;mopen&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mord mathnormal&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;mclose&quot;&gt;)&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/span&gt; and a message polynomial &lt;span class=&quot;katex&quot;&gt;&lt;span class=&quot;katex-html&quot; aria-hidden=&quot;true&quot;&gt;&lt;span class=&quot;base&quot;&gt;&lt;span class=&quot;strut&quot; style=&quot;height:1em;vertical-align:-0.25em;&quot;&gt;&lt;/span&gt;&lt;span class=&quot;mord mathnormal&quot;&gt;m&lt;/span&gt;&lt;span class=&quot;mopen&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mord mathnormal&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;mclose&quot;&gt;)&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;. The primary Reed-Solomon codeword generation equation is:&lt;/td&gt;&lt;td&gt;&lt;/td&gt;&lt;td&gt;&lt;/td&gt;&lt;/tr&gt;&lt;/tbody&gt;&lt;/table&gt;&lt;/section&gt;
&lt;span class=&quot;katex-display&quot;&gt;&lt;span class=&quot;katex&quot;&gt;&lt;span class=&quot;katex-html&quot; aria-hidden=&quot;true&quot;&gt;&lt;span class=&quot;base&quot;&gt;&lt;span class=&quot;strut&quot; style=&quot;height:1em;vertical-align:-0.25em;&quot;&gt;&lt;/span&gt;&lt;span class=&quot;mord mathnormal&quot;&gt;c&lt;/span&gt;&lt;span class=&quot;mopen&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mord mathnormal&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;mclose&quot;&gt;)&lt;/span&gt;&lt;span class=&quot;mspace&quot; style=&quot;margin-right:0.2778em;&quot;&gt;&lt;/span&gt;&lt;span class=&quot;mrel&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mspace&quot; style=&quot;margin-right:0.2778em;&quot;&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class=&quot;base&quot;&gt;&lt;span class=&quot;strut&quot; style=&quot;height:1em;vertical-align:-0.25em;&quot;&gt;&lt;/span&gt;&lt;span class=&quot;mord mathnormal&quot;&gt;m&lt;/span&gt;&lt;span class=&quot;mopen&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mord mathnormal&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;mclose&quot;&gt;)&lt;/span&gt;&lt;span class=&quot;mspace&quot; style=&quot;margin-right:0.2222em;&quot;&gt;&lt;/span&gt;&lt;span class=&quot;mbin&quot;&gt;⋅&lt;/span&gt;&lt;span class=&quot;mspace&quot; style=&quot;margin-right:0.2222em;&quot;&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class=&quot;base&quot;&gt;&lt;span class=&quot;strut&quot; style=&quot;height:0.9747em;vertical-align:-0.0833em;&quot;&gt;&lt;/span&gt;&lt;span class=&quot;mord&quot;&gt;&lt;span class=&quot;mord mathnormal&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;msupsub&quot;&gt;&lt;span class=&quot;vlist-t&quot;&gt;&lt;span class=&quot;vlist-r&quot;&gt;&lt;span class=&quot;vlist&quot; style=&quot;height:0.8913em;&quot;&gt;&lt;span style=&quot;top:-3.113em;margin-right:0.05em;&quot;&gt;&lt;span class=&quot;pstrut&quot; style=&quot;height:2.7em;&quot;&gt;&lt;/span&gt;&lt;span class=&quot;sizing reset-size6 size3 mtight&quot;&gt;&lt;span class=&quot;mord mathnormal mtight&quot; style=&quot;margin-right:0.0077em;&quot;&gt;R&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class=&quot;mspace&quot; style=&quot;margin-right:0.2222em;&quot;&gt;&lt;/span&gt;&lt;span class=&quot;mbin&quot;&gt;−&lt;/span&gt;&lt;span class=&quot;mspace&quot; style=&quot;margin-right:0.2222em;&quot;&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class=&quot;base&quot;&gt;&lt;span class=&quot;strut&quot; style=&quot;height:1em;vertical-align:-0.25em;&quot;&gt;&lt;/span&gt;&lt;span class=&quot;mopen&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mord mathnormal&quot;&gt;m&lt;/span&gt;&lt;span class=&quot;mopen&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mord mathnormal&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;mclose&quot;&gt;)&lt;/span&gt;&lt;span class=&quot;mspace&quot; style=&quot;margin-right:0.2222em;&quot;&gt;&lt;/span&gt;&lt;span class=&quot;mbin&quot;&gt;⋅&lt;/span&gt;&lt;span class=&quot;mspace&quot; style=&quot;margin-right:0.2222em;&quot;&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class=&quot;base&quot;&gt;&lt;span class=&quot;strut&quot; style=&quot;height:0.8913em;&quot;&gt;&lt;/span&gt;&lt;span class=&quot;mord&quot;&gt;&lt;span class=&quot;mord mathnormal&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;msupsub&quot;&gt;&lt;span class=&quot;vlist-t&quot;&gt;&lt;span class=&quot;vlist-r&quot;&gt;&lt;span class=&quot;vlist&quot; style=&quot;height:0.8913em;&quot;&gt;&lt;span style=&quot;top:-3.113em;margin-right:0.05em;&quot;&gt;&lt;span class=&quot;pstrut&quot; style=&quot;height:2.7em;&quot;&gt;&lt;/span&gt;&lt;span class=&quot;sizing reset-size6 size3 mtight&quot;&gt;&lt;span class=&quot;mord mathnormal mtight&quot; style=&quot;margin-right:0.0077em;&quot;&gt;R&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class=&quot;mspace allowbreak&quot;&gt;&lt;/span&gt;&lt;span class=&quot;mspace&quot; style=&quot;margin-right:1em;&quot;&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class=&quot;base&quot;&gt;&lt;span class=&quot;strut&quot; style=&quot;height:1em;vertical-align:-0.25em;&quot;&gt;&lt;/span&gt;&lt;span class=&quot;mopen&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mord&quot;&gt;&lt;span class=&quot;mord&quot;&gt;&lt;span class=&quot;mord mathrm&quot;&gt;mod&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class=&quot;mspace&quot; style=&quot;margin-right:0.3333em;&quot;&gt;&lt;/span&gt;&lt;span class=&quot;mord mathnormal&quot; style=&quot;margin-right:0.0359em;&quot;&gt;g&lt;/span&gt;&lt;span class=&quot;mopen&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mord mathnormal&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;mclose&quot;&gt;))]&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;
&lt;p&gt;Here, &lt;span class=&quot;katex&quot;&gt;&lt;span class=&quot;katex-html&quot; aria-hidden=&quot;true&quot;&gt;&lt;span class=&quot;base&quot;&gt;&lt;span class=&quot;strut&quot; style=&quot;height:0.6833em;&quot;&gt;&lt;/span&gt;&lt;span class=&quot;mord mathnormal&quot; style=&quot;margin-right:0.0077em;&quot;&gt;R&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/span&gt; represents the number of error correction bytes. When you encode data, this formula appends extra parity bytes to your original message. When a scanner reads a damaged code, it runs the data through a syndrome calculator. If the data contains errors, the syndrome evaluations return non-zero values. Using these values, the algorithm determines the exact location and severity of the corruption, repairing the bits instantly.&lt;/p&gt;
&lt;figure&gt;&lt;img src=&quot;https://raw.githubusercontent.com/rafeuddaraj/rafes-blog-assets/refs/heads/qr-code-engineering-handbook-optical-physics-production-pipeline/assets/reed-solomon-error-correction.svg&quot; alt=&quot;Reed-Solomon Error Correction and Data Recovery Flow&quot; loading=&quot;lazy&quot; decoding=&quot;async&quot; width=&quot;800&quot; height=&quot;450&quot;&gt;&lt;figcaption&gt;Reed-Solomon Error Correction and Data Recovery Flow&lt;/figcaption&gt;&lt;/figure&gt;
&lt;p&gt;We can use a familiar storage architecture analogy to make this advanced math intuitive.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;The RAID Server Storage Analogy:&lt;/strong&gt; If you manage enterprise servers or distributed databases, you probably use a RAID (Redundant Array of Independent Disks) configuration to protect against data loss. For example, a RAID 5 setup writes parity information across separate drives. If one hard drive crashes completely, the server calculates the missing data using mathematical relationships from the remaining drives and parity bits. The Reed-Solomon algorithm builds a mini parity backup system right inside the QR code matrix, acting as a mathematical shield against physical damage.&lt;/p&gt;
&lt;div class=&quot;callout&quot; role=&quot;note&quot; data-type=&quot;warning&quot;&gt;
&lt;p class=&quot;callout-title&quot;&gt;Level H Memory Overhead&lt;/p&gt;
&lt;p&gt;If you select Level H without a clear reason or logo requirement, you drastically reduce your total data capacity. Nearly one-third of the available matrix space will be consumed solely by error correction bits. Stick to Level M for standard URLs to optimize space.&lt;/p&gt;
&lt;/div&gt;
&lt;hr&gt;
&lt;h2 id=&quot;step-4-step-by-step-data-encoding-pipeline-and-bit-level-masking&quot;&gt;Step 4: Step-by-Step Data Encoding Pipeline and Bit-Level Masking&lt;/h2&gt;
&lt;p&gt;QR codes scale across 40 distinct versions, which dictate the physical size and memory capacity of the matrix grid. Version 1 is the smallest, featuring a 21x21 module grid. Every version increase adds 4 modules to both the width and height, scaling all the way up to Version 40, which uses a massive 177x177 grid. A Version 40 code can hold up to 7,089 numeric characters or 4,296 alphanumeric characters. A production system automatically selects the most compact version based on your payload size and error correction configuration.&lt;/p&gt;
&lt;p&gt;Here is how a raw string like &lt;code&gt;https://blog.rafeuddaraj.me&lt;/code&gt; transforms from binary bits into a completed visual QR code:&lt;/p&gt;
&lt;figure&gt;&lt;img src=&quot;https://raw.githubusercontent.com/rafeuddaraj/rafes-blog-assets/refs/heads/qr-code-engineering-handbook-optical-physics-production-pipeline/assets/end-to-end-qr-pipeline.svg&quot; alt=&quot;End-to-End QR Code Generation and Decoding Pipeline&quot; loading=&quot;lazy&quot; decoding=&quot;async&quot; width=&quot;800&quot; height=&quot;450&quot;&gt;&lt;figcaption&gt;End-to-End QR Code Generation and Decoding Pipeline&lt;/figcaption&gt;&lt;/figure&gt;
&lt;p&gt;Let us examine how a production-grade encoder runs through this pipeline step by step:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;
&lt;p&gt;&lt;strong&gt;Step 1 - Mode Selection:&lt;/strong&gt; The encoder analyzes your input characters first. To keep the data footprint as small as possible, it selects the most efficient encoding mode: Numeric (for numbers 0-9), Alphanumeric (numbers, uppercase letters, and select symbols), Byte (for standard 8-bit data or UTF-8 text), or Kanji (for Japanese characters).&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;&lt;strong&gt;Step 2 - Bit Stream Conversion and Padding:&lt;/strong&gt; The encoder converts each character into a binary bit stream based on the chosen mode. It appends a 4-bit mode indicator (like &lt;code&gt;0100&lt;/code&gt; for byte mode) and a character count indicator at the beginning. If the resulting bit stream is shorter than the target version capacity, the encoder appends trailing zeroes and standard padding bytes (&lt;code&gt;11101100&lt;/code&gt; and &lt;code&gt;00010001&lt;/code&gt;, which are 236 and 17 in decimal) to fill out the remaining space.&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;&lt;strong&gt;Step 3 - Reed-Solomon ECC Generation:&lt;/strong&gt; The completed bit stream is broken down into specific block sizes. The encoder applies Galois field arithmetic to each block, generating the required error correction codewords. It then interleaves the original data blocks and error correction blocks into a single continuous binary sequence.&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;&lt;strong&gt;Step 4 - Matrix Placement:&lt;/strong&gt; This long binary sequence is mapped onto the 2D grid, where a 0 represents a white pixel and a 1 represents a black pixel. The placement begins at the bottom-right corner and climbs upwards in a two-module wide column, zigzagging up and down like a snake across the remaining data space.&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;&lt;strong&gt;Step 5 - Masking Pattern Application:&lt;/strong&gt; Sometimes, raw bit placement results in large clusters of identical pixels or patterns that mimic finder blocks, which confuses scanner sensors. To solve this, the QR standard uses 8 bitmask patterns (e.g., inverting pixels where &lt;span class=&quot;katex&quot;&gt;&lt;span class=&quot;katex-html&quot; aria-hidden=&quot;true&quot;&gt;&lt;span class=&quot;base&quot;&gt;&lt;span class=&quot;strut&quot; style=&quot;height:0.7429em;vertical-align:-0.0833em;&quot;&gt;&lt;/span&gt;&lt;span class=&quot;mord mathnormal&quot;&gt;i&lt;/span&gt;&lt;span class=&quot;mspace&quot; style=&quot;margin-right:0.2222em;&quot;&gt;&lt;/span&gt;&lt;span class=&quot;mbin&quot;&gt;+&lt;/span&gt;&lt;span class=&quot;mspace&quot; style=&quot;margin-right:0.2222em;&quot;&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class=&quot;base&quot;&gt;&lt;span class=&quot;strut&quot; style=&quot;height:0.854em;vertical-align:-0.1944em;&quot;&gt;&lt;/span&gt;&lt;span class=&quot;mord mathnormal&quot; style=&quot;margin-right:0.0572em;&quot;&gt;j&lt;/span&gt;&lt;span class=&quot;mspace allowbreak&quot;&gt;&lt;/span&gt;&lt;span class=&quot;mspace&quot; style=&quot;margin-right:0.4444em;&quot;&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class=&quot;base&quot;&gt;&lt;span class=&quot;strut&quot; style=&quot;height:1em;vertical-align:-0.25em;&quot;&gt;&lt;/span&gt;&lt;span class=&quot;mopen&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mord&quot;&gt;&lt;span class=&quot;mord&quot;&gt;&lt;span class=&quot;mord mathrm&quot;&gt;mod&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class=&quot;mspace&quot; style=&quot;margin-right:0.3333em;&quot;&gt;&lt;/span&gt;&lt;span class=&quot;mord&quot;&gt;3&lt;/span&gt;&lt;span class=&quot;mclose&quot;&gt;)&lt;/span&gt;&lt;span class=&quot;mspace&quot; style=&quot;margin-right:0.2778em;&quot;&gt;&lt;/span&gt;&lt;span class=&quot;mrel&quot;&gt;==&lt;/span&gt;&lt;span class=&quot;mspace&quot; style=&quot;margin-right:0.2778em;&quot;&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class=&quot;base&quot;&gt;&lt;span class=&quot;strut&quot; style=&quot;height:0.6444em;&quot;&gt;&lt;/span&gt;&lt;span class=&quot;mord&quot;&gt;0&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;). The encoder evaluates all 8 masks, applies a penalty scoring system based on optical noise, and selects the mask with the cleanest contrast balance.&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;&lt;strong&gt;Step 6 - Final Rendering:&lt;/strong&gt; Once the optimal mask is applied, its identifier is written into the format information zone. The encoder appends the mandatory 4-module wide white Quiet Zone and renders the final image as a PNG, SVG, or memory buffer.&lt;/p&gt;
&lt;/li&gt;
&lt;/ul&gt;
&lt;hr&gt;
&lt;h2 id=&quot;step-5-enterprise-production-architecture-nodejs-backend-and-react-frontend&quot;&gt;Step 5: Enterprise Production Architecture (Node.js Backend and React Frontend)&lt;/h2&gt;
&lt;p&gt;Now that we have covered the mathematical theory, let us focus on real-world implementation. When building an enterprise backend that generates thousands of dynamic QR codes per second-such as fintech OTPs, event tickets, or transaction tokens-relying on standard file system operations will cause severe production bottlenecks. Writing images to a local disk and reading them back to serve client requests is slow. Blocking disk I/O degrades the Node.js event loop, creating high CPU overhead and memory leaks under heavy loads.&lt;/p&gt;
&lt;p&gt;To eliminate this bottleneck, you must generate codes as in-memory buffer streams asynchronously. Below is a production-ready, memory-optimized enterprise QR generation service built with Node.js and TypeScript:&lt;/p&gt;
&lt;div class=&quot;expressive-code&quot;&gt;&lt;style&gt;.expressive-code{font-family:var(--ec-uiFontFml);font-size:var(--ec-uiFontSize);font-weight:var(--ec-uiFontWg);line-height:var(--ec-uiLineHt);text-size-adjust:none;-webkit-text-size-adjust:none}.expressive-code *:not(:is(svg, svg *)){all:revert;box-sizing:border-box}.expressive-code pre{display:flex;margin:0;padding:0;border:var(--ec-brdWd) solid var(--ec-brdCol);border-radius:calc(var(--ec-brdRad) + var(--ec-brdWd));background:var(--ec-codeBg)}.expressive-code pre:focus-visible{outline:3px solid var(--ec-focusBrd);outline-offset:-3px}.expressive-code pre &gt; code{all:unset;display:block;flex:1 0 100%;padding:var(--ec-codePadBlk) 0;color:var(--ec-codeFg);font-family:var(--ec-codeFontFml);font-size:var(--ec-codeFontSize);font-weight:var(--ec-codeFontWg);line-height:var(--ec-codeLineHt)}.expressive-code pre{overflow-x:auto}.expressive-code pre.wrap .ec-line .code{white-space:pre-wrap;overflow-wrap:break-word;min-width:min(20ch, var(--ecMaxLine, 20ch))}.expressive-code pre.wrap .ec-line .code span.indent{white-space:pre}.expressive-code pre::-webkit-scrollbar,.expressive-code pre::-webkit-scrollbar-track{background-color:inherit;border-radius:calc(var(--ec-brdRad) + var(--ec-brdWd));border-top-left-radius:0;border-top-right-radius:0}.expressive-code pre::-webkit-scrollbar-thumb{background-color:var(--ec-sbThumbCol);border:4px solid transparent;background-clip:content-box;border-radius:10px}.expressive-code pre::-webkit-scrollbar-thumb:hover{background-color:var(--ec-sbThumbHoverCol)}.expressive-code pre::-webkit-scrollbar-corner{background:transparent}.expressive-code .ec-line{direction:ltr;unicode-bidi:isolate;display:grid;grid-template-areas:&apos;gutter code&apos;;grid-template-columns:auto 1fr;position:relative}.expressive-code .ec-line .gutter{grid-area:gutter;color:var(--ec-gtrFg)}.expressive-code .ec-line .gutter &gt; *{pointer-events:none;user-select:none;-webkit-user-select:none}.expressive-code .ec-line .gutter ~ .code{--ecLineBrdCol:var(--ec-gtrBrdCol)}.expressive-code .ec-line.highlight .gutter{color:var(--ec-gtrHlFg)}.expressive-code .ec-line .code{grid-area:code;position:relative;box-sizing:content-box;padding-inline-start:calc(var(--ecIndent, 0ch) + var(--ec-codePadInl) - var(--ecGtrBrdWd));padding-inline-end:var(--ec-codePadInl);text-indent:calc(var(--ecIndent, 0ch) * -1)}.expressive-code .ec-line .code::before,.expressive-code .ec-line .code::after,.expressive-code .ec-line .code :where(*){text-indent:0}.expressive-code .ec-line .code{--ecGtrBrdWd:var(--ec-gtrBrdWd);border-inline-start:var(--ecGtrBrdWd) solid var(--ecLineBrdCol, transparent)}.expressive-code .sr-only{position:absolute;width:1px;height:1px;padding:0;margin:-1px;overflow:hidden;clip:rect(0, 0, 0, 0);white-space:nowrap;border-width:0}.expressive-code .ec-line.mark{--tmLineBgCol:var(--ec-tm-markBg)}.expressive-code .ec-line.mark .code{--ecLineBrdCol:var(--ec-tm-markBrdCol)}.expressive-code .ec-line.ins{--tmLineBgCol:var(--ec-tm-insBg);--tmLabel:var(--ec-tm-insDiffIndContent)}.expressive-code .ec-line.ins .code{--ecLineBrdCol:var(--ec-tm-insBrdCol)}.expressive-code .ec-line.ins .code::before{color:var(--ec-tm-insDiffIndCol)}.expressive-code .ec-line.del{--tmLineBgCol:var(--ec-tm-delBg);--tmLabel:var(--ec-tm-delDiffIndContent)}.expressive-code .ec-line.del .code{--ecLineBrdCol:var(--ec-tm-delBrdCol)}.expressive-code .ec-line.del .code::before{color:var(--ec-tm-delDiffIndCol)}.expressive-code .ec-line.mark,.expressive-code .ec-line.ins,.expressive-code .ec-line.del{background:var(--tmLineBgCol)}.expressive-code .ec-line.mark .code,.expressive-code .ec-line.ins .code,.expressive-code .ec-line.del .code{--ecGtrBrdWd:var(--ec-tm-lineMarkerAccentWd)}.expressive-code .ec-line.mark .code::before,.expressive-code .ec-line.ins .code::before,.expressive-code .ec-line.del .code::before{display:block;position:absolute;left:0;box-sizing:border-box;content:var(--tmLabel, &apos; &apos;);padding-inline-start:var(--ec-tm-lineDiffIndMargLeft);text-align:center;white-space:pre}.expressive-code .ec-line.mark.tm-label .code::before,.expressive-code .ec-line.ins.tm-label .code::before,.expressive-code .ec-line.del.tm-label .code::before{background:var(--ecLineBrdCol);padding:0 calc(var(--ec-tm-lineMarkerLabelPadInl) + var(--ec-tm-lineMarkerAccentWd)) 0 var(--ec-tm-lineMarkerLabelPadInl);color:var(--ec-tm-lineMarkerLabelCol)}.expressive-code .ec-line mark{--tmInlineBgCol:var(--ec-tm-markBg);--tmInlineBrdCol:var(--ec-tm-markBrdCol)}.expressive-code .ec-line ins{--tmInlineBgCol:var(--ec-tm-insBg);--tmInlineBrdCol:var(--ec-tm-insBrdCol)}.expressive-code .ec-line del{--tmInlineBgCol:var(--ec-tm-delBg);--tmInlineBrdCol:var(--ec-tm-delBrdCol)}.expressive-code .ec-line mark,.expressive-code .ec-line ins,.expressive-code .ec-line del{all:unset;display:inline-block;position:relative;--tmBrdL:var(--ec-tm-inlMarkerBrdWd);--tmBrdR:var(--ec-tm-inlMarkerBrdWd);--tmRadL:var(--ec-tm-inlMarkerBrdRad);--tmRadR:var(--ec-tm-inlMarkerBrdRad);margin-inline:0.025rem;padding-inline:var(--ec-tm-inlMarkerPad);border-radius:var(--tmRadL) var(--tmRadR) var(--tmRadR) var(--tmRadL);background:var(--tmInlineBgCol);background-clip:padding-box}.expressive-code .ec-line mark.open-start,.expressive-code .ec-line ins.open-start,.expressive-code .ec-line del.open-start{margin-inline-start:0;padding-inline-start:0;--tmBrdL:0px;--tmRadL:0}.expressive-code .ec-line mark.open-end,.expressive-code .ec-line ins.open-end,.expressive-code .ec-line del.open-end{margin-inline-end:0;padding-inline-end:0;--tmBrdR:0px;--tmRadR:0}.expressive-code .ec-line mark::before,.expressive-code .ec-line ins::before,.expressive-code .ec-line del::before{content:&apos;&apos;;position:absolute;pointer-events:none;display:inline-block;inset:0;border-radius:var(--tmRadL) var(--tmRadR) var(--tmRadR) var(--tmRadL);border:var(--ec-tm-inlMarkerBrdWd) solid var(--tmInlineBrdCol);border-inline-width:var(--tmBrdL) var(--tmBrdR)}.expressive-code .frame{all:unset;position:relative;display:block;--header-border-radius:calc(var(--ec-brdRad) + var(--ec-brdWd));--tab-border-radius:calc(var(--ec-frm-edTabBrdRad) + var(--ec-brdWd));--button-spacing:0.4rem;--code-background:var(--ec-frm-edBg);border-radius:var(--header-border-radius);box-shadow:var(--ec-frm-frameBoxShdCssVal)}.expressive-code .frame .header{display:none;z-index:1;position:relative;border-radius:var(--header-border-radius) var(--header-border-radius) 0 0}.expressive-code .frame.has-title pre,.expressive-code .frame.has-title code,.expressive-code .frame.is-terminal pre,.expressive-code .frame.is-terminal code{border-top:none;border-top-left-radius:0;border-top-right-radius:0}.expressive-code .frame .title:empty:before{content:&apos;\a0&apos;}.expressive-code .frame.has-title:not(.is-terminal){--button-spacing:calc(1.9rem + 2 * (var(--ec-uiPadBlk) + var(--ec-frm-edActTabIndHt)))}.expressive-code .frame.has-title:not(.is-terminal) .title{position:relative;color:var(--ec-frm-edActTabFg);background:var(--ec-frm-edActTabBg);background-clip:padding-box;margin-block-start:var(--ec-frm-edTabsMargBlkStart);padding:calc(var(--ec-uiPadBlk) + var(--ec-frm-edActTabIndHt)) var(--ec-uiPadInl);border:var(--ec-brdWd) solid var(--ec-frm-edActTabBrdCol);border-radius:var(--tab-border-radius) var(--tab-border-radius) 0 0;border-bottom:none;overflow:hidden}.expressive-code .frame.has-title:not(.is-terminal) .title::after{content:&apos;&apos;;position:absolute;pointer-events:none;inset:0;border-top:var(--ec-frm-edActTabIndHt) solid var(--ec-frm-edActTabIndTopCol);border-bottom:var(--ec-frm-edActTabIndHt) solid var(--ec-frm-edActTabIndBtmCol)}.expressive-code .frame.has-title:not(.is-terminal) .header{display:flex;background:linear-gradient(to top, var(--ec-frm-edTabBarBrdBtmCol) var(--ec-brdWd), transparent var(--ec-brdWd)),linear-gradient(var(--ec-frm-edTabBarBg), var(--ec-frm-edTabBarBg));background-repeat:no-repeat;padding-inline-start:var(--ec-frm-edTabsMargInlStart)}.expressive-code .frame.has-title:not(.is-terminal) .header::before{content:&apos;&apos;;position:absolute;pointer-events:none;inset:0;border:var(--ec-brdWd) solid var(--ec-frm-edTabBarBrdCol);border-radius:inherit;border-bottom:none}.expressive-code .frame.is-terminal{--button-spacing:calc(1.9rem + var(--ec-brdWd) + 2 * var(--ec-uiPadBlk));--code-background:var(--ec-frm-trmBg)}.expressive-code .frame.is-terminal .header{display:flex;align-items:center;justify-content:center;padding-block:var(--ec-uiPadBlk);padding-block-end:calc(var(--ec-uiPadBlk) + var(--ec-brdWd));position:relative;font-weight:500;letter-spacing:0.025ch;color:var(--ec-frm-trmTtbFg);background:var(--ec-frm-trmTtbBg);border:var(--ec-brdWd) solid var(--ec-brdCol);border-bottom:none}.expressive-code .frame.is-terminal .header::before{content:&apos;&apos;;position:absolute;pointer-events:none;left:var(--ec-uiPadInl);width:2.1rem;height:0.56rem;line-height:0;background-color:var(--ec-frm-trmTtbDotsFg);opacity:var(--ec-frm-trmTtbDotsOpa);-webkit-mask-image:var(--ec-frm-trmIcon);-webkit-mask-repeat:no-repeat;mask-image:var(--ec-frm-trmIcon);mask-repeat:no-repeat}.expressive-code .frame.is-terminal .header::after{content:&apos;&apos;;position:absolute;pointer-events:none;inset:0;border-bottom:var(--ec-brdWd) solid var(--ec-frm-trmTtbBrdBtmCol)}.expressive-code .frame pre{background:var(--code-background)}.expressive-code .copy{display:flex;gap:0.25rem;flex-direction:row;position:absolute;inset-block-start:calc(var(--ec-brdWd) + var(--button-spacing));inset-inline-end:calc(var(--ec-brdWd) + var(--ec-uiPadInl) / 2)}@media (scripting: none){.expressive-code .copy{display:none}}.expressive-code .copy{direction:ltr;unicode-bidi:isolate}.expressive-code .copy button{position:relative;align-self:flex-end;margin:0;padding:0;border:none;border-radius:0.2rem;z-index:1;cursor:pointer;transition-property:opacity, background, border-color;transition-duration:0.2s;transition-timing-function:cubic-bezier(0.25, 0.46, 0.45, 0.94);width:2.5rem;height:2.5rem;background:var(--code-background);opacity:0.75}.expressive-code .copy button div{position:absolute;inset:0;border-radius:inherit;background:var(--ec-frm-inlBtnBg);opacity:var(--ec-frm-inlBtnBgIdleOpa);transition-property:inherit;transition-duration:inherit;transition-timing-function:inherit}.expressive-code .copy button::before{content:&apos;&apos;;position:absolute;pointer-events:none;inset:0;border-radius:inherit;border:var(--ec-brdWd) solid var(--ec-frm-inlBtnBrd);opacity:var(--ec-frm-inlBtnBrdOpa)}.expressive-code .copy button::after{content:&apos;&apos;;position:absolute;pointer-events:none;inset:0;background-color:var(--ec-frm-inlBtnFg);-webkit-mask-image:var(--ec-frm-copyIcon);-webkit-mask-repeat:no-repeat;mask-image:var(--ec-frm-copyIcon);mask-repeat:no-repeat;margin:0.475rem;line-height:0}.expressive-code .copy button:hover,.expressive-code .copy button:focus:focus-visible{opacity:1}.expressive-code .copy button:hover div,.expressive-code .copy button:focus:focus-visible div{opacity:var(--ec-frm-inlBtnBgHoverOrFocusOpa)}.expressive-code .copy button:active{opacity:1}.expressive-code .copy button:active div{opacity:var(--ec-frm-inlBtnBgActOpa)}.expressive-code .copy .feedback{--tooltip-arrow-size:0.35rem;--tooltip-bg:var(--ec-frm-tooltipSuccessBg);color:var(--ec-frm-tooltipSuccessFg);pointer-events:none;user-select:none;-webkit-user-select:none;position:relative;align-self:center;background-color:var(--tooltip-bg);z-index:99;padding:0.125rem 0.75rem;border-radius:0.2rem;margin-inline-end:var(--tooltip-arrow-size);opacity:0;transition-property:opacity, transform;transition-duration:0.2s;transition-timing-function:ease-in-out;transform:translate3d(0, 0.25rem, 0)}.expressive-code .copy .feedback::after{content:&apos;&apos;;position:absolute;pointer-events:none;top:calc(50% - var(--tooltip-arrow-size));inset-inline-end:calc(-2 * (var(--tooltip-arrow-size) - 0.5px));border:var(--tooltip-arrow-size) solid transparent;border-inline-start-color:var(--tooltip-bg)}.expressive-code .copy .feedback.show{opacity:1;transform:translate3d(0, 0, 0)}@media (hover: hover){.expressive-code{}.expressive-code .copy button{opacity:0;width:2rem;height:2rem}.expressive-code .frame:hover .copy button:not(:hover),.expressive-code .frame:focus-within :focus-visible ~ .copy button:not(:hover),.expressive-code .frame .copy .feedback.show ~ button:not(:hover){opacity:0.75}}.expressive-code :nth-child(1 of .ec-line) .code{padding-inline-end:calc(2rem + var(--ec-codePadInl))}:root{--ec-brdRad:0.75rem;--ec-brdWd:1.5px;--ec-brdCol:var(--code-line);--ec-codeFontFml:var(--font-code);--ec-codeFontSize:0.875rem;--ec-codeFontWg:400;--ec-codeLineHt:1.75;--ec-codePadBlk:1rem;--ec-codePadInl:1.125rem;--ec-codeBg:var(--code-bg);--ec-codeFg:#e6edf3;--ec-codeSelBg:#264f78;--ec-gtrFg:#6e7681;--ec-gtrBrdCol:#6e768133;--ec-gtrBrdWd:1.5px;--ec-gtrHlFg:#e6edf3;--ec-uiFontFml:var(--font-mono);--ec-uiFontSize:0.75rem;--ec-uiFontWg:400;--ec-uiLineHt:1.65;--ec-uiPadBlk:0.25rem;--ec-uiPadInl:1rem;--ec-uiSelBg:#6e768166;--ec-uiSelFg:#e6edf3;--ec-focusBrd:#1f6feb;--ec-sbThumbCol:#8b949e33;--ec-sbThumbHoverCol:#8b949e3d;--ec-tm-lineMarkerAccentMarg:0rem;--ec-tm-lineMarkerAccentWd:0.15rem;--ec-tm-lineMarkerLabelPadInl:0.2rem;--ec-tm-lineMarkerLabelCol:white;--ec-tm-lineDiffIndMargLeft:0.3rem;--ec-tm-inlMarkerBrdWd:1.5px;--ec-tm-inlMarkerBrdRad:0.2rem;--ec-tm-inlMarkerPad:0.15rem;--ec-tm-insDiffIndContent:&apos;+&apos;;--ec-tm-delDiffIndContent:&apos;-&apos;;--ec-tm-markBg:#264a8980;--ec-tm-markBrdCol:#5570b3d0;--ec-tm-insBg:#26561c80;--ec-tm-insBrdCol:#4e7e41d0;--ec-tm-insDiffIndCol:#7eb070d0;--ec-tm-delBg:#81322b80;--ec-tm-delBrdCol:#ae594fd0;--ec-tm-delDiffIndCol:#e68a7ed0;--ec-frm-shdCol:#0000005b;--ec-frm-frameBoxShdCssVal:none;--ec-frm-edActTabBg:var(--code-bg);--ec-frm-edActTabFg:var(--code-muted);--ec-frm-edActTabBrdCol:transparent;--ec-frm-edActTabIndHt:1.5px;--ec-frm-edActTabIndTopCol:transparent;--ec-frm-edActTabIndBtmCol:#0d1117;--ec-frm-edTabsMargInlStart:0;--ec-frm-edTabsMargBlkStart:0;--ec-frm-edTabBrdRad:0.75rem;--ec-frm-edTabBarBg:var(--code-bg);--ec-frm-edTabBarBrdCol:var(--code-line);--ec-frm-edTabBarBrdBtmCol:var(--code-line);--ec-frm-edBg:var(--code-bg);--ec-frm-trmTtbFg:var(--code-muted);--ec-frm-trmTtbDotsFg:var(--code-muted);--ec-frm-trmTtbDotsOpa:0.15;--ec-frm-trmTtbBg:var(--code-bg);--ec-frm-trmTtbBrdBtmCol:var(--code-line);--ec-frm-trmBg:var(--code-bg);--ec-frm-inlBtnBg:var(--code-ink);--ec-frm-inlBtnBgIdleOpa:0;--ec-frm-inlBtnBgHoverOrFocusOpa:0.2;--ec-frm-inlBtnBgActOpa:0.3;--ec-frm-inlBtnFg:var(--code-ink);--ec-frm-inlBtnBrd:var(--code-line);--ec-frm-inlBtnBrdOpa:0.4;--ec-frm-tooltipSuccessBg:var(--color-emerald);--ec-frm-tooltipSuccessFg:var(--color-bg);--ec-frm-copyIcon:url(&quot;data:image/svg+xml,%3Csvg%20xmlns%3D&apos;http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg&apos;%20viewBox%3D&apos;0%200%2024%2024&apos;%20fill%3D&apos;none&apos;%20stroke%3D&apos;black&apos;%20stroke-width%3D&apos;1.75&apos;%3E%3Cpath%20d%3D&apos;M3%2019a2%202%200%200%201-1-2V2a2%202%200%200%201%201-1h13a2%202%200%200%201%202%201&apos;%2F%3E%3Crect%20x%3D&apos;6&apos;%20y%3D&apos;5&apos;%20width%3D&apos;16&apos;%20height%3D&apos;18&apos;%20rx%3D&apos;1.5&apos;%20ry%3D&apos;1.5&apos;%2F%3E%3C%2Fsvg%3E&quot;);--ec-frm-trmIcon:url(&quot;data:image/svg+xml,%3Csvg%20xmlns%3D&apos;http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg&apos;%20viewBox%3D&apos;0%200%2060%2016&apos;%20preserveAspectRatio%3D&apos;xMidYMid%20meet&apos;%3E%3Ccircle%20cx%3D&apos;8&apos;%20cy%3D&apos;8&apos;%20r%3D&apos;8&apos;%2F%3E%3Ccircle%20cx%3D&apos;30&apos;%20cy%3D&apos;8&apos;%20r%3D&apos;8&apos;%2F%3E%3Ccircle%20cx%3D&apos;52&apos;%20cy%3D&apos;8&apos;%20r%3D&apos;8&apos;%2F%3E%3C%2Fsvg%3E&quot;)}.expressive-code .ec-line :where(span[style^=&apos;--&apos;]:not([class])){color:var(--0, inherit);background-color:var(--0bg, transparent);font-style:var(--0fs, inherit);font-weight:var(--0fw, inherit);text-decoration:var(--0td, inherit)}&lt;/style&gt;&lt;script type=&quot;module&quot; src=&quot;/_astro/ec.0vx5m.js&quot;&gt;&lt;/script&gt;&lt;figure class=&quot;frame has-title&quot;&gt;&lt;figcaption class=&quot;header&quot;&gt;&lt;span class=&quot;title&quot;&gt;TypeScript&lt;/span&gt;&lt;/figcaption&gt;&lt;pre data-language=&quot;typescript&quot;&gt;&lt;code&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span style=&quot;--0:#8B949E&quot;&gt;// Enterprise-grade High-Performance QR Code Service (Node.js / TypeScript)&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;import&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; QRCode, { QRCodeToBufferOptions } &lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;from&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; &lt;/span&gt;&lt;span style=&quot;--0:#A5D6FF&quot;&gt;&apos;qrcode&apos;&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;;&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;import&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; fs &lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;from&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; &lt;/span&gt;&lt;span style=&quot;--0:#A5D6FF&quot;&gt;&apos;fs/promises&apos;&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;;&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;import&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; path &lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;from&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; &lt;/span&gt;&lt;span style=&quot;--0:#A5D6FF&quot;&gt;&apos;path&apos;&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;;&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;
&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span style=&quot;--0:#8B949E&quot;&gt;/**&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span class=&quot;indent&quot;&gt;&lt;span style=&quot;--0:#8B949E&quot;&gt; &lt;/span&gt;&lt;/span&gt;&lt;span style=&quot;--0:#8B949E&quot;&gt;* Interface representing standard enterprise response payload for QR generation.&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span class=&quot;indent&quot;&gt;&lt;span style=&quot;--0:#8B949E&quot;&gt; &lt;/span&gt;&lt;/span&gt;&lt;span style=&quot;--0:#8B949E&quot;&gt;*/&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;export&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; &lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;interface&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; &lt;/span&gt;&lt;span style=&quot;--0:#FFA657&quot;&gt;QRCodeServiceResponse&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; {&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span class=&quot;indent&quot;&gt;  &lt;/span&gt;&lt;span style=&quot;--0:#FFA657&quot;&gt;success&lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;:&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; &lt;/span&gt;&lt;span style=&quot;--0:#79C0FF&quot;&gt;boolean&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;;&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span class=&quot;indent&quot;&gt;  &lt;/span&gt;&lt;span style=&quot;--0:#FFA657&quot;&gt;buffer&lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;:&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; &lt;/span&gt;&lt;span style=&quot;--0:#FFA657&quot;&gt;Buffer&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;;&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span class=&quot;indent&quot;&gt;  &lt;/span&gt;&lt;span style=&quot;--0:#FFA657&quot;&gt;base64DataUrl&lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;:&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; &lt;/span&gt;&lt;span style=&quot;--0:#79C0FF&quot;&gt;string&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;;&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span class=&quot;indent&quot;&gt;  &lt;/span&gt;&lt;span style=&quot;--0:#FFA657&quot;&gt;savedPath&lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;?:&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; &lt;/span&gt;&lt;span style=&quot;--0:#79C0FF&quot;&gt;string&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;;&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span class=&quot;indent&quot;&gt;  &lt;/span&gt;&lt;span style=&quot;--0:#FFA657&quot;&gt;executionTimeMs&lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;:&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; &lt;/span&gt;&lt;span style=&quot;--0:#79C0FF&quot;&gt;number&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;;&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;}&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;
&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span style=&quot;--0:#8B949E&quot;&gt;/**&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span class=&quot;indent&quot;&gt;&lt;span style=&quot;--0:#8B949E&quot;&gt; &lt;/span&gt;&lt;/span&gt;&lt;span style=&quot;--0:#8B949E&quot;&gt;* Generates an enterprise-grade, high-contrast QR Code buffer in-memory.&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span class=&quot;indent&quot;&gt;&lt;span style=&quot;--0:#8B949E&quot;&gt; &lt;/span&gt;&lt;/span&gt;&lt;span style=&quot;--0:#8B949E&quot;&gt;* Optimized for high-concurrency microservices without blocking the Event Loop.&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span class=&quot;indent&quot;&gt;&lt;span style=&quot;--0:#8B949E&quot;&gt; &lt;/span&gt;&lt;/span&gt;&lt;span style=&quot;--0:#8B949E&quot;&gt;*&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span class=&quot;indent&quot;&gt;&lt;span style=&quot;--0:#8B949E&quot;&gt; &lt;/span&gt;&lt;/span&gt;&lt;span style=&quot;--0:#8B949E&quot;&gt;* &lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;@param&lt;/span&gt;&lt;span style=&quot;--0:#8B949E&quot;&gt; &lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;payload&lt;/span&gt;&lt;span style=&quot;--0:#8B949E&quot;&gt; - The raw string, URL, or JSON payload to encode.&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span class=&quot;indent&quot;&gt;&lt;span style=&quot;--0:#8B949E&quot;&gt; &lt;/span&gt;&lt;/span&gt;&lt;span style=&quot;--0:#8B949E&quot;&gt;* &lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;@param&lt;/span&gt;&lt;span style=&quot;--0:#8B949E&quot;&gt; &lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;saveToDisk&lt;/span&gt;&lt;span style=&quot;--0:#8B949E&quot;&gt; - Optional flag to asynchronously persist the image to storage.&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span class=&quot;indent&quot;&gt;&lt;span style=&quot;--0:#8B949E&quot;&gt; &lt;/span&gt;&lt;/span&gt;&lt;span style=&quot;--0:#8B949E&quot;&gt;* &lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;@param&lt;/span&gt;&lt;span style=&quot;--0:#8B949E&quot;&gt; &lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;customPath&lt;/span&gt;&lt;span style=&quot;--0:#8B949E&quot;&gt; - Optional destination file path if saveToDisk is enabled.&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span class=&quot;indent&quot;&gt;&lt;span style=&quot;--0:#8B949E&quot;&gt; &lt;/span&gt;&lt;/span&gt;&lt;span style=&quot;--0:#8B949E&quot;&gt;* &lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;@returns&lt;/span&gt;&lt;span style=&quot;--0:#8B949E&quot;&gt; Promise resolving to the complete QR Code service response.&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span class=&quot;indent&quot;&gt;&lt;span style=&quot;--0:#8B949E&quot;&gt; &lt;/span&gt;&lt;/span&gt;&lt;span style=&quot;--0:#8B949E&quot;&gt;*/&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;export&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; &lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;async&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; &lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;function&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; &lt;/span&gt;&lt;span style=&quot;--0:#D2A8FF&quot;&gt;generateEnterpriseQRCode&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;(&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span class=&quot;indent&quot;&gt;  &lt;/span&gt;&lt;span style=&quot;--0:#FFA657&quot;&gt;payload&lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;:&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; &lt;/span&gt;&lt;span style=&quot;--0:#79C0FF&quot;&gt;string&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;,&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span class=&quot;indent&quot;&gt;  &lt;/span&gt;&lt;span style=&quot;--0:#FFA657&quot;&gt;saveToDisk&lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;:&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; &lt;/span&gt;&lt;span style=&quot;--0:#79C0FF&quot;&gt;boolean&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; &lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;=&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; &lt;/span&gt;&lt;span style=&quot;--0:#79C0FF&quot;&gt;false&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;,&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span class=&quot;indent&quot;&gt;  &lt;/span&gt;&lt;span style=&quot;--0:#FFA657&quot;&gt;customPath&lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;?:&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; &lt;/span&gt;&lt;span style=&quot;--0:#79C0FF&quot;&gt;string&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;)&lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;:&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; &lt;/span&gt;&lt;span style=&quot;--0:#FFA657&quot;&gt;Promise&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;&amp;#x3C;&lt;/span&gt;&lt;span style=&quot;--0:#FFA657&quot;&gt;QRCodeServiceResponse&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;&gt; {&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span class=&quot;indent&quot;&gt;  &lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;const&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; &lt;/span&gt;&lt;span style=&quot;--0:#79C0FF&quot;&gt;startTime&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; &lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;=&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; Date.&lt;/span&gt;&lt;span style=&quot;--0:#D2A8FF&quot;&gt;now&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;();&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;
&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span class=&quot;indent&quot;&gt;  &lt;/span&gt;&lt;span style=&quot;--0:#8B949E&quot;&gt;// Validate payload length to prevent unexpected memory bloat in extreme scenarios&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span class=&quot;indent&quot;&gt;  &lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;if&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; (&lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;!&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;payload &lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;||&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; payload.&lt;/span&gt;&lt;span style=&quot;--0:#D2A8FF&quot;&gt;trim&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;().&lt;/span&gt;&lt;span style=&quot;--0:#79C0FF&quot;&gt;length&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; &lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;===&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; &lt;/span&gt;&lt;span style=&quot;--0:#79C0FF&quot;&gt;0&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;) {&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span class=&quot;indent&quot;&gt;    &lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;throw&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; &lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;new&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; &lt;/span&gt;&lt;span style=&quot;--0:#D2A8FF&quot;&gt;Error&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;(&lt;/span&gt;&lt;span style=&quot;--0:#A5D6FF&quot;&gt;&apos;[CRITICAL] QR Payload cannot be empty or undefined.&apos;&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;);&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span class=&quot;indent&quot;&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;  &lt;/span&gt;&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;}&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;
&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span class=&quot;indent&quot;&gt;  &lt;/span&gt;&lt;span style=&quot;--0:#8B949E&quot;&gt;// Enterprise configuration strictly enforcing optical contrast and safety boundaries&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span class=&quot;indent&quot;&gt;  &lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;const&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; &lt;/span&gt;&lt;span style=&quot;--0:#79C0FF&quot;&gt;options&lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;:&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; &lt;/span&gt;&lt;span style=&quot;--0:#FFA657&quot;&gt;QRCodeToBufferOptions&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; &lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;=&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; {&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span class=&quot;indent&quot;&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;    &lt;/span&gt;&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;errorCorrectionLevel: &lt;/span&gt;&lt;span style=&quot;--0:#A5D6FF&quot;&gt;&apos;H&apos;&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;, &lt;/span&gt;&lt;span style=&quot;--0:#8B949E&quot;&gt;// 30% fault tolerance for harsh production environments&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span class=&quot;indent&quot;&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;    &lt;/span&gt;&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;type: &lt;/span&gt;&lt;span style=&quot;--0:#A5D6FF&quot;&gt;&apos;png&apos;&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;,&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span class=&quot;indent&quot;&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;    &lt;/span&gt;&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;quality: &lt;/span&gt;&lt;span style=&quot;--0:#79C0FF&quot;&gt;0.98&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;,&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span class=&quot;indent&quot;&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;    &lt;/span&gt;&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;margin: &lt;/span&gt;&lt;span style=&quot;--0:#79C0FF&quot;&gt;4&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;,                 &lt;/span&gt;&lt;span style=&quot;--0:#8B949E&quot;&gt;// Strict adherence to the 4-module Quiet Zone standard&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span class=&quot;indent&quot;&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;    &lt;/span&gt;&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;color: {&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span class=&quot;indent&quot;&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;      &lt;/span&gt;&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;dark: &lt;/span&gt;&lt;span style=&quot;--0:#A5D6FF&quot;&gt;&apos;#0F172A&apos;&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;,         &lt;/span&gt;&lt;span style=&quot;--0:#8B949E&quot;&gt;// High-contrast Deep Slate (Never use absolute #000000 if printing on gloss)&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span class=&quot;indent&quot;&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;      &lt;/span&gt;&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;light: &lt;/span&gt;&lt;span style=&quot;--0:#A5D6FF&quot;&gt;&apos;#FFFFFF&apos;&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;         &lt;/span&gt;&lt;span style=&quot;--0:#8B949E&quot;&gt;// Absolute optical white background for maximum sensor reflection&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span class=&quot;indent&quot;&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;    &lt;/span&gt;&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;}&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span class=&quot;indent&quot;&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;  &lt;/span&gt;&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;};&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;
&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span class=&quot;indent&quot;&gt;  &lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;try&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; {&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span class=&quot;indent&quot;&gt;    &lt;/span&gt;&lt;span style=&quot;--0:#8B949E&quot;&gt;// Step 1: Generate High-Speed In-Memory Buffer directly bypassing disk I/O&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span class=&quot;indent&quot;&gt;    &lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;const&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; &lt;/span&gt;&lt;span style=&quot;--0:#79C0FF&quot;&gt;qrBuffer&lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;:&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; &lt;/span&gt;&lt;span style=&quot;--0:#FFA657&quot;&gt;Buffer&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; &lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;=&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; &lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;await&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; QRCode.&lt;/span&gt;&lt;span style=&quot;--0:#D2A8FF&quot;&gt;toBuffer&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;(payload, options);&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;
&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span class=&quot;indent&quot;&gt;    &lt;/span&gt;&lt;span style=&quot;--0:#8B949E&quot;&gt;// Step 2: Convert buffer to Base64 Data URL for instant React/Frontend rendering&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span class=&quot;indent&quot;&gt;    &lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;const&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; &lt;/span&gt;&lt;span style=&quot;--0:#79C0FF&quot;&gt;base64DataUrl&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; &lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;=&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; &lt;/span&gt;&lt;span style=&quot;--0:#A5D6FF&quot;&gt;`data:image/png;base64,${&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;qrBuffer&lt;/span&gt;&lt;span style=&quot;--0:#A5D6FF&quot;&gt;.&lt;/span&gt;&lt;span style=&quot;--0:#D2A8FF&quot;&gt;toString&lt;/span&gt;&lt;span style=&quot;--0:#A5D6FF&quot;&gt;(&lt;/span&gt;&lt;span style=&quot;--0:#A5D6FF&quot;&gt;&apos;base64&apos;&lt;/span&gt;&lt;span style=&quot;--0:#A5D6FF&quot;&gt;)&lt;/span&gt;&lt;span style=&quot;--0:#A5D6FF&quot;&gt;}`&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;;&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span class=&quot;indent&quot;&gt;    &lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;let&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; resolvedPath&lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;:&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; &lt;/span&gt;&lt;span style=&quot;--0:#79C0FF&quot;&gt;string&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; &lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;|&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; &lt;/span&gt;&lt;span style=&quot;--0:#79C0FF&quot;&gt;undefined&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; &lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;=&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; &lt;/span&gt;&lt;span style=&quot;--0:#79C0FF&quot;&gt;undefined&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;;&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;
&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span class=&quot;indent&quot;&gt;    &lt;/span&gt;&lt;span style=&quot;--0:#8B949E&quot;&gt;// Step 3: Asynchronously persist to Disk or Object Storage (S3/GCS) only if explicitly requested&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span class=&quot;indent&quot;&gt;    &lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;if&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; (saveToDisk &lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;&amp;#x26;&amp;#x26;&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; customPath) {&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span class=&quot;indent&quot;&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;      &lt;/span&gt;&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;resolvedPath &lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;=&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; path.&lt;/span&gt;&lt;span style=&quot;--0:#D2A8FF&quot;&gt;resolve&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;(customPath);&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span class=&quot;indent&quot;&gt;      &lt;/span&gt;&lt;span style=&quot;--0:#8B949E&quot;&gt;// Non-blocking asynchronous file writing&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span class=&quot;indent&quot;&gt;      &lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;await&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; fs.&lt;/span&gt;&lt;span style=&quot;--0:#D2A8FF&quot;&gt;writeFile&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;(resolvedPath, qrBuffer);&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span class=&quot;indent&quot;&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;    &lt;/span&gt;&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;}&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;
&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span class=&quot;indent&quot;&gt;    &lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;const&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; &lt;/span&gt;&lt;span style=&quot;--0:#79C0FF&quot;&gt;executionTimeMs&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; &lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;=&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; Date.&lt;/span&gt;&lt;span style=&quot;--0:#D2A8FF&quot;&gt;now&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;() &lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;-&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; startTime;&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;
&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span class=&quot;indent&quot;&gt;    &lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;return&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; {&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span class=&quot;indent&quot;&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;      &lt;/span&gt;&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;success: &lt;/span&gt;&lt;span style=&quot;--0:#79C0FF&quot;&gt;true&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;,&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span class=&quot;indent&quot;&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;      &lt;/span&gt;&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;buffer: qrBuffer,&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span class=&quot;indent&quot;&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;      &lt;/span&gt;&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;base64DataUrl,&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span class=&quot;indent&quot;&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;      &lt;/span&gt;&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;savedPath: resolvedPath,&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span class=&quot;indent&quot;&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;      &lt;/span&gt;&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;executionTimeMs&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span class=&quot;indent&quot;&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;    &lt;/span&gt;&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;};&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span class=&quot;indent&quot;&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;  &lt;/span&gt;&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;} &lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;catch&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; (&lt;/span&gt;&lt;span style=&quot;--0:#FFA657&quot;&gt;error&lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;:&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; &lt;/span&gt;&lt;span style=&quot;--0:#79C0FF&quot;&gt;any&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;) {&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span class=&quot;indent&quot;&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;    &lt;/span&gt;&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;console.&lt;/span&gt;&lt;span style=&quot;--0:#D2A8FF&quot;&gt;error&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;(&lt;/span&gt;&lt;span style=&quot;--0:#A5D6FF&quot;&gt;`[FATAL] System Architecture Error in QR Generation Pipeline: ${&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;error&lt;/span&gt;&lt;span style=&quot;--0:#A5D6FF&quot;&gt;.&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;message&lt;/span&gt;&lt;span style=&quot;--0:#A5D6FF&quot;&gt;}`&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;);&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span class=&quot;indent&quot;&gt;    &lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;throw&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; &lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;new&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; &lt;/span&gt;&lt;span style=&quot;--0:#D2A8FF&quot;&gt;Error&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;(&lt;/span&gt;&lt;span style=&quot;--0:#A5D6FF&quot;&gt;`Enterprise QR Pipeline Failed: ${&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;error&lt;/span&gt;&lt;span style=&quot;--0:#A5D6FF&quot;&gt;.&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;message&lt;/span&gt;&lt;span style=&quot;--0:#A5D6FF&quot;&gt;}`&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;);&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span class=&quot;indent&quot;&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;  &lt;/span&gt;&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;}&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;}&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;
&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span style=&quot;--0:#8B949E&quot;&gt;// ============================================================================&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span style=&quot;--0:#8B949E&quot;&gt;// Example Execution inside a Fastify / Express API Controller or Microservice&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span style=&quot;--0:#8B949E&quot;&gt;// ============================================================================&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;(&lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;async&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; () &lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;=&gt;&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; {&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span class=&quot;indent&quot;&gt;  &lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;try&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; {&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span class=&quot;indent&quot;&gt;    &lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;const&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; &lt;/span&gt;&lt;span style=&quot;--0:#79C0FF&quot;&gt;samplePayload&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; &lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;=&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; &lt;/span&gt;&lt;span style=&quot;--0:#A5D6FF&quot;&gt;&apos;https://blog.rafeuddaraj.me/articles/qr-code-engineering-handbook-optical-physics-production-pipeline&apos;&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;;&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span class=&quot;indent&quot;&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;    &lt;/span&gt;&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;console.&lt;/span&gt;&lt;span style=&quot;--0:#D2A8FF&quot;&gt;log&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;(&lt;/span&gt;&lt;span style=&quot;--0:#A5D6FF&quot;&gt;&apos;[LOG] Initiating In-Memory QR Code Generation...&apos;&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;);&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;
&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span class=&quot;indent&quot;&gt;    &lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;const&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; &lt;/span&gt;&lt;span style=&quot;--0:#79C0FF&quot;&gt;result&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; &lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;=&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; &lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;await&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; &lt;/span&gt;&lt;span style=&quot;--0:#D2A8FF&quot;&gt;generateEnterpriseQRCode&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;(samplePayload, &lt;/span&gt;&lt;span style=&quot;--0:#79C0FF&quot;&gt;true&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;, &lt;/span&gt;&lt;span style=&quot;--0:#A5D6FF&quot;&gt;&apos;./dist/secure-payload.png&apos;&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;);&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;
&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span class=&quot;indent&quot;&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;    &lt;/span&gt;&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;console.&lt;/span&gt;&lt;span style=&quot;--0:#D2A8FF&quot;&gt;log&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;(&lt;/span&gt;&lt;span style=&quot;--0:#A5D6FF&quot;&gt;`[SUCCESS] QR Code Generated in ${&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;result&lt;/span&gt;&lt;span style=&quot;--0:#A5D6FF&quot;&gt;.&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;executionTimeMs&lt;/span&gt;&lt;span style=&quot;--0:#A5D6FF&quot;&gt;}ms.`&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;);&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span class=&quot;indent&quot;&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;    &lt;/span&gt;&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;console.&lt;/span&gt;&lt;span style=&quot;--0:#D2A8FF&quot;&gt;log&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;(&lt;/span&gt;&lt;span style=&quot;--0:#A5D6FF&quot;&gt;`[LOG] Data URL Preview (First 50 chars): ${&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;result&lt;/span&gt;&lt;span style=&quot;--0:#A5D6FF&quot;&gt;.&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;base64DataUrl&lt;/span&gt;&lt;span style=&quot;--0:#A5D6FF&quot;&gt;.&lt;/span&gt;&lt;span style=&quot;--0:#D2A8FF&quot;&gt;substring&lt;/span&gt;&lt;span style=&quot;--0:#A5D6FF&quot;&gt;(&lt;/span&gt;&lt;span style=&quot;--0:#79C0FF&quot;&gt;0&lt;/span&gt;&lt;span style=&quot;--0:#A5D6FF&quot;&gt;, &lt;/span&gt;&lt;span style=&quot;--0:#79C0FF&quot;&gt;50&lt;/span&gt;&lt;span style=&quot;--0:#A5D6FF&quot;&gt;)&lt;/span&gt;&lt;span style=&quot;--0:#A5D6FF&quot;&gt;}...`&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;);&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span class=&quot;indent&quot;&gt;    &lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;if&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; (result.savedPath) {&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span class=&quot;indent&quot;&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;      &lt;/span&gt;&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;console.&lt;/span&gt;&lt;span style=&quot;--0:#D2A8FF&quot;&gt;log&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;(&lt;/span&gt;&lt;span style=&quot;--0:#A5D6FF&quot;&gt;`[LOG] Asynchronously persisted to local storage at: ${&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;result&lt;/span&gt;&lt;span style=&quot;--0:#A5D6FF&quot;&gt;.&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;savedPath&lt;/span&gt;&lt;span style=&quot;--0:#A5D6FF&quot;&gt;}`&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;);&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span class=&quot;indent&quot;&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;    &lt;/span&gt;&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;}&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span class=&quot;indent&quot;&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;  &lt;/span&gt;&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;} &lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;catch&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; (&lt;/span&gt;&lt;span style=&quot;--0:#FFA657&quot;&gt;err&lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;:&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; &lt;/span&gt;&lt;span style=&quot;--0:#79C0FF&quot;&gt;any&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;) {&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span class=&quot;indent&quot;&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;    &lt;/span&gt;&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;console.&lt;/span&gt;&lt;span style=&quot;--0:#D2A8FF&quot;&gt;error&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;(&lt;/span&gt;&lt;span style=&quot;--0:#A5D6FF&quot;&gt;&apos;[ERROR] Microservice execution aborted:&apos;&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;, err.message);&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span class=&quot;indent&quot;&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;  &lt;/span&gt;&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;}&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;})();&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;/code&gt;&lt;/pre&gt;&lt;div class=&quot;copy&quot;&gt;&lt;div aria-live=&quot;polite&quot;&gt;&lt;/div&gt;&lt;button title=&quot;Copy to clipboard&quot; data-copied=&quot;Copied!&quot; data-code=&quot;// Enterprise-grade High-Performance QR Code Service (Node.js / TypeScript)import QRCode, { QRCodeToBufferOptions } from &amp;#x27;qrcode&amp;#x27;;import fs from &amp;#x27;fs/promises&amp;#x27;;import path from &amp;#x27;path&amp;#x27;;/** * Interface representing standard enterprise response payload for QR generation. */export interface QRCodeServiceResponse {  success: boolean;  buffer: Buffer;  base64DataUrl: string;  savedPath?: string;  executionTimeMs: number;}/** * Generates an enterprise-grade, high-contrast QR Code buffer in-memory. * Optimized for high-concurrency microservices without blocking the Event Loop. * * @param payload - The raw string, URL, or JSON payload to encode. * @param saveToDisk - Optional flag to asynchronously persist the image to storage. * @param customPath - Optional destination file path if saveToDisk is enabled. * @returns Promise resolving to the complete QR Code service response. */export async function generateEnterpriseQRCode(  payload: string,  saveToDisk: boolean = false,  customPath?: string): Promise&lt;QRCodeServiceResponse&gt; {  const startTime = Date.now();  // Validate payload length to prevent unexpected memory bloat in extreme scenarios  if (!payload || payload.trim().length === 0) {    throw new Error(&amp;#x27;[CRITICAL] QR Payload cannot be empty or undefined.&amp;#x27;);  }  // Enterprise configuration strictly enforcing optical contrast and safety boundaries  const options: QRCodeToBufferOptions = {    errorCorrectionLevel: &amp;#x27;H&amp;#x27;, // 30% fault tolerance for harsh production environments    type: &amp;#x27;png&amp;#x27;,    quality: 0.98,    margin: 4,                 // Strict adherence to the 4-module Quiet Zone standard    color: {      dark: &amp;#x27;#0F172A&amp;#x27;,         // High-contrast Deep Slate (Never use absolute #000000 if printing on gloss)      light: &amp;#x27;#FFFFFF&amp;#x27;         // Absolute optical white background for maximum sensor reflection    }  };  try {    // Step 1: Generate High-Speed In-Memory Buffer directly bypassing disk I/O    const qrBuffer: Buffer = await QRCode.toBuffer(payload, options);    // Step 2: Convert buffer to Base64 Data URL for instant React/Frontend rendering    const base64DataUrl = &amp;#x60;data:image/png;base64,${qrBuffer.toString(&amp;#x27;base64&amp;#x27;)}&amp;#x60;;    let resolvedPath: string | undefined = undefined;    // Step 3: Asynchronously persist to Disk or Object Storage (S3/GCS) only if explicitly requested    if (saveToDisk &amp;#x26;&amp;#x26; customPath) {      resolvedPath = path.resolve(customPath);      // Non-blocking asynchronous file writing      await fs.writeFile(resolvedPath, qrBuffer);    }    const executionTimeMs = Date.now() - startTime;    return {      success: true,      buffer: qrBuffer,      base64DataUrl,      savedPath: resolvedPath,      executionTimeMs    };  } catch (error: any) {    console.error(&amp;#x60;[FATAL] System Architecture Error in QR Generation Pipeline: ${error.message}&amp;#x60;);    throw new Error(&amp;#x60;Enterprise QR Pipeline Failed: ${error.message}&amp;#x60;);  }}// ============================================================================// Example Execution inside a Fastify / Express API Controller or Microservice// ============================================================================(async () =&gt; {  try {    const samplePayload = &amp;#x27;https://blog.rafeuddaraj.me/articles/qr-code-engineering-handbook-optical-physics-production-pipeline&amp;#x27;;    console.log(&amp;#x27;[LOG] Initiating In-Memory QR Code Generation...&amp;#x27;);    const result = await generateEnterpriseQRCode(samplePayload, true, &amp;#x27;./dist/secure-payload.png&amp;#x27;);    console.log(&amp;#x60;[SUCCESS] QR Code Generated in ${result.executionTimeMs}ms.&amp;#x60;);    console.log(&amp;#x60;[LOG] Data URL Preview (First 50 chars): ${result.base64DataUrl.substring(0, 50)}...&amp;#x60;);    if (result.savedPath) {      console.log(&amp;#x60;[LOG] Asynchronously persisted to local storage at: ${result.savedPath}&amp;#x60;);    }  } catch (err: any) {    console.error(&amp;#x27;[ERROR] Microservice execution aborted:&amp;#x27;, err.message);  }})();&quot;&gt;&lt;div&gt;&lt;/div&gt;&lt;/button&gt;&lt;/div&gt;&lt;/figure&gt;&lt;/div&gt;
&lt;p&gt;While optimizing backend memory is crucial, you will encounter an even tougher engineering hurdle on the client side when handling live camera feeds in React or Next.js apps. Modern mobile cameras feed up to 60 high-resolution frames per second into the browser. If you attempt to handle image binarization and parsing inside the main UI thread using standard JavaScript, your app will lag, drop frames, heat up the phone, and drain the device battery.&lt;/p&gt;
&lt;p&gt;To solve this, your client-side architecture must run asynchronously without blocking UI interactions. You should offload processing to Web Workers and compile your parsing engine into WebAssembly (WASM). Here is a clean, production-ready React hook and component framework that extracts frames smoothly:&lt;/p&gt;
&lt;div class=&quot;expressive-code&quot;&gt;&lt;figure class=&quot;frame has-title&quot;&gt;&lt;figcaption class=&quot;header&quot;&gt;&lt;span class=&quot;title&quot;&gt;TSX&lt;/span&gt;&lt;/figcaption&gt;&lt;pre data-language=&quot;tsx&quot;&gt;&lt;code&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span style=&quot;--0:#8B949E&quot;&gt;// Production-grade React Custom Hook &amp;#x26; Component for Non-Blocking QR Scanning&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;import&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; React, { useEffect, useRef, useState, useCallback } &lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;from&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; &lt;/span&gt;&lt;span style=&quot;--0:#A5D6FF&quot;&gt;&apos;react&apos;&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;;&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;
&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span style=&quot;--0:#8B949E&quot;&gt;/**&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span class=&quot;indent&quot;&gt;&lt;span style=&quot;--0:#8B949E&quot;&gt; &lt;/span&gt;&lt;/span&gt;&lt;span style=&quot;--0:#8B949E&quot;&gt;* Interface for the Decoded QR Result payload.&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span class=&quot;indent&quot;&gt;&lt;span style=&quot;--0:#8B949E&quot;&gt; &lt;/span&gt;&lt;/span&gt;&lt;span style=&quot;--0:#8B949E&quot;&gt;*/&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;export&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; &lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;interface&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; &lt;/span&gt;&lt;span style=&quot;--0:#FFA657&quot;&gt;DecodedQRResult&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; {&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span class=&quot;indent&quot;&gt;  &lt;/span&gt;&lt;span style=&quot;--0:#FFA657&quot;&gt;text&lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;:&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; &lt;/span&gt;&lt;span style=&quot;--0:#79C0FF&quot;&gt;string&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;;&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span class=&quot;indent&quot;&gt;  &lt;/span&gt;&lt;span style=&quot;--0:#FFA657&quot;&gt;timestamp&lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;:&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; &lt;/span&gt;&lt;span style=&quot;--0:#79C0FF&quot;&gt;number&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;;&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;}&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;
&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span style=&quot;--0:#8B949E&quot;&gt;/**&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span class=&quot;indent&quot;&gt;&lt;span style=&quot;--0:#8B949E&quot;&gt; &lt;/span&gt;&lt;/span&gt;&lt;span style=&quot;--0:#8B949E&quot;&gt;* A specialized custom hook to manage live camera streaming and background Canvas frame extraction.&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span class=&quot;indent&quot;&gt;&lt;span style=&quot;--0:#8B949E&quot;&gt; &lt;/span&gt;&lt;/span&gt;&lt;span style=&quot;--0:#8B949E&quot;&gt;*/&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;export&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; &lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;function&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; &lt;/span&gt;&lt;span style=&quot;--0:#D2A8FF&quot;&gt;useOptimizedQRScanner&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;(&lt;/span&gt;&lt;span style=&quot;--0:#D2A8FF&quot;&gt;onDecode&lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;:&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; (&lt;/span&gt;&lt;span style=&quot;--0:#FFA657&quot;&gt;result&lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;:&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; &lt;/span&gt;&lt;span style=&quot;--0:#FFA657&quot;&gt;DecodedQRResult&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;) &lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;=&gt;&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; &lt;/span&gt;&lt;span style=&quot;--0:#79C0FF&quot;&gt;void&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;) {&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span class=&quot;indent&quot;&gt;  &lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;const&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; &lt;/span&gt;&lt;span style=&quot;--0:#79C0FF&quot;&gt;videoRef&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; &lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;=&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; &lt;/span&gt;&lt;span style=&quot;--0:#D2A8FF&quot;&gt;useRef&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;&amp;#x3C;&lt;/span&gt;&lt;span style=&quot;--0:#FFA657&quot;&gt;HTMLVideoElement&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; &lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;|&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; &lt;/span&gt;&lt;span style=&quot;--0:#79C0FF&quot;&gt;null&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;&gt;(&lt;/span&gt;&lt;span style=&quot;--0:#79C0FF&quot;&gt;null&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;);&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span class=&quot;indent&quot;&gt;  &lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;const&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; &lt;/span&gt;&lt;span style=&quot;--0:#79C0FF&quot;&gt;canvasRef&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; &lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;=&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; &lt;/span&gt;&lt;span style=&quot;--0:#D2A8FF&quot;&gt;useRef&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;&amp;#x3C;&lt;/span&gt;&lt;span style=&quot;--0:#FFA657&quot;&gt;HTMLCanvasElement&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; &lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;|&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; &lt;/span&gt;&lt;span style=&quot;--0:#79C0FF&quot;&gt;null&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;&gt;(&lt;/span&gt;&lt;span style=&quot;--0:#79C0FF&quot;&gt;null&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;);&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span class=&quot;indent&quot;&gt;  &lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;const&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; [&lt;/span&gt;&lt;span style=&quot;--0:#79C0FF&quot;&gt;isScanning&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;, &lt;/span&gt;&lt;span style=&quot;--0:#79C0FF&quot;&gt;setIsScanning&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;] &lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;=&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; &lt;/span&gt;&lt;span style=&quot;--0:#D2A8FF&quot;&gt;useState&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;&amp;#x3C;&lt;/span&gt;&lt;span style=&quot;--0:#79C0FF&quot;&gt;boolean&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;&gt;(&lt;/span&gt;&lt;span style=&quot;--0:#79C0FF&quot;&gt;false&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;);&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span class=&quot;indent&quot;&gt;  &lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;const&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; [&lt;/span&gt;&lt;span style=&quot;--0:#79C0FF&quot;&gt;error&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;, &lt;/span&gt;&lt;span style=&quot;--0:#79C0FF&quot;&gt;setError&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;] &lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;=&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; &lt;/span&gt;&lt;span style=&quot;--0:#D2A8FF&quot;&gt;useState&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;&amp;#x3C;&lt;/span&gt;&lt;span style=&quot;--0:#79C0FF&quot;&gt;string&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; &lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;|&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; &lt;/span&gt;&lt;span style=&quot;--0:#79C0FF&quot;&gt;null&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;&gt;(&lt;/span&gt;&lt;span style=&quot;--0:#79C0FF&quot;&gt;null&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;);&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span class=&quot;indent&quot;&gt;  &lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;const&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; &lt;/span&gt;&lt;span style=&quot;--0:#79C0FF&quot;&gt;animationFrameId&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; &lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;=&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; &lt;/span&gt;&lt;span style=&quot;--0:#D2A8FF&quot;&gt;useRef&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;&amp;#x3C;&lt;/span&gt;&lt;span style=&quot;--0:#79C0FF&quot;&gt;number&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; &lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;|&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; &lt;/span&gt;&lt;span style=&quot;--0:#79C0FF&quot;&gt;null&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;&gt;(&lt;/span&gt;&lt;span style=&quot;--0:#79C0FF&quot;&gt;null&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;);&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;
&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span class=&quot;indent&quot;&gt;  &lt;/span&gt;&lt;span style=&quot;--0:#8B949E&quot;&gt;// Stop camera stream safely to prevent memory leaks and hardware locks&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span class=&quot;indent&quot;&gt;  &lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;const&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; &lt;/span&gt;&lt;span style=&quot;--0:#79C0FF&quot;&gt;stopCamera&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; &lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;=&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; &lt;/span&gt;&lt;span style=&quot;--0:#D2A8FF&quot;&gt;useCallback&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;(() &lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;=&gt;&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; {&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span class=&quot;indent&quot;&gt;    &lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;if&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; (videoRef.current &lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;&amp;#x26;&amp;#x26;&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; videoRef.current.srcObject) {&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span class=&quot;indent&quot;&gt;      &lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;const&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; &lt;/span&gt;&lt;span style=&quot;--0:#79C0FF&quot;&gt;stream&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; &lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;=&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; videoRef.current.srcObject &lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;as&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; &lt;/span&gt;&lt;span style=&quot;--0:#FFA657&quot;&gt;MediaStream&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;;&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span class=&quot;indent&quot;&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;      &lt;/span&gt;&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;stream.&lt;/span&gt;&lt;span style=&quot;--0:#D2A8FF&quot;&gt;getTracks&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;().&lt;/span&gt;&lt;span style=&quot;--0:#D2A8FF&quot;&gt;forEach&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;((&lt;/span&gt;&lt;span style=&quot;--0:#FFA657&quot;&gt;track&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;) &lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;=&gt;&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; track.&lt;/span&gt;&lt;span style=&quot;--0:#D2A8FF&quot;&gt;stop&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;());&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span class=&quot;indent&quot;&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;      &lt;/span&gt;&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;videoRef.current.srcObject &lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;=&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; &lt;/span&gt;&lt;span style=&quot;--0:#79C0FF&quot;&gt;null&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;;&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span class=&quot;indent&quot;&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;    &lt;/span&gt;&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;}&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span class=&quot;indent&quot;&gt;    &lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;if&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; (animationFrameId.current) {&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span class=&quot;indent&quot;&gt;      &lt;/span&gt;&lt;span style=&quot;--0:#D2A8FF&quot;&gt;cancelAnimationFrame&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;(animationFrameId.current);&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span class=&quot;indent&quot;&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;    &lt;/span&gt;&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;}&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span class=&quot;indent&quot;&gt;    &lt;/span&gt;&lt;span style=&quot;--0:#D2A8FF&quot;&gt;setIsScanning&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;(&lt;/span&gt;&lt;span style=&quot;--0:#79C0FF&quot;&gt;false&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;);&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span class=&quot;indent&quot;&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;  &lt;/span&gt;&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;}, []);&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;
&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span class=&quot;indent&quot;&gt;  &lt;/span&gt;&lt;span style=&quot;--0:#8B949E&quot;&gt;// Frame extraction loop running at controlled intervals to save battery&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span class=&quot;indent&quot;&gt;  &lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;const&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; &lt;/span&gt;&lt;span style=&quot;--0:#79C0FF&quot;&gt;scanFrame&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; &lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;=&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; &lt;/span&gt;&lt;span style=&quot;--0:#D2A8FF&quot;&gt;useCallback&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;(() &lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;=&gt;&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; {&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span class=&quot;indent&quot;&gt;    &lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;if&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; (&lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;!&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;videoRef.current &lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;||&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; &lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;!&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;canvasRef.current &lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;||&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; &lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;!&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;isScanning) &lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;return&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;;&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;
&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span class=&quot;indent&quot;&gt;    &lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;const&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; &lt;/span&gt;&lt;span style=&quot;--0:#79C0FF&quot;&gt;video&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; &lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;=&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; videoRef.current;&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span class=&quot;indent&quot;&gt;    &lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;const&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; &lt;/span&gt;&lt;span style=&quot;--0:#79C0FF&quot;&gt;canvas&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; &lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;=&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; canvasRef.current;&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span class=&quot;indent&quot;&gt;    &lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;const&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; &lt;/span&gt;&lt;span style=&quot;--0:#79C0FF&quot;&gt;context&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; &lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;=&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; canvas.&lt;/span&gt;&lt;span style=&quot;--0:#D2A8FF&quot;&gt;getContext&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;(&lt;/span&gt;&lt;span style=&quot;--0:#A5D6FF&quot;&gt;&apos;2d&apos;&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;, { willReadFrequently: &lt;/span&gt;&lt;span style=&quot;--0:#79C0FF&quot;&gt;true&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; });&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;
&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span class=&quot;indent&quot;&gt;    &lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;if&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; (video.readyState &lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;===&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; video.&lt;/span&gt;&lt;span style=&quot;--0:#79C0FF&quot;&gt;HAVE_ENOUGH_DATA&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; &lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;&amp;#x26;&amp;#x26;&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; context) {&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span class=&quot;indent&quot;&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;      &lt;/span&gt;&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;canvas.width &lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;=&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; video.videoWidth;&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span class=&quot;indent&quot;&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;      &lt;/span&gt;&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;canvas.height &lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;=&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; video.videoHeight;&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;
&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span class=&quot;indent&quot;&gt;      &lt;/span&gt;&lt;span style=&quot;--0:#8B949E&quot;&gt;// Draw video frame to off-screen canvas&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span class=&quot;indent&quot;&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;      &lt;/span&gt;&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;context.&lt;/span&gt;&lt;span style=&quot;--0:#D2A8FF&quot;&gt;drawImage&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;(video, &lt;/span&gt;&lt;span style=&quot;--0:#79C0FF&quot;&gt;0&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;, &lt;/span&gt;&lt;span style=&quot;--0:#79C0FF&quot;&gt;0&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;, canvas.width, canvas.height);&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;
&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span class=&quot;indent&quot;&gt;      &lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;try&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; {&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span class=&quot;indent&quot;&gt;        &lt;/span&gt;&lt;span style=&quot;--0:#8B949E&quot;&gt;// Extract ImageData for background processing&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span class=&quot;indent&quot;&gt;        &lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;const&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; &lt;/span&gt;&lt;span style=&quot;--0:#79C0FF&quot;&gt;imageData&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; &lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;=&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; context.&lt;/span&gt;&lt;span style=&quot;--0:#D2A8FF&quot;&gt;getImageData&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;(&lt;/span&gt;&lt;span style=&quot;--0:#79C0FF&quot;&gt;0&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;, &lt;/span&gt;&lt;span style=&quot;--0:#79C0FF&quot;&gt;0&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;, canvas.width, canvas.height);&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;
&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span class=&quot;indent&quot;&gt;        &lt;/span&gt;&lt;span style=&quot;--0:#8B949E&quot;&gt;// In a true enterprise setup, send `imageData.data.buffer` to a Web Worker / WebAssembly decoder&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span class=&quot;indent&quot;&gt;        &lt;/span&gt;&lt;span style=&quot;--0:#8B949E&quot;&gt;// Example simulation of detection logic:&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span class=&quot;indent&quot;&gt;        &lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;if&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; (imageData.width &lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;&gt;&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; &lt;/span&gt;&lt;span style=&quot;--0:#79C0FF&quot;&gt;0&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;) {&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span class=&quot;indent&quot;&gt;          &lt;/span&gt;&lt;span style=&quot;--0:#8B949E&quot;&gt;// Simulated non-blocking detection check&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span class=&quot;indent&quot;&gt;          &lt;/span&gt;&lt;span style=&quot;--0:#8B949E&quot;&gt;// When WASM worker returns success, trigger callback:&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span class=&quot;indent&quot;&gt;          &lt;/span&gt;&lt;span style=&quot;--0:#8B949E&quot;&gt;// onDecode({ text: &quot;https://blog.rafeuddaraj.me&quot;, timestamp: Date.now() });&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span class=&quot;indent&quot;&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;        &lt;/span&gt;&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;}&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span class=&quot;indent&quot;&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;      &lt;/span&gt;&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;} &lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;catch&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; (&lt;/span&gt;&lt;span style=&quot;--0:#FFA657&quot;&gt;err&lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;:&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; &lt;/span&gt;&lt;span style=&quot;--0:#79C0FF&quot;&gt;any&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;) {&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span class=&quot;indent&quot;&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;        &lt;/span&gt;&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;console.&lt;/span&gt;&lt;span style=&quot;--0:#D2A8FF&quot;&gt;warn&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;(&lt;/span&gt;&lt;span style=&quot;--0:#A5D6FF&quot;&gt;&apos;[WARN] Frame extraction temporarily failed:&apos;&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;, err.message);&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span class=&quot;indent&quot;&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;      &lt;/span&gt;&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;}&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span class=&quot;indent&quot;&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;    &lt;/span&gt;&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;}&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;
&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span class=&quot;indent&quot;&gt;    &lt;/span&gt;&lt;span style=&quot;--0:#8B949E&quot;&gt;// Schedule next frame check using requestAnimationFrame instead of setInterval&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span class=&quot;indent&quot;&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;    &lt;/span&gt;&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;animationFrameId.current &lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;=&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; &lt;/span&gt;&lt;span style=&quot;--0:#D2A8FF&quot;&gt;requestAnimationFrame&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;(scanFrame);&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span class=&quot;indent&quot;&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;  &lt;/span&gt;&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;}, [isScanning, onDecode]);&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;
&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span class=&quot;indent&quot;&gt;  &lt;/span&gt;&lt;span style=&quot;--0:#8B949E&quot;&gt;// Initialize Hardware Camera Access&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span class=&quot;indent&quot;&gt;  &lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;const&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; &lt;/span&gt;&lt;span style=&quot;--0:#79C0FF&quot;&gt;startCamera&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; &lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;=&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; &lt;/span&gt;&lt;span style=&quot;--0:#D2A8FF&quot;&gt;useCallback&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;(&lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;async&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; () &lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;=&gt;&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; {&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span class=&quot;indent&quot;&gt;    &lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;try&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; {&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span class=&quot;indent&quot;&gt;      &lt;/span&gt;&lt;span style=&quot;--0:#D2A8FF&quot;&gt;setError&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;(&lt;/span&gt;&lt;span style=&quot;--0:#79C0FF&quot;&gt;null&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;);&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span class=&quot;indent&quot;&gt;      &lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;const&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; &lt;/span&gt;&lt;span style=&quot;--0:#79C0FF&quot;&gt;stream&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; &lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;=&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; &lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;await&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; navigator.mediaDevices.&lt;/span&gt;&lt;span style=&quot;--0:#D2A8FF&quot;&gt;getUserMedia&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;({&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span class=&quot;indent&quot;&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;        &lt;/span&gt;&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;video: {&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span class=&quot;indent&quot;&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;          &lt;/span&gt;&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;facingMode: &lt;/span&gt;&lt;span style=&quot;--0:#A5D6FF&quot;&gt;&apos;environment&apos;&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;, &lt;/span&gt;&lt;span style=&quot;--0:#8B949E&quot;&gt;// Request back camera for physical scanning&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span class=&quot;indent&quot;&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;          &lt;/span&gt;&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;width: { ideal: &lt;/span&gt;&lt;span style=&quot;--0:#79C0FF&quot;&gt;1280&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; },&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span class=&quot;indent&quot;&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;          &lt;/span&gt;&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;height: { ideal: &lt;/span&gt;&lt;span style=&quot;--0:#79C0FF&quot;&gt;720&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; }&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span class=&quot;indent&quot;&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;        &lt;/span&gt;&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;}&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span class=&quot;indent&quot;&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;      &lt;/span&gt;&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;});&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;
&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span class=&quot;indent&quot;&gt;      &lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;if&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; (videoRef.current) {&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span class=&quot;indent&quot;&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;        &lt;/span&gt;&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;videoRef.current.srcObject &lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;=&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; stream;&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span class=&quot;indent&quot;&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;        &lt;/span&gt;&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;videoRef.current.&lt;/span&gt;&lt;span style=&quot;--0:#D2A8FF&quot;&gt;setAttribute&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;(&lt;/span&gt;&lt;span style=&quot;--0:#A5D6FF&quot;&gt;&apos;playsinline&apos;&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;, &lt;/span&gt;&lt;span style=&quot;--0:#A5D6FF&quot;&gt;&apos;true&apos;&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;); &lt;/span&gt;&lt;span style=&quot;--0:#8B949E&quot;&gt;// Required for iOS Safari&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span class=&quot;indent&quot;&gt;        &lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;await&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; videoRef.current.&lt;/span&gt;&lt;span style=&quot;--0:#D2A8FF&quot;&gt;play&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;();&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span class=&quot;indent&quot;&gt;        &lt;/span&gt;&lt;span style=&quot;--0:#D2A8FF&quot;&gt;setIsScanning&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;(&lt;/span&gt;&lt;span style=&quot;--0:#79C0FF&quot;&gt;true&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;);&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span class=&quot;indent&quot;&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;      &lt;/span&gt;&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;}&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span class=&quot;indent&quot;&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;    &lt;/span&gt;&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;} &lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;catch&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; (&lt;/span&gt;&lt;span style=&quot;--0:#FFA657&quot;&gt;err&lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;:&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; &lt;/span&gt;&lt;span style=&quot;--0:#79C0FF&quot;&gt;any&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;) {&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span class=&quot;indent&quot;&gt;      &lt;/span&gt;&lt;span style=&quot;--0:#D2A8FF&quot;&gt;setError&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;(&lt;/span&gt;&lt;span style=&quot;--0:#A5D6FF&quot;&gt;`Camera access denied or unavailable: ${&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;err&lt;/span&gt;&lt;span style=&quot;--0:#A5D6FF&quot;&gt;.&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;message&lt;/span&gt;&lt;span style=&quot;--0:#A5D6FF&quot;&gt;}`&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;);&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span class=&quot;indent&quot;&gt;      &lt;/span&gt;&lt;span style=&quot;--0:#D2A8FF&quot;&gt;setIsScanning&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;(&lt;/span&gt;&lt;span style=&quot;--0:#79C0FF&quot;&gt;false&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;);&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span class=&quot;indent&quot;&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;    &lt;/span&gt;&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;}&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span class=&quot;indent&quot;&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;  &lt;/span&gt;&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;}, []);&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;
&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span class=&quot;indent&quot;&gt;  &lt;/span&gt;&lt;span style=&quot;--0:#D2A8FF&quot;&gt;useEffect&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;(() &lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;=&gt;&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; {&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span class=&quot;indent&quot;&gt;    &lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;if&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; (isScanning) {&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span class=&quot;indent&quot;&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;      &lt;/span&gt;&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;animationFrameId.current &lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;=&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; &lt;/span&gt;&lt;span style=&quot;--0:#D2A8FF&quot;&gt;requestAnimationFrame&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;(scanFrame);&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span class=&quot;indent&quot;&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;    &lt;/span&gt;&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;}&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span class=&quot;indent&quot;&gt;    &lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;return&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; () &lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;=&gt;&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; &lt;/span&gt;&lt;span style=&quot;--0:#D2A8FF&quot;&gt;stopCamera&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;();&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span class=&quot;indent&quot;&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;  &lt;/span&gt;&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;}, [isScanning, scanFrame, stopCamera]);&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;
&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span class=&quot;indent&quot;&gt;  &lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;return&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; { videoRef, canvasRef, isScanning, startCamera, stopCamera, error };&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;}&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;
&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span style=&quot;--0:#8B949E&quot;&gt;// ============================================================================&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span style=&quot;--0:#8B949E&quot;&gt;// Functional UI Component implementation&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span style=&quot;--0:#8B949E&quot;&gt;// ============================================================================&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;export&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; &lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;const&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; &lt;/span&gt;&lt;span style=&quot;--0:#D2A8FF&quot;&gt;EnterpriseQRScannerUI&lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;:&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; &lt;/span&gt;&lt;span style=&quot;--0:#FFA657&quot;&gt;React&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;.&lt;/span&gt;&lt;span style=&quot;--0:#FFA657&quot;&gt;FC&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; &lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;=&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; () &lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;=&gt;&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; {&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span class=&quot;indent&quot;&gt;  &lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;const&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; [&lt;/span&gt;&lt;span style=&quot;--0:#79C0FF&quot;&gt;lastScanned&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;, &lt;/span&gt;&lt;span style=&quot;--0:#79C0FF&quot;&gt;setLastScanned&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;] &lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;=&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; &lt;/span&gt;&lt;span style=&quot;--0:#D2A8FF&quot;&gt;useState&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;&amp;#x3C;&lt;/span&gt;&lt;span style=&quot;--0:#79C0FF&quot;&gt;string&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;&gt;(&lt;/span&gt;&lt;span style=&quot;--0:#A5D6FF&quot;&gt;&apos;No data detected yet.&apos;&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;);&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;
&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span class=&quot;indent&quot;&gt;  &lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;const&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; &lt;/span&gt;&lt;span style=&quot;--0:#79C0FF&quot;&gt;handleDecode&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; &lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;=&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; &lt;/span&gt;&lt;span style=&quot;--0:#D2A8FF&quot;&gt;useCallback&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;((&lt;/span&gt;&lt;span style=&quot;--0:#FFA657&quot;&gt;result&lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;:&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; &lt;/span&gt;&lt;span style=&quot;--0:#FFA657&quot;&gt;DecodedQRResult&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;) &lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;=&gt;&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; {&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span class=&quot;indent&quot;&gt;    &lt;/span&gt;&lt;span style=&quot;--0:#D2A8FF&quot;&gt;setLastScanned&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;(&lt;/span&gt;&lt;span style=&quot;--0:#A5D6FF&quot;&gt;`${&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;result&lt;/span&gt;&lt;span style=&quot;--0:#A5D6FF&quot;&gt;.&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;text&lt;/span&gt;&lt;span style=&quot;--0:#A5D6FF&quot;&gt;} (Time: ${&lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;new&lt;/span&gt;&lt;span style=&quot;--0:#A5D6FF&quot;&gt; &lt;/span&gt;&lt;span style=&quot;--0:#D2A8FF&quot;&gt;Date&lt;/span&gt;&lt;span style=&quot;--0:#A5D6FF&quot;&gt;(&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;result&lt;/span&gt;&lt;span style=&quot;--0:#A5D6FF&quot;&gt;.&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;timestamp&lt;/span&gt;&lt;span style=&quot;--0:#A5D6FF&quot;&gt;).&lt;/span&gt;&lt;span style=&quot;--0:#D2A8FF&quot;&gt;toLocaleTimeString&lt;/span&gt;&lt;span style=&quot;--0:#A5D6FF&quot;&gt;()&lt;/span&gt;&lt;span style=&quot;--0:#A5D6FF&quot;&gt;})`&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;);&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span class=&quot;indent&quot;&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;  &lt;/span&gt;&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;}, []);&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;
&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span class=&quot;indent&quot;&gt;  &lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;const&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; { &lt;/span&gt;&lt;span style=&quot;--0:#79C0FF&quot;&gt;videoRef&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;, &lt;/span&gt;&lt;span style=&quot;--0:#79C0FF&quot;&gt;canvasRef&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;, &lt;/span&gt;&lt;span style=&quot;--0:#79C0FF&quot;&gt;isScanning&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;, &lt;/span&gt;&lt;span style=&quot;--0:#79C0FF&quot;&gt;startCamera&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;, &lt;/span&gt;&lt;span style=&quot;--0:#79C0FF&quot;&gt;stopCamera&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;, &lt;/span&gt;&lt;span style=&quot;--0:#79C0FF&quot;&gt;error&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; } &lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;=&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; &lt;/span&gt;&lt;span style=&quot;--0:#D2A8FF&quot;&gt;useOptimizedQRScanner&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;(handleDecode);&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;
&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span class=&quot;indent&quot;&gt;  &lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;return&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; (&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span class=&quot;indent&quot;&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;    &lt;/span&gt;&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;&amp;#x3C;&lt;/span&gt;&lt;span style=&quot;--0:#7EE787&quot;&gt;div&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; &lt;/span&gt;&lt;span style=&quot;--0:#79C0FF&quot;&gt;style&lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;={&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;{ padding: &lt;/span&gt;&lt;span style=&quot;--0:#A5D6FF&quot;&gt;&apos;20px&apos;&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;, backgroundColor: &lt;/span&gt;&lt;span style=&quot;--0:#A5D6FF&quot;&gt;&apos;#0F172A&apos;&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;, color: &lt;/span&gt;&lt;span style=&quot;--0:#A5D6FF&quot;&gt;&apos;#FFFFFF&apos;&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;, borderRadius: &lt;/span&gt;&lt;span style=&quot;--0:#A5D6FF&quot;&gt;&apos;8px&apos;&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;, maxWidth: &lt;/span&gt;&lt;span style=&quot;--0:#A5D6FF&quot;&gt;&apos;600px&apos;&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;, margin: &lt;/span&gt;&lt;span style=&quot;--0:#A5D6FF&quot;&gt;&apos;0 auto&apos;&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; }&lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;}&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;&gt;&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span class=&quot;indent&quot;&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;      &lt;/span&gt;&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;&amp;#x3C;&lt;/span&gt;&lt;span style=&quot;--0:#7EE787&quot;&gt;h3&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; &lt;/span&gt;&lt;span style=&quot;--0:#79C0FF&quot;&gt;style&lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;={&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;{ color: &lt;/span&gt;&lt;span style=&quot;--0:#A5D6FF&quot;&gt;&apos;#FFC83B&apos;&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;, borderBottom: &lt;/span&gt;&lt;span style=&quot;--0:#A5D6FF&quot;&gt;&apos;1px solid #334155&apos;&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;, paddingBottom: &lt;/span&gt;&lt;span style=&quot;--0:#A5D6FF&quot;&gt;&apos;10px&apos;&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; }&lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;}&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;&gt;&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span class=&quot;indent&quot;&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;        &lt;/span&gt;&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;Enterprise Live Optical Scanner&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span class=&quot;indent&quot;&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;      &lt;/span&gt;&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;&amp;#x3C;/&lt;/span&gt;&lt;span style=&quot;--0:#7EE787&quot;&gt;h3&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;&gt;&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;
&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span class=&quot;indent&quot;&gt;      &lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;{&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;error &lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;&amp;#x26;&amp;#x26;&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; (&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span class=&quot;indent&quot;&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;        &lt;/span&gt;&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;&amp;#x3C;&lt;/span&gt;&lt;span style=&quot;--0:#7EE787&quot;&gt;div&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; &lt;/span&gt;&lt;span style=&quot;--0:#79C0FF&quot;&gt;style&lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;={&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;{ backgroundColor: &lt;/span&gt;&lt;span style=&quot;--0:#A5D6FF&quot;&gt;&apos;#EF4444&apos;&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;, padding: &lt;/span&gt;&lt;span style=&quot;--0:#A5D6FF&quot;&gt;&apos;10px&apos;&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;, borderRadius: &lt;/span&gt;&lt;span style=&quot;--0:#A5D6FF&quot;&gt;&apos;4px&apos;&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;, margin: &lt;/span&gt;&lt;span style=&quot;--0:#A5D6FF&quot;&gt;&apos;10px 0&apos;&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; }&lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;}&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;&gt;&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span class=&quot;indent&quot;&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;          &lt;/span&gt;&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;[ERROR]: &lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;{&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;error&lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;}&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span class=&quot;indent&quot;&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;        &lt;/span&gt;&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;&amp;#x3C;/&lt;/span&gt;&lt;span style=&quot;--0:#7EE787&quot;&gt;div&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;&gt;&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span class=&quot;indent&quot;&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;      &lt;/span&gt;&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;)&lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;}&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;
&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span class=&quot;indent&quot;&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;      &lt;/span&gt;&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;&amp;#x3C;&lt;/span&gt;&lt;span style=&quot;--0:#7EE787&quot;&gt;div&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; &lt;/span&gt;&lt;span style=&quot;--0:#79C0FF&quot;&gt;style&lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;={&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;{ position: &lt;/span&gt;&lt;span style=&quot;--0:#A5D6FF&quot;&gt;&apos;relative&apos;&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;, width: &lt;/span&gt;&lt;span style=&quot;--0:#A5D6FF&quot;&gt;&apos;100%&apos;&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;, height: &lt;/span&gt;&lt;span style=&quot;--0:#A5D6FF&quot;&gt;&apos;350px&apos;&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;, backgroundColor: &lt;/span&gt;&lt;span style=&quot;--0:#A5D6FF&quot;&gt;&apos;#000000&apos;&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;, borderRadius: &lt;/span&gt;&lt;span style=&quot;--0:#A5D6FF&quot;&gt;&apos;6px&apos;&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;, overflow: &lt;/span&gt;&lt;span style=&quot;--0:#A5D6FF&quot;&gt;&apos;hidden&apos;&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;, border: &lt;/span&gt;&lt;span style=&quot;--0:#A5D6FF&quot;&gt;&apos;2px solid #334155&apos;&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; }&lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;}&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;&gt;&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span class=&quot;indent&quot;&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;        &lt;/span&gt;&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;&amp;#x3C;&lt;/span&gt;&lt;span style=&quot;--0:#7EE787&quot;&gt;video&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; &lt;/span&gt;&lt;span style=&quot;--0:#79C0FF&quot;&gt;ref&lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;={&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;videoRef&lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;}&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; &lt;/span&gt;&lt;span style=&quot;--0:#79C0FF&quot;&gt;style&lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;={&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;{ width: &lt;/span&gt;&lt;span style=&quot;--0:#A5D6FF&quot;&gt;&apos;100%&apos;&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;, height: &lt;/span&gt;&lt;span style=&quot;--0:#A5D6FF&quot;&gt;&apos;100%&apos;&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;, objectFit: &lt;/span&gt;&lt;span style=&quot;--0:#A5D6FF&quot;&gt;&apos;cover&apos;&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; }&lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;}&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; /&gt;&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span class=&quot;indent&quot;&gt;        &lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;{&lt;/span&gt;&lt;span style=&quot;--0:#8B949E&quot;&gt;/* Hidden Canvas used exclusively for fast background pixel manipulation */&lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;}&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span class=&quot;indent&quot;&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;        &lt;/span&gt;&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;&amp;#x3C;&lt;/span&gt;&lt;span style=&quot;--0:#7EE787&quot;&gt;canvas&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; &lt;/span&gt;&lt;span style=&quot;--0:#79C0FF&quot;&gt;ref&lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;={&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;canvasRef&lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;}&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; &lt;/span&gt;&lt;span style=&quot;--0:#79C0FF&quot;&gt;style&lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;={&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;{ display: &lt;/span&gt;&lt;span style=&quot;--0:#A5D6FF&quot;&gt;&apos;none&apos;&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; }&lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;}&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; /&gt;&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;
&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span class=&quot;indent&quot;&gt;        &lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;{!&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;isScanning &lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;&amp;#x26;&amp;#x26;&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; (&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span class=&quot;indent&quot;&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;          &lt;/span&gt;&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;&amp;#x3C;&lt;/span&gt;&lt;span style=&quot;--0:#7EE787&quot;&gt;div&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; &lt;/span&gt;&lt;span style=&quot;--0:#79C0FF&quot;&gt;style&lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;={&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;{ position: &lt;/span&gt;&lt;span style=&quot;--0:#A5D6FF&quot;&gt;&apos;absolute&apos;&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;, top: &lt;/span&gt;&lt;span style=&quot;--0:#A5D6FF&quot;&gt;&apos;50%&apos;&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;, left: &lt;/span&gt;&lt;span style=&quot;--0:#A5D6FF&quot;&gt;&apos;50%&apos;&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;, transform: &lt;/span&gt;&lt;span style=&quot;--0:#A5D6FF&quot;&gt;&apos;translate(-50%, -50%)&apos;&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;, color: &lt;/span&gt;&lt;span style=&quot;--0:#A5D6FF&quot;&gt;&apos;#94A3B8&apos;&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; }&lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;}&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;&gt;&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span class=&quot;indent&quot;&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;            &lt;/span&gt;&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;Camera Stream Inactive&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span class=&quot;indent&quot;&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;          &lt;/span&gt;&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;&amp;#x3C;/&lt;/span&gt;&lt;span style=&quot;--0:#7EE787&quot;&gt;div&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;&gt;&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span class=&quot;indent&quot;&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;        &lt;/span&gt;&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;)&lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;}&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span class=&quot;indent&quot;&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;      &lt;/span&gt;&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;&amp;#x3C;/&lt;/span&gt;&lt;span style=&quot;--0:#7EE787&quot;&gt;div&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;&gt;&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;
&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span class=&quot;indent&quot;&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;      &lt;/span&gt;&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;&amp;#x3C;&lt;/span&gt;&lt;span style=&quot;--0:#7EE787&quot;&gt;div&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; &lt;/span&gt;&lt;span style=&quot;--0:#79C0FF&quot;&gt;style&lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;={&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;{ marginTop: &lt;/span&gt;&lt;span style=&quot;--0:#A5D6FF&quot;&gt;&apos;15px&apos;&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;, display: &lt;/span&gt;&lt;span style=&quot;--0:#A5D6FF&quot;&gt;&apos;flex&apos;&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;, gap: &lt;/span&gt;&lt;span style=&quot;--0:#A5D6FF&quot;&gt;&apos;10px&apos;&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;, justifyContent: &lt;/span&gt;&lt;span style=&quot;--0:#A5D6FF&quot;&gt;&apos;space-between&apos;&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;, alignItems: &lt;/span&gt;&lt;span style=&quot;--0:#A5D6FF&quot;&gt;&apos;center&apos;&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; }&lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;}&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;&gt;&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span class=&quot;indent&quot;&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;        &lt;/span&gt;&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;&amp;#x3C;&lt;/span&gt;&lt;span style=&quot;--0:#7EE787&quot;&gt;div&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;&gt;&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span class=&quot;indent&quot;&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;          &lt;/span&gt;&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;&amp;#x3C;&lt;/span&gt;&lt;span style=&quot;--0:#7EE787&quot;&gt;button&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span class=&quot;indent&quot;&gt;            &lt;/span&gt;&lt;span style=&quot;--0:#79C0FF&quot;&gt;onClick&lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;={&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;isScanning &lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;?&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; stopCamera &lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;:&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; startCamera&lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;}&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span class=&quot;indent&quot;&gt;            &lt;/span&gt;&lt;span style=&quot;--0:#79C0FF&quot;&gt;style&lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;={&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;{&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span class=&quot;indent&quot;&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;              &lt;/span&gt;&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;padding: &lt;/span&gt;&lt;span style=&quot;--0:#A5D6FF&quot;&gt;&apos;10px 20px&apos;&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;,&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span class=&quot;indent&quot;&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;              &lt;/span&gt;&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;backgroundColor: isScanning &lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;?&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; &lt;/span&gt;&lt;span style=&quot;--0:#A5D6FF&quot;&gt;&apos;#EF4444&apos;&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; &lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;:&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; &lt;/span&gt;&lt;span style=&quot;--0:#A5D6FF&quot;&gt;&apos;#10B981&apos;&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;,&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span class=&quot;indent&quot;&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;              &lt;/span&gt;&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;color: &lt;/span&gt;&lt;span style=&quot;--0:#A5D6FF&quot;&gt;&apos;#FFFFFF&apos;&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;,&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span class=&quot;indent&quot;&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;              &lt;/span&gt;&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;border: &lt;/span&gt;&lt;span style=&quot;--0:#A5D6FF&quot;&gt;&apos;none&apos;&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;,&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span class=&quot;indent&quot;&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;              &lt;/span&gt;&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;borderRadius: &lt;/span&gt;&lt;span style=&quot;--0:#A5D6FF&quot;&gt;&apos;4px&apos;&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;,&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span class=&quot;indent&quot;&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;              &lt;/span&gt;&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;fontWeight: &lt;/span&gt;&lt;span style=&quot;--0:#A5D6FF&quot;&gt;&apos;bold&apos;&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;,&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span class=&quot;indent&quot;&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;              &lt;/span&gt;&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;cursor: &lt;/span&gt;&lt;span style=&quot;--0:#A5D6FF&quot;&gt;&apos;pointer&apos;&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span class=&quot;indent&quot;&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;            &lt;/span&gt;&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;}&lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;}&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span class=&quot;indent&quot;&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;          &lt;/span&gt;&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;&gt;&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span class=&quot;indent&quot;&gt;            &lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;{&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;isScanning &lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;?&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; &lt;/span&gt;&lt;span style=&quot;--0:#A5D6FF&quot;&gt;&apos;Terminate Scanner&apos;&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; &lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;:&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; &lt;/span&gt;&lt;span style=&quot;--0:#A5D6FF&quot;&gt;&apos;Initialize Hardware Scanner&apos;&lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;}&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span class=&quot;indent&quot;&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;          &lt;/span&gt;&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;&amp;#x3C;/&lt;/span&gt;&lt;span style=&quot;--0:#7EE787&quot;&gt;button&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;&gt;&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span class=&quot;indent&quot;&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;        &lt;/span&gt;&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;&amp;#x3C;/&lt;/span&gt;&lt;span style=&quot;--0:#7EE787&quot;&gt;div&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;&gt;&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span class=&quot;indent&quot;&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;        &lt;/span&gt;&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;&amp;#x3C;&lt;/span&gt;&lt;span style=&quot;--0:#7EE787&quot;&gt;div&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; &lt;/span&gt;&lt;span style=&quot;--0:#79C0FF&quot;&gt;style&lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;={&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;{ fontSize: &lt;/span&gt;&lt;span style=&quot;--0:#A5D6FF&quot;&gt;&apos;13px&apos;&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;, color: &lt;/span&gt;&lt;span style=&quot;--0:#A5D6FF&quot;&gt;&apos;#00E5FF&apos;&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; }&lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;}&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;&gt;&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span class=&quot;indent&quot;&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;          &lt;/span&gt;&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;Status: &lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;{&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;isScanning &lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;?&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; &lt;/span&gt;&lt;span style=&quot;--0:#A5D6FF&quot;&gt;&apos;ACTIVE (60 FPS Stream)&apos;&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; &lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;:&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; &lt;/span&gt;&lt;span style=&quot;--0:#A5D6FF&quot;&gt;&apos;STANDBY&apos;&lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;}&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span class=&quot;indent&quot;&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;        &lt;/span&gt;&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;&amp;#x3C;/&lt;/span&gt;&lt;span style=&quot;--0:#7EE787&quot;&gt;div&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;&gt;&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span class=&quot;indent&quot;&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;      &lt;/span&gt;&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;&amp;#x3C;/&lt;/span&gt;&lt;span style=&quot;--0:#7EE787&quot;&gt;div&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;&gt;&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;
&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span class=&quot;indent&quot;&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;      &lt;/span&gt;&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;&amp;#x3C;&lt;/span&gt;&lt;span style=&quot;--0:#7EE787&quot;&gt;div&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; &lt;/span&gt;&lt;span style=&quot;--0:#79C0FF&quot;&gt;style&lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;={&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;{ marginTop: &lt;/span&gt;&lt;span style=&quot;--0:#A5D6FF&quot;&gt;&apos;15px&apos;&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;, padding: &lt;/span&gt;&lt;span style=&quot;--0:#A5D6FF&quot;&gt;&apos;10px&apos;&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;, backgroundColor: &lt;/span&gt;&lt;span style=&quot;--0:#A5D6FF&quot;&gt;&apos;#1E293B&apos;&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;, borderRadius: &lt;/span&gt;&lt;span style=&quot;--0:#A5D6FF&quot;&gt;&apos;4px&apos;&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;, fontSize: &lt;/span&gt;&lt;span style=&quot;--0:#A5D6FF&quot;&gt;&apos;14px&apos;&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;, wordBreak: &lt;/span&gt;&lt;span style=&quot;--0:#A5D6FF&quot;&gt;&apos;break-all&apos;&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; }&lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;}&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;&gt;&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span class=&quot;indent&quot;&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;        &lt;/span&gt;&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;&amp;#x3C;&lt;/span&gt;&lt;span style=&quot;--0:#7EE787&quot;&gt;strong&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; &lt;/span&gt;&lt;span style=&quot;--0:#79C0FF&quot;&gt;style&lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;={&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;{ color: &lt;/span&gt;&lt;span style=&quot;--0:#A5D6FF&quot;&gt;&apos;#FFC83B&apos;&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; }&lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;}&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;&gt;Latest Payload: &amp;#x3C;/&lt;/span&gt;&lt;span style=&quot;--0:#7EE787&quot;&gt;strong&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;&gt; &lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;{&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;lastScanned&lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;}&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span class=&quot;indent&quot;&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;      &lt;/span&gt;&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;&amp;#x3C;/&lt;/span&gt;&lt;span style=&quot;--0:#7EE787&quot;&gt;div&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;&gt;&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span class=&quot;indent&quot;&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;    &lt;/span&gt;&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;&amp;#x3C;/&lt;/span&gt;&lt;span style=&quot;--0:#7EE787&quot;&gt;div&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;&gt;&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span class=&quot;indent&quot;&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;  &lt;/span&gt;&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;);&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;};&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;/code&gt;&lt;/pre&gt;&lt;div class=&quot;copy&quot;&gt;&lt;div aria-live=&quot;polite&quot;&gt;&lt;/div&gt;&lt;button title=&quot;Copy to clipboard&quot; data-copied=&quot;Copied!&quot; data-code=&quot;// Production-grade React Custom Hook &amp;#x26; Component for Non-Blocking QR Scanningimport React, { useEffect, useRef, useState, useCallback } from &amp;#x27;react&amp;#x27;;/** * Interface for the Decoded QR Result payload. */export interface DecodedQRResult {  text: string;  timestamp: number;}/** * A specialized custom hook to manage live camera streaming and background Canvas frame extraction. */export function useOptimizedQRScanner(onDecode: (result: DecodedQRResult) =&gt; void) {  const videoRef = useRef&lt;HTMLVideoElement | null&gt;(null);  const canvasRef = useRef&lt;HTMLCanvasElement | null&gt;(null);  const [isScanning, setIsScanning] = useState&lt;boolean&gt;(false);  const [error, setError] = useState&lt;string | null&gt;(null);  const animationFrameId = useRef&lt;number | null&gt;(null);  // Stop camera stream safely to prevent memory leaks and hardware locks  const stopCamera = useCallback(() =&gt; {    if (videoRef.current &amp;#x26;&amp;#x26; videoRef.current.srcObject) {      const stream = videoRef.current.srcObject as MediaStream;      stream.getTracks().forEach((track) =&gt; track.stop());      videoRef.current.srcObject = null;    }    if (animationFrameId.current) {      cancelAnimationFrame(animationFrameId.current);    }    setIsScanning(false);  }, []);  // Frame extraction loop running at controlled intervals to save battery  const scanFrame = useCallback(() =&gt; {    if (!videoRef.current || !canvasRef.current || !isScanning) return;    const video = videoRef.current;    const canvas = canvasRef.current;    const context = canvas.getContext(&amp;#x27;2d&amp;#x27;, { willReadFrequently: true });    if (video.readyState === video.HAVE_ENOUGH_DATA &amp;#x26;&amp;#x26; context) {      canvas.width = video.videoWidth;      canvas.height = video.videoHeight;      // Draw video frame to off-screen canvas      context.drawImage(video, 0, 0, canvas.width, canvas.height);      try {        // Extract ImageData for background processing        const imageData = context.getImageData(0, 0, canvas.width, canvas.height);        // In a true enterprise setup, send &amp;#x60;imageData.data.buffer&amp;#x60; to a Web Worker / WebAssembly decoder        // Example simulation of detection logic:        if (imageData.width &gt; 0) {          // Simulated non-blocking detection check          // When WASM worker returns success, trigger callback:          // onDecode({ text: &amp;#x22;https://blog.rafeuddaraj.me&amp;#x22;, timestamp: Date.now() });        }      } catch (err: any) {        console.warn(&amp;#x27;[WARN] Frame extraction temporarily failed:&amp;#x27;, err.message);      }    }    // Schedule next frame check using requestAnimationFrame instead of setInterval    animationFrameId.current = requestAnimationFrame(scanFrame);  }, [isScanning, onDecode]);  // Initialize Hardware Camera Access  const startCamera = useCallback(async () =&gt; {    try {      setError(null);      const stream = await navigator.mediaDevices.getUserMedia({        video: {          facingMode: &amp;#x27;environment&amp;#x27;, // Request back camera for physical scanning          width: { ideal: 1280 },          height: { ideal: 720 }        }      });      if (videoRef.current) {        videoRef.current.srcObject = stream;        videoRef.current.setAttribute(&amp;#x27;playsinline&amp;#x27;, &amp;#x27;true&amp;#x27;); // Required for iOS Safari        await videoRef.current.play();        setIsScanning(true);      }    } catch (err: any) {      setError(&amp;#x60;Camera access denied or unavailable: ${err.message}&amp;#x60;);      setIsScanning(false);    }  }, []);  useEffect(() =&gt; {    if (isScanning) {      animationFrameId.current = requestAnimationFrame(scanFrame);    }    return () =&gt; stopCamera();  }, [isScanning, scanFrame, stopCamera]);  return { videoRef, canvasRef, isScanning, startCamera, stopCamera, error };}// ============================================================================// Functional UI Component implementation// ============================================================================export const EnterpriseQRScannerUI: React.FC = () =&gt; {  const [lastScanned, setLastScanned] = useState&lt;string&gt;(&amp;#x27;No data detected yet.&amp;#x27;);  const handleDecode = useCallback((result: DecodedQRResult) =&gt; {    setLastScanned(&amp;#x60;${result.text} (Time: ${new Date(result.timestamp).toLocaleTimeString()})&amp;#x60;);  }, []);  const { videoRef, canvasRef, isScanning, startCamera, stopCamera, error } = useOptimizedQRScanner(handleDecode);  return (    &lt;div style={{ padding: &amp;#x27;20px&amp;#x27;, backgroundColor: &amp;#x27;#0F172A&amp;#x27;, color: &amp;#x27;#FFFFFF&amp;#x27;, borderRadius: &amp;#x27;8px&amp;#x27;, maxWidth: &amp;#x27;600px&amp;#x27;, margin: &amp;#x27;0 auto&amp;#x27; }}&gt;      &lt;h3 style={{ color: &amp;#x27;#FFC83B&amp;#x27;, borderBottom: &amp;#x27;1px solid #334155&amp;#x27;, paddingBottom: &amp;#x27;10px&amp;#x27; }}&gt;        Enterprise Live Optical Scanner      &lt;/h3&gt;      {error &amp;#x26;&amp;#x26; (        &lt;div style={{ backgroundColor: &amp;#x27;#EF4444&amp;#x27;, padding: &amp;#x27;10px&amp;#x27;, borderRadius: &amp;#x27;4px&amp;#x27;, margin: &amp;#x27;10px 0&amp;#x27; }}&gt;          [ERROR]: {error}        &lt;/div&gt;      )}      &lt;div style={{ position: &amp;#x27;relative&amp;#x27;, width: &amp;#x27;100%&amp;#x27;, height: &amp;#x27;350px&amp;#x27;, backgroundColor: &amp;#x27;#000000&amp;#x27;, borderRadius: &amp;#x27;6px&amp;#x27;, overflow: &amp;#x27;hidden&amp;#x27;, border: &amp;#x27;2px solid #334155&amp;#x27; }}&gt;        &lt;video ref={videoRef} style={{ width: &amp;#x27;100%&amp;#x27;, height: &amp;#x27;100%&amp;#x27;, objectFit: &amp;#x27;cover&amp;#x27; }} /&gt;        {/* Hidden Canvas used exclusively for fast background pixel manipulation */}        &lt;canvas ref={canvasRef} style={{ display: &amp;#x27;none&amp;#x27; }} /&gt;        {!isScanning &amp;#x26;&amp;#x26; (          &lt;div style={{ position: &amp;#x27;absolute&amp;#x27;, top: &amp;#x27;50%&amp;#x27;, left: &amp;#x27;50%&amp;#x27;, transform: &amp;#x27;translate(-50%, -50%)&amp;#x27;, color: &amp;#x27;#94A3B8&amp;#x27; }}&gt;            Camera Stream Inactive          &lt;/div&gt;        )}      &lt;/div&gt;      &lt;div style={{ marginTop: &amp;#x27;15px&amp;#x27;, display: &amp;#x27;flex&amp;#x27;, gap: &amp;#x27;10px&amp;#x27;, justifyContent: &amp;#x27;space-between&amp;#x27;, alignItems: &amp;#x27;center&amp;#x27; }}&gt;        &lt;div&gt;          &lt;button            onClick={isScanning ? stopCamera : startCamera}            style={{              padding: &amp;#x27;10px 20px&amp;#x27;,              backgroundColor: isScanning ? &amp;#x27;#EF4444&amp;#x27; : &amp;#x27;#10B981&amp;#x27;,              color: &amp;#x27;#FFFFFF&amp;#x27;,              border: &amp;#x27;none&amp;#x27;,              borderRadius: &amp;#x27;4px&amp;#x27;,              fontWeight: &amp;#x27;bold&amp;#x27;,              cursor: &amp;#x27;pointer&amp;#x27;            }}          &gt;            {isScanning ? &amp;#x27;Terminate Scanner&amp;#x27; : &amp;#x27;Initialize Hardware Scanner&amp;#x27;}          &lt;/button&gt;        &lt;/div&gt;        &lt;div style={{ fontSize: &amp;#x27;13px&amp;#x27;, color: &amp;#x27;#00E5FF&amp;#x27; }}&gt;          Status: {isScanning ? &amp;#x27;ACTIVE (60 FPS Stream)&amp;#x27; : &amp;#x27;STANDBY&amp;#x27;}        &lt;/div&gt;      &lt;/div&gt;      &lt;div style={{ marginTop: &amp;#x27;15px&amp;#x27;, padding: &amp;#x27;10px&amp;#x27;, backgroundColor: &amp;#x27;#1E293B&amp;#x27;, borderRadius: &amp;#x27;4px&amp;#x27;, fontSize: &amp;#x27;14px&amp;#x27;, wordBreak: &amp;#x27;break-all&amp;#x27; }}&gt;        &lt;strong style={{ color: &amp;#x27;#FFC83B&amp;#x27; }}&gt;Latest Payload: &lt;/strong&gt; {lastScanned}      &lt;/div&gt;    &lt;/div&gt;  );};&quot;&gt;&lt;div&gt;&lt;/div&gt;&lt;/button&gt;&lt;/div&gt;&lt;/figure&gt;&lt;/div&gt;
&lt;div class=&quot;callout&quot; role=&quot;note&quot; data-type=&quot;tip&quot;&gt;
&lt;p class=&quot;callout-title&quot;&gt;Memory Leak Prevention&lt;/p&gt;
&lt;p&gt;When creating live camera interfaces in React, remember to turn off video stream tracks and terminate background Web Workers inside your clean-up effects when components unmount. Neglecting this can freeze camera hardware, lock up browser memory, and quickly drain mobile batteries.&lt;/p&gt;
&lt;/div&gt;
&lt;hr&gt;
&lt;h2 id=&quot;step-6-production-deployment-checklist-and-security-best-practices&quot;&gt;Step 6: Production Deployment Checklist and Security Best Practices&lt;/h2&gt;
&lt;p&gt;Before rolling out a QR code infrastructure in your next production app, review this architectural checklist to make sure your system remains secure, fast, and highly reliable:&lt;/p&gt;
&lt;section class=&quot;table-wrap&quot; tabindex=&quot;0&quot; aria-label=&quot;Table 2&quot;&gt;












































&lt;table&gt;&lt;thead&gt;&lt;tr&gt;&lt;th&gt;Architectural Domain&lt;/th&gt;&lt;th&gt;Production Best Practice&lt;/th&gt;&lt;th&gt;Risk &amp;#x26; Mitigation Strategy&lt;/th&gt;&lt;/tr&gt;&lt;/thead&gt;&lt;tbody&gt;&lt;tr&gt;&lt;td&gt;&lt;strong&gt;1. Error Correction Choice&lt;/strong&gt;&lt;/td&gt;&lt;td&gt;Stick to &lt;code&gt;Level M&lt;/code&gt; (15%) for clean digital URLs. Reserve &lt;code&gt;Level H&lt;/code&gt; (30%) exclusively for branded codes with center logos or warehouse labels.&lt;/td&gt;&lt;td&gt;Forcing Level H adds significant data overhead, making the code grid denser and harder for budget cameras to resolve quickly.&lt;/td&gt;&lt;/tr&gt;&lt;tr&gt;&lt;td&gt;&lt;strong&gt;2. Payload &amp;#x26; Version Scaling&lt;/strong&gt;&lt;/td&gt;&lt;td&gt;Never embed raw, bulky JSON objects inside a code. Instead, compress identifiers down to a minimal Short URL or a secure UUID.&lt;/td&gt;&lt;td&gt;Massive payloads push the code into higher versions, creating tiny, compressed modules that struggle to scan on low-end lenses.&lt;/td&gt;&lt;/tr&gt;&lt;tr&gt;&lt;td&gt;&lt;strong&gt;3. Optical Contrast Ratio&lt;/strong&gt;&lt;/td&gt;&lt;td&gt;Maintain high contrast by placing dark modules (e.g., dark slate or navy) on a clean, bright background. Avoid inverted color styles.&lt;/td&gt;&lt;td&gt;Inverting codes (white modules on a black background) breaks compatibility with standard commercial laser scanners.&lt;/td&gt;&lt;/tr&gt;&lt;tr&gt;&lt;td&gt;&lt;strong&gt;4. Quiet Zone Verification&lt;/strong&gt;&lt;/td&gt;&lt;td&gt;Enforce a clean 4-module wide margin on all sides of the code. Keep text and design borders outside of this boundary.&lt;/td&gt;&lt;td&gt;Clipping the Quiet Zone prevents scanner edge detection filters from isolating the grid, causing parsing to fail.&lt;/td&gt;&lt;/tr&gt;&lt;tr&gt;&lt;td&gt;&lt;strong&gt;5. Static vs Dynamic Routing&lt;/strong&gt;&lt;/td&gt;&lt;td&gt;Use Dynamic QR Codes for commercial applications. Embed a redirect link that resolves backend records dynamically.&lt;/td&gt;&lt;td&gt;Static codes embed data permanently. If a database schema changes or a link breaks after printing, millions of labels become landfill.&lt;/td&gt;&lt;/tr&gt;&lt;tr&gt;&lt;td&gt;&lt;strong&gt;6. Security Optimization&lt;/strong&gt;&lt;/td&gt;&lt;td&gt;Treat scanned payloads as untrusted user input. Sanitize all incoming strings before rendering them or saving them to a database.&lt;/td&gt;&lt;td&gt;Attackers can embed malicious XSS scripts or lookalike phishing links inside codes, attempting QRLjacking or session takeovers.&lt;/td&gt;&lt;/tr&gt;&lt;tr&gt;&lt;td&gt;Understanding these underlying mechanisms and optimization techniques helps software architects build efficient, robust optical data pipelines for enterprise platforms. Keep this handbook handy as an ongoing reference for your future engineering projects.&lt;/td&gt;&lt;td&gt;&lt;/td&gt;&lt;td&gt;&lt;/td&gt;&lt;/tr&gt;&lt;/tbody&gt;&lt;/table&gt;&lt;/section&gt;</content:encoded><category>System Design</category><category>QR Code</category><category>System Architecture</category><category>Node.js</category><category>React</category><category>TypeScript</category><category>WebAssembly</category><category>Optical Scanning</category><category>Software Engineering</category><category>Algorithms</category><category>Backend Development</category></item><item><title>How the Transactional Outbox Pattern and Idempotency Really Work Under the Hood in Distributed Systems</title><link>https://www.rafeuddaraj.me/blog/distributed-systems-transactional-outbox-idempotency-deep-dive/</link><guid isPermaLink="true">https://www.rafeuddaraj.me/blog/distributed-systems-transactional-outbox-idempotency-deep-dive/</guid><description>A practical engineering guide to handling distributed transactions and data consistency when moving from monoliths to microservices. Learn the mechanics of dual-write anti-patterns, Change Data Capture, Write-Ahead Logging, and idempotent consumers.</description><pubDate>Thu, 16 Jul 2026 21:26:02 GMT</pubDate><content:encoded>&lt;p&gt;When we transition from a monolithic architecture to microservices, the biggest and most intimidating challenge we face is handling distributed transactions and data consistency. In a monolithic application, we have a single relational database where we can easily use ACID transactions to guarantee atomicity. But once we move to a microservices architecture, every service has its own dedicated database and relies on the network or a message broker to communicate with other services. This creates a complex architectural puzzle that can silently corrupt your production database if you do not solve it with the right system design.&lt;/p&gt;
&lt;p&gt;Today, we will talk directly about why standard retry mechanisms or try-catch blocks fail in large-scale distributed systems. We will explore how you can use the Transactional Outbox Pattern along with idempotent consumer mechanisms to design a production-grade, fault-tolerant system. Let us analyze this topic from the ground up, right down to the low-level engine mechanics.&lt;/p&gt;
&lt;h2 id=&quot;1-the-core-mystery-and-why-it-matters&quot;&gt;1. The Core Mystery and Why It Matters&lt;/h2&gt;
&lt;p&gt;When a service updates its local database and immediately publishes an event to an external message broker like Apache Kafka or RabbitMQ, we call that pattern a dual-write. On the surface, this looks like a very straightforward and simple piece of logic, but from a system architecture perspective, it is a dangerous anti-pattern. When you try to execute write operations across two completely different and independent storage engines inside the same code block, network latency and partial failures will quickly push your system into an inconsistent state.&lt;/p&gt;
&lt;p&gt;Imagine you are building the order service for an e-commerce platform. When a user places an order, your code first saves the order details in the database and then sends an &lt;code&gt;OrderCreated&lt;/code&gt; event to the Kafka broker so the inventory service can reduce stock and the payment service can process the charge. Now think about what happens if your database transaction succeeds and the data is saved in the orders table, but right at that exact millisecond, the Kafka broker goes down or your network connection drops. As a result, the event is never published to Kafka. Your order service assumes the order was successful, but the inventory and payment services know nothing about it. This exact condition is called silent data corruption, and it completely destroys your core business logic.&lt;/p&gt;
&lt;p&gt;Many experienced engineers try to solve this problem by relying on standard try-catch blocks or retry loops. They assume that if sending the event to Kafka fails, the code can simply retry a few times or throw an exception to roll back the database transaction. In a distributed system, this assumption is completely flawed. If your message reaches the Kafka broker successfully, but a network partition occurs while the acknowledgment is traveling back to your application, your application will think the message never arrived. If you trigger a retry, you will send the exact same message to Kafka twice. If you decide to roll back the database transaction instead, the message remains in Kafka while the database record disappears. The only way out of this logical trap is to leverage the atomic power of your database.&lt;/p&gt;
&lt;h2 id=&quot;2-the-foundational-mental-model-and-analogy&quot;&gt;2. The Foundational Mental Model and Analogy&lt;/h2&gt;
&lt;p&gt;The foundational concept behind the Transactional Outbox Pattern is brilliant and straightforward. We completely stop trying to send data to an external message broker in real time. Instead, we rely on the atomic ACID properties of our local database. When a business transaction occurs, we save the event payload inside a special table within the exact same database transaction as our primary business data. This special table is called the &lt;code&gt;outbox_messages&lt;/code&gt; table. Because both tables reside within the same database and share a single transaction, the database engine guarantees that either both writes succeed simultaneously or neither of them does.&lt;/p&gt;
&lt;p&gt;To make this concept crystal clear, we can look at a real-world banking analogy. Imagine you are standing at a bank counter, and you want to transfer money to an account at a different bank. If the bank teller tries to connect directly to the other bank&apos;s servers in real time while you stand there, any network slowdown will freeze or ruin your transaction. Instead, the teller does something much smarter: they record the withdrawal in their local ledger to deduct money from your account, and in that exact same ledger, they write an entry in an outbox section noting that a check must be mailed to the other bank. The teller completes this entire task with a single stroke of a pen. Later, background staff collect those notes from the outbox section and safely mail the checks when the timing is right.&lt;/p&gt;
&lt;p&gt;In distributed systems engineering, we call this mental model Eventual Consistency. We let go of the unrealistic expectation of strict real-time synchronization and design the system so that all data across different services synchronizes within a few milliseconds or seconds. Using real-time distributed locking in high-throughput architectures is impossible, which makes Eventual Consistency the only practical solution for production systems.&lt;/p&gt;
&lt;h2 id=&quot;3-under-the-hood-architecture-the-core-deep-dive&quot;&gt;3. Under-The-Hood Architecture (The Core Deep Dive)&lt;/h2&gt;
&lt;p&gt;Now let us examine how this entire process works under the hood at the memory and disk level of the engine. When you start a transaction in a relational database like PostgreSQL or MySQL, the database engine does not touch your main data files directly. Instead, it records your change instructions in an optimized, sequential disk file called the Write-Ahead Log, or WAL. When you insert data into both the &lt;code&gt;orders&lt;/code&gt; table and the &lt;code&gt;outbox_messages&lt;/code&gt; table within the same transaction, the database engine writes those two operations into memory buffers as part of a single WAL entry and later flushes them to disk.&lt;/p&gt;
&lt;p&gt;When you issue the &lt;code&gt;COMMIT&lt;/code&gt; command, the database engine ensures that the changes for both tables are written atomically to the WAL file. If the server crashes or loses power right during the disk write, the database engine will read the WAL file during restart and roll back the entire incomplete transaction. This guarantees 100% synchronization between your business data and your outbox events. There is zero external network risk here because the entire workflow happens inside the internal storage engine of your database.&lt;/p&gt;
&lt;figure&gt;&lt;img src=&quot;https://raw.githubusercontent.com/rafeuddaraj/rafes-blog-assets/refs/heads/distributed-systems-transactional-outbox-idempotency-deep-dive/assets/transactional-outbox-architecture.svg&quot; alt=&quot;Transactional Outbox Architecture Workflow&quot; loading=&quot;lazy&quot; decoding=&quot;async&quot; width=&quot;1000&quot; height=&quot;520&quot;&gt;&lt;figcaption&gt;Transactional Outbox Architecture Workflow&lt;/figcaption&gt;&lt;/figure&gt;
&lt;p&gt;While the outbox pattern gives us strict consistency at the database level, we must pay careful attention to message delivery guarantees when transferring data from the message broker to consumer services. Distributed systems generally offer three types of delivery guarantees: at-most-once, at-least-once, and exactly-once. The outbox pattern provides an at-least-once delivery guarantee by default. This means your event will reach the consumer service at least one time, but network retries or failure recoveries might cause the exact same event to arrive multiple times.&lt;/p&gt;
&lt;p&gt;Many developers assume that modern brokers like Kafka provide end-to-end exactly-once delivery, but in the low-level reality of distributed systems, true end-to-end exactly-once delivery is practically impossible. A broker might prevent duplicates within its own internal layers, but network latency can easily cause your background poller or consumer service to process the same message twice. Therefore, in reliable production architectures, we always pair at-least-once delivery guarantees with idempotency logic on the consumer side to achieve exactly-once processing.&lt;/p&gt;
&lt;p&gt;In the architectural diagram shown above, you can see how our primary application updates both the business table and the outbox table inside a single database transaction. Afterwards, a background process or a Change Data Capture engine reads the data from that outbox table and pushes it to the message broker. Finally, the consumer service receives the event and executes an idempotency check before processing the business logic.&lt;/p&gt;
&lt;h2 id=&quot;4-step-by-step-execution-trace-and-code-mechanics&quot;&gt;4. Step-by-Step Execution Trace and Code Mechanics&lt;/h2&gt;
&lt;p&gt;To design a production-ready architecture, we first need to understand the database schema and backend code mechanics. Let us walk through the execution trace step by step.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Step 1: The Blueprint for SQL Schema Design&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;We need a specific database schema to store our outbox messages reliably. This table must track the event payload, processing status, and retry attempts. At the same time, we need to create an idempotency table in the consumer service database to prevent duplicate message processing.&lt;/p&gt;
&lt;div class=&quot;expressive-code&quot;&gt;&lt;style&gt;.expressive-code{font-family:var(--ec-uiFontFml);font-size:var(--ec-uiFontSize);font-weight:var(--ec-uiFontWg);line-height:var(--ec-uiLineHt);text-size-adjust:none;-webkit-text-size-adjust:none}.expressive-code *:not(:is(svg, svg *)){all:revert;box-sizing:border-box}.expressive-code pre{display:flex;margin:0;padding:0;border:var(--ec-brdWd) solid var(--ec-brdCol);border-radius:calc(var(--ec-brdRad) + var(--ec-brdWd));background:var(--ec-codeBg)}.expressive-code pre:focus-visible{outline:3px solid var(--ec-focusBrd);outline-offset:-3px}.expressive-code pre &gt; code{all:unset;display:block;flex:1 0 100%;padding:var(--ec-codePadBlk) 0;color:var(--ec-codeFg);font-family:var(--ec-codeFontFml);font-size:var(--ec-codeFontSize);font-weight:var(--ec-codeFontWg);line-height:var(--ec-codeLineHt)}.expressive-code pre{overflow-x:auto}.expressive-code pre.wrap .ec-line .code{white-space:pre-wrap;overflow-wrap:break-word;min-width:min(20ch, var(--ecMaxLine, 20ch))}.expressive-code pre.wrap .ec-line .code span.indent{white-space:pre}.expressive-code pre::-webkit-scrollbar,.expressive-code pre::-webkit-scrollbar-track{background-color:inherit;border-radius:calc(var(--ec-brdRad) + var(--ec-brdWd));border-top-left-radius:0;border-top-right-radius:0}.expressive-code pre::-webkit-scrollbar-thumb{background-color:var(--ec-sbThumbCol);border:4px solid transparent;background-clip:content-box;border-radius:10px}.expressive-code pre::-webkit-scrollbar-thumb:hover{background-color:var(--ec-sbThumbHoverCol)}.expressive-code pre::-webkit-scrollbar-corner{background:transparent}.expressive-code .ec-line{direction:ltr;unicode-bidi:isolate;display:grid;grid-template-areas:&apos;gutter code&apos;;grid-template-columns:auto 1fr;position:relative}.expressive-code .ec-line .gutter{grid-area:gutter;color:var(--ec-gtrFg)}.expressive-code .ec-line .gutter &gt; *{pointer-events:none;user-select:none;-webkit-user-select:none}.expressive-code .ec-line .gutter ~ .code{--ecLineBrdCol:var(--ec-gtrBrdCol)}.expressive-code .ec-line.highlight .gutter{color:var(--ec-gtrHlFg)}.expressive-code .ec-line .code{grid-area:code;position:relative;box-sizing:content-box;padding-inline-start:calc(var(--ecIndent, 0ch) + var(--ec-codePadInl) - var(--ecGtrBrdWd));padding-inline-end:var(--ec-codePadInl);text-indent:calc(var(--ecIndent, 0ch) * -1)}.expressive-code .ec-line .code::before,.expressive-code .ec-line .code::after,.expressive-code .ec-line .code :where(*){text-indent:0}.expressive-code .ec-line .code{--ecGtrBrdWd:var(--ec-gtrBrdWd);border-inline-start:var(--ecGtrBrdWd) solid var(--ecLineBrdCol, transparent)}.expressive-code .sr-only{position:absolute;width:1px;height:1px;padding:0;margin:-1px;overflow:hidden;clip:rect(0, 0, 0, 0);white-space:nowrap;border-width:0}.expressive-code .ec-line.mark{--tmLineBgCol:var(--ec-tm-markBg)}.expressive-code .ec-line.mark .code{--ecLineBrdCol:var(--ec-tm-markBrdCol)}.expressive-code .ec-line.ins{--tmLineBgCol:var(--ec-tm-insBg);--tmLabel:var(--ec-tm-insDiffIndContent)}.expressive-code .ec-line.ins .code{--ecLineBrdCol:var(--ec-tm-insBrdCol)}.expressive-code .ec-line.ins .code::before{color:var(--ec-tm-insDiffIndCol)}.expressive-code .ec-line.del{--tmLineBgCol:var(--ec-tm-delBg);--tmLabel:var(--ec-tm-delDiffIndContent)}.expressive-code .ec-line.del .code{--ecLineBrdCol:var(--ec-tm-delBrdCol)}.expressive-code .ec-line.del .code::before{color:var(--ec-tm-delDiffIndCol)}.expressive-code .ec-line.mark,.expressive-code .ec-line.ins,.expressive-code .ec-line.del{background:var(--tmLineBgCol)}.expressive-code .ec-line.mark .code,.expressive-code .ec-line.ins .code,.expressive-code .ec-line.del .code{--ecGtrBrdWd:var(--ec-tm-lineMarkerAccentWd)}.expressive-code .ec-line.mark .code::before,.expressive-code .ec-line.ins .code::before,.expressive-code .ec-line.del .code::before{display:block;position:absolute;left:0;box-sizing:border-box;content:var(--tmLabel, &apos; &apos;);padding-inline-start:var(--ec-tm-lineDiffIndMargLeft);text-align:center;white-space:pre}.expressive-code .ec-line.mark.tm-label .code::before,.expressive-code .ec-line.ins.tm-label .code::before,.expressive-code .ec-line.del.tm-label .code::before{background:var(--ecLineBrdCol);padding:0 calc(var(--ec-tm-lineMarkerLabelPadInl) + var(--ec-tm-lineMarkerAccentWd)) 0 var(--ec-tm-lineMarkerLabelPadInl);color:var(--ec-tm-lineMarkerLabelCol)}.expressive-code .ec-line mark{--tmInlineBgCol:var(--ec-tm-markBg);--tmInlineBrdCol:var(--ec-tm-markBrdCol)}.expressive-code .ec-line ins{--tmInlineBgCol:var(--ec-tm-insBg);--tmInlineBrdCol:var(--ec-tm-insBrdCol)}.expressive-code .ec-line del{--tmInlineBgCol:var(--ec-tm-delBg);--tmInlineBrdCol:var(--ec-tm-delBrdCol)}.expressive-code .ec-line mark,.expressive-code .ec-line ins,.expressive-code .ec-line del{all:unset;display:inline-block;position:relative;--tmBrdL:var(--ec-tm-inlMarkerBrdWd);--tmBrdR:var(--ec-tm-inlMarkerBrdWd);--tmRadL:var(--ec-tm-inlMarkerBrdRad);--tmRadR:var(--ec-tm-inlMarkerBrdRad);margin-inline:0.025rem;padding-inline:var(--ec-tm-inlMarkerPad);border-radius:var(--tmRadL) var(--tmRadR) var(--tmRadR) var(--tmRadL);background:var(--tmInlineBgCol);background-clip:padding-box}.expressive-code .ec-line mark.open-start,.expressive-code .ec-line ins.open-start,.expressive-code .ec-line del.open-start{margin-inline-start:0;padding-inline-start:0;--tmBrdL:0px;--tmRadL:0}.expressive-code .ec-line mark.open-end,.expressive-code .ec-line ins.open-end,.expressive-code .ec-line del.open-end{margin-inline-end:0;padding-inline-end:0;--tmBrdR:0px;--tmRadR:0}.expressive-code .ec-line mark::before,.expressive-code .ec-line ins::before,.expressive-code .ec-line del::before{content:&apos;&apos;;position:absolute;pointer-events:none;display:inline-block;inset:0;border-radius:var(--tmRadL) var(--tmRadR) var(--tmRadR) var(--tmRadL);border:var(--ec-tm-inlMarkerBrdWd) solid var(--tmInlineBrdCol);border-inline-width:var(--tmBrdL) var(--tmBrdR)}.expressive-code .frame{all:unset;position:relative;display:block;--header-border-radius:calc(var(--ec-brdRad) + var(--ec-brdWd));--tab-border-radius:calc(var(--ec-frm-edTabBrdRad) + var(--ec-brdWd));--button-spacing:0.4rem;--code-background:var(--ec-frm-edBg);border-radius:var(--header-border-radius);box-shadow:var(--ec-frm-frameBoxShdCssVal)}.expressive-code .frame .header{display:none;z-index:1;position:relative;border-radius:var(--header-border-radius) var(--header-border-radius) 0 0}.expressive-code .frame.has-title pre,.expressive-code .frame.has-title code,.expressive-code .frame.is-terminal pre,.expressive-code .frame.is-terminal code{border-top:none;border-top-left-radius:0;border-top-right-radius:0}.expressive-code .frame .title:empty:before{content:&apos;\a0&apos;}.expressive-code .frame.has-title:not(.is-terminal){--button-spacing:calc(1.9rem + 2 * (var(--ec-uiPadBlk) + var(--ec-frm-edActTabIndHt)))}.expressive-code .frame.has-title:not(.is-terminal) .title{position:relative;color:var(--ec-frm-edActTabFg);background:var(--ec-frm-edActTabBg);background-clip:padding-box;margin-block-start:var(--ec-frm-edTabsMargBlkStart);padding:calc(var(--ec-uiPadBlk) + var(--ec-frm-edActTabIndHt)) var(--ec-uiPadInl);border:var(--ec-brdWd) solid var(--ec-frm-edActTabBrdCol);border-radius:var(--tab-border-radius) var(--tab-border-radius) 0 0;border-bottom:none;overflow:hidden}.expressive-code .frame.has-title:not(.is-terminal) .title::after{content:&apos;&apos;;position:absolute;pointer-events:none;inset:0;border-top:var(--ec-frm-edActTabIndHt) solid var(--ec-frm-edActTabIndTopCol);border-bottom:var(--ec-frm-edActTabIndHt) solid var(--ec-frm-edActTabIndBtmCol)}.expressive-code .frame.has-title:not(.is-terminal) .header{display:flex;background:linear-gradient(to top, var(--ec-frm-edTabBarBrdBtmCol) var(--ec-brdWd), transparent var(--ec-brdWd)),linear-gradient(var(--ec-frm-edTabBarBg), var(--ec-frm-edTabBarBg));background-repeat:no-repeat;padding-inline-start:var(--ec-frm-edTabsMargInlStart)}.expressive-code .frame.has-title:not(.is-terminal) .header::before{content:&apos;&apos;;position:absolute;pointer-events:none;inset:0;border:var(--ec-brdWd) solid var(--ec-frm-edTabBarBrdCol);border-radius:inherit;border-bottom:none}.expressive-code .frame.is-terminal{--button-spacing:calc(1.9rem + var(--ec-brdWd) + 2 * var(--ec-uiPadBlk));--code-background:var(--ec-frm-trmBg)}.expressive-code .frame.is-terminal .header{display:flex;align-items:center;justify-content:center;padding-block:var(--ec-uiPadBlk);padding-block-end:calc(var(--ec-uiPadBlk) + var(--ec-brdWd));position:relative;font-weight:500;letter-spacing:0.025ch;color:var(--ec-frm-trmTtbFg);background:var(--ec-frm-trmTtbBg);border:var(--ec-brdWd) solid var(--ec-brdCol);border-bottom:none}.expressive-code .frame.is-terminal .header::before{content:&apos;&apos;;position:absolute;pointer-events:none;left:var(--ec-uiPadInl);width:2.1rem;height:0.56rem;line-height:0;background-color:var(--ec-frm-trmTtbDotsFg);opacity:var(--ec-frm-trmTtbDotsOpa);-webkit-mask-image:var(--ec-frm-trmIcon);-webkit-mask-repeat:no-repeat;mask-image:var(--ec-frm-trmIcon);mask-repeat:no-repeat}.expressive-code .frame.is-terminal .header::after{content:&apos;&apos;;position:absolute;pointer-events:none;inset:0;border-bottom:var(--ec-brdWd) solid var(--ec-frm-trmTtbBrdBtmCol)}.expressive-code .frame pre{background:var(--code-background)}.expressive-code .copy{display:flex;gap:0.25rem;flex-direction:row;position:absolute;inset-block-start:calc(var(--ec-brdWd) + var(--button-spacing));inset-inline-end:calc(var(--ec-brdWd) + var(--ec-uiPadInl) / 2)}@media (scripting: none){.expressive-code .copy{display:none}}.expressive-code .copy{direction:ltr;unicode-bidi:isolate}.expressive-code .copy button{position:relative;align-self:flex-end;margin:0;padding:0;border:none;border-radius:0.2rem;z-index:1;cursor:pointer;transition-property:opacity, background, border-color;transition-duration:0.2s;transition-timing-function:cubic-bezier(0.25, 0.46, 0.45, 0.94);width:2.5rem;height:2.5rem;background:var(--code-background);opacity:0.75}.expressive-code .copy button div{position:absolute;inset:0;border-radius:inherit;background:var(--ec-frm-inlBtnBg);opacity:var(--ec-frm-inlBtnBgIdleOpa);transition-property:inherit;transition-duration:inherit;transition-timing-function:inherit}.expressive-code .copy button::before{content:&apos;&apos;;position:absolute;pointer-events:none;inset:0;border-radius:inherit;border:var(--ec-brdWd) solid var(--ec-frm-inlBtnBrd);opacity:var(--ec-frm-inlBtnBrdOpa)}.expressive-code .copy button::after{content:&apos;&apos;;position:absolute;pointer-events:none;inset:0;background-color:var(--ec-frm-inlBtnFg);-webkit-mask-image:var(--ec-frm-copyIcon);-webkit-mask-repeat:no-repeat;mask-image:var(--ec-frm-copyIcon);mask-repeat:no-repeat;margin:0.475rem;line-height:0}.expressive-code .copy button:hover,.expressive-code .copy button:focus:focus-visible{opacity:1}.expressive-code .copy button:hover div,.expressive-code .copy button:focus:focus-visible div{opacity:var(--ec-frm-inlBtnBgHoverOrFocusOpa)}.expressive-code .copy button:active{opacity:1}.expressive-code .copy button:active div{opacity:var(--ec-frm-inlBtnBgActOpa)}.expressive-code .copy .feedback{--tooltip-arrow-size:0.35rem;--tooltip-bg:var(--ec-frm-tooltipSuccessBg);color:var(--ec-frm-tooltipSuccessFg);pointer-events:none;user-select:none;-webkit-user-select:none;position:relative;align-self:center;background-color:var(--tooltip-bg);z-index:99;padding:0.125rem 0.75rem;border-radius:0.2rem;margin-inline-end:var(--tooltip-arrow-size);opacity:0;transition-property:opacity, transform;transition-duration:0.2s;transition-timing-function:ease-in-out;transform:translate3d(0, 0.25rem, 0)}.expressive-code .copy .feedback::after{content:&apos;&apos;;position:absolute;pointer-events:none;top:calc(50% - var(--tooltip-arrow-size));inset-inline-end:calc(-2 * (var(--tooltip-arrow-size) - 0.5px));border:var(--tooltip-arrow-size) solid transparent;border-inline-start-color:var(--tooltip-bg)}.expressive-code .copy .feedback.show{opacity:1;transform:translate3d(0, 0, 0)}@media (hover: hover){.expressive-code{}.expressive-code .copy button{opacity:0;width:2rem;height:2rem}.expressive-code .frame:hover .copy button:not(:hover),.expressive-code .frame:focus-within :focus-visible ~ .copy button:not(:hover),.expressive-code .frame .copy .feedback.show ~ button:not(:hover){opacity:0.75}}.expressive-code :nth-child(1 of .ec-line) .code{padding-inline-end:calc(2rem + var(--ec-codePadInl))}:root{--ec-brdRad:0.75rem;--ec-brdWd:1.5px;--ec-brdCol:var(--code-line);--ec-codeFontFml:var(--font-code);--ec-codeFontSize:0.875rem;--ec-codeFontWg:400;--ec-codeLineHt:1.75;--ec-codePadBlk:1rem;--ec-codePadInl:1.125rem;--ec-codeBg:var(--code-bg);--ec-codeFg:#e6edf3;--ec-codeSelBg:#264f78;--ec-gtrFg:#6e7681;--ec-gtrBrdCol:#6e768133;--ec-gtrBrdWd:1.5px;--ec-gtrHlFg:#e6edf3;--ec-uiFontFml:var(--font-mono);--ec-uiFontSize:0.75rem;--ec-uiFontWg:400;--ec-uiLineHt:1.65;--ec-uiPadBlk:0.25rem;--ec-uiPadInl:1rem;--ec-uiSelBg:#6e768166;--ec-uiSelFg:#e6edf3;--ec-focusBrd:#1f6feb;--ec-sbThumbCol:#8b949e33;--ec-sbThumbHoverCol:#8b949e3d;--ec-tm-lineMarkerAccentMarg:0rem;--ec-tm-lineMarkerAccentWd:0.15rem;--ec-tm-lineMarkerLabelPadInl:0.2rem;--ec-tm-lineMarkerLabelCol:white;--ec-tm-lineDiffIndMargLeft:0.3rem;--ec-tm-inlMarkerBrdWd:1.5px;--ec-tm-inlMarkerBrdRad:0.2rem;--ec-tm-inlMarkerPad:0.15rem;--ec-tm-insDiffIndContent:&apos;+&apos;;--ec-tm-delDiffIndContent:&apos;-&apos;;--ec-tm-markBg:#264a8980;--ec-tm-markBrdCol:#5570b3d0;--ec-tm-insBg:#26561c80;--ec-tm-insBrdCol:#4e7e41d0;--ec-tm-insDiffIndCol:#7eb070d0;--ec-tm-delBg:#81322b80;--ec-tm-delBrdCol:#ae594fd0;--ec-tm-delDiffIndCol:#e68a7ed0;--ec-frm-shdCol:#0000005b;--ec-frm-frameBoxShdCssVal:none;--ec-frm-edActTabBg:var(--code-bg);--ec-frm-edActTabFg:var(--code-muted);--ec-frm-edActTabBrdCol:transparent;--ec-frm-edActTabIndHt:1.5px;--ec-frm-edActTabIndTopCol:transparent;--ec-frm-edActTabIndBtmCol:#0d1117;--ec-frm-edTabsMargInlStart:0;--ec-frm-edTabsMargBlkStart:0;--ec-frm-edTabBrdRad:0.75rem;--ec-frm-edTabBarBg:var(--code-bg);--ec-frm-edTabBarBrdCol:var(--code-line);--ec-frm-edTabBarBrdBtmCol:var(--code-line);--ec-frm-edBg:var(--code-bg);--ec-frm-trmTtbFg:var(--code-muted);--ec-frm-trmTtbDotsFg:var(--code-muted);--ec-frm-trmTtbDotsOpa:0.15;--ec-frm-trmTtbBg:var(--code-bg);--ec-frm-trmTtbBrdBtmCol:var(--code-line);--ec-frm-trmBg:var(--code-bg);--ec-frm-inlBtnBg:var(--code-ink);--ec-frm-inlBtnBgIdleOpa:0;--ec-frm-inlBtnBgHoverOrFocusOpa:0.2;--ec-frm-inlBtnBgActOpa:0.3;--ec-frm-inlBtnFg:var(--code-ink);--ec-frm-inlBtnBrd:var(--code-line);--ec-frm-inlBtnBrdOpa:0.4;--ec-frm-tooltipSuccessBg:var(--color-emerald);--ec-frm-tooltipSuccessFg:var(--color-bg);--ec-frm-copyIcon:url(&quot;data:image/svg+xml,%3Csvg%20xmlns%3D&apos;http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg&apos;%20viewBox%3D&apos;0%200%2024%2024&apos;%20fill%3D&apos;none&apos;%20stroke%3D&apos;black&apos;%20stroke-width%3D&apos;1.75&apos;%3E%3Cpath%20d%3D&apos;M3%2019a2%202%200%200%201-1-2V2a2%202%200%200%201%201-1h13a2%202%200%200%201%202%201&apos;%2F%3E%3Crect%20x%3D&apos;6&apos;%20y%3D&apos;5&apos;%20width%3D&apos;16&apos;%20height%3D&apos;18&apos;%20rx%3D&apos;1.5&apos;%20ry%3D&apos;1.5&apos;%2F%3E%3C%2Fsvg%3E&quot;);--ec-frm-trmIcon:url(&quot;data:image/svg+xml,%3Csvg%20xmlns%3D&apos;http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg&apos;%20viewBox%3D&apos;0%200%2060%2016&apos;%20preserveAspectRatio%3D&apos;xMidYMid%20meet&apos;%3E%3Ccircle%20cx%3D&apos;8&apos;%20cy%3D&apos;8&apos;%20r%3D&apos;8&apos;%2F%3E%3Ccircle%20cx%3D&apos;30&apos;%20cy%3D&apos;8&apos;%20r%3D&apos;8&apos;%2F%3E%3Ccircle%20cx%3D&apos;52&apos;%20cy%3D&apos;8&apos;%20r%3D&apos;8&apos;%2F%3E%3C%2Fsvg%3E&quot;)}.expressive-code .ec-line :where(span[style^=&apos;--&apos;]:not([class])){color:var(--0, inherit);background-color:var(--0bg, transparent);font-style:var(--0fs, inherit);font-weight:var(--0fw, inherit);text-decoration:var(--0td, inherit)}&lt;/style&gt;&lt;script type=&quot;module&quot; src=&quot;/_astro/ec.0vx5m.js&quot;&gt;&lt;/script&gt;&lt;figure class=&quot;frame has-title&quot;&gt;&lt;figcaption class=&quot;header&quot;&gt;&lt;span class=&quot;title&quot;&gt;SQL&lt;/span&gt;&lt;/figcaption&gt;&lt;pre data-language=&quot;sql&quot;&gt;&lt;code&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span style=&quot;--0:#8B949E&quot;&gt;-- Outbox table in the producer service database&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;CREATE&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; &lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;TABLE&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; &lt;/span&gt;&lt;span style=&quot;--0:#D2A8FF&quot;&gt;outbox_messages&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; (&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span class=&quot;indent&quot;&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;    &lt;/span&gt;&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;id UUID &lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;PRIMARY KEY&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; &lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;DEFAULT&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; gen_random_uuid(),&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span class=&quot;indent&quot;&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;    &lt;/span&gt;&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;aggregate_type &lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;VARCHAR&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;(&lt;/span&gt;&lt;span style=&quot;--0:#79C0FF&quot;&gt;255&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;) &lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;NOT NULL&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;, &lt;/span&gt;&lt;span style=&quot;--0:#8B949E&quot;&gt;-- For example: &apos;ORDER&apos;&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span class=&quot;indent&quot;&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;    &lt;/span&gt;&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;aggregate_id &lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;VARCHAR&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;(&lt;/span&gt;&lt;span style=&quot;--0:#79C0FF&quot;&gt;255&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;) &lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;NOT NULL&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;,   &lt;/span&gt;&lt;span style=&quot;--0:#8B949E&quot;&gt;-- For example: Order ID&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span class=&quot;indent&quot;&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;    &lt;/span&gt;&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;event_type &lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;VARCHAR&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;(&lt;/span&gt;&lt;span style=&quot;--0:#79C0FF&quot;&gt;255&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;) &lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;NOT NULL&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;,     &lt;/span&gt;&lt;span style=&quot;--0:#8B949E&quot;&gt;-- For example: &apos;ORDER_CREATED&apos;&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span class=&quot;indent&quot;&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;    &lt;/span&gt;&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;payload JSONB &lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;NOT NULL&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;,               &lt;/span&gt;&lt;span style=&quot;--0:#8B949E&quot;&gt;-- Complete event payload&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span class=&quot;indent&quot;&gt;    &lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;status&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; &lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;VARCHAR&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;(&lt;/span&gt;&lt;span style=&quot;--0:#79C0FF&quot;&gt;50&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;) &lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;DEFAULT&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; &lt;/span&gt;&lt;span style=&quot;--0:#A5D6FF&quot;&gt;&apos;PENDING&apos;&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;, &lt;/span&gt;&lt;span style=&quot;--0:#8B949E&quot;&gt;-- PENDING, PROCESSED, or FAILED&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span class=&quot;indent&quot;&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;    &lt;/span&gt;&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;retry_count &lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;INT&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; &lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;DEFAULT&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; &lt;/span&gt;&lt;span style=&quot;--0:#79C0FF&quot;&gt;0&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;,&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span class=&quot;indent&quot;&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;    &lt;/span&gt;&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;created_at &lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;TIMESTAMP WITH TIME ZONE&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; &lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;DEFAULT&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; CURRENT_TIMESTAMP,&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span class=&quot;indent&quot;&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;    &lt;/span&gt;&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;processed_at &lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;TIMESTAMP WITH TIME ZONE&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;);&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;
&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span style=&quot;--0:#8B949E&quot;&gt;-- Idempotency table in the consumer service database&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;CREATE&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; &lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;TABLE&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; &lt;/span&gt;&lt;span style=&quot;--0:#D2A8FF&quot;&gt;idempotent_consumers&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; (&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span class=&quot;indent&quot;&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;    &lt;/span&gt;&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;message_id UUID &lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;PRIMARY KEY&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;,          &lt;/span&gt;&lt;span style=&quot;--0:#8B949E&quot;&gt;-- Outbox table ID serves as the unique key here&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span class=&quot;indent&quot;&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;    &lt;/span&gt;&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;processed_at &lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;TIMESTAMP WITH TIME ZONE&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; &lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;DEFAULT&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; CURRENT_TIMESTAMP,&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span class=&quot;indent&quot;&gt;    &lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;status&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; &lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;VARCHAR&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;(&lt;/span&gt;&lt;span style=&quot;--0:#79C0FF&quot;&gt;50&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;) &lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;NOT NULL&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;           &lt;/span&gt;&lt;span style=&quot;--0:#8B949E&quot;&gt;-- SUCCESS or FAILED&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;);&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;/code&gt;&lt;/pre&gt;&lt;div class=&quot;copy&quot;&gt;&lt;div aria-live=&quot;polite&quot;&gt;&lt;/div&gt;&lt;button title=&quot;Copy to clipboard&quot; data-copied=&quot;Copied!&quot; data-code=&quot;-- Outbox table in the producer service databaseCREATE TABLE outbox_messages (    id UUID PRIMARY KEY DEFAULT gen_random_uuid(),    aggregate_type VARCHAR(255) NOT NULL, -- For example: &amp;#x27;ORDER&amp;#x27;    aggregate_id VARCHAR(255) NOT NULL,   -- For example: Order ID    event_type VARCHAR(255) NOT NULL,     -- For example: &amp;#x27;ORDER_CREATED&amp;#x27;    payload JSONB NOT NULL,               -- Complete event payload    status VARCHAR(50) DEFAULT &amp;#x27;PENDING&amp;#x27;, -- PENDING, PROCESSED, or FAILED    retry_count INT DEFAULT 0,    created_at TIMESTAMP WITH TIME ZONE DEFAULT CURRENT_TIMESTAMP,    processed_at TIMESTAMP WITH TIME ZONE);-- Idempotency table in the consumer service databaseCREATE TABLE idempotent_consumers (    message_id UUID PRIMARY KEY,          -- Outbox table ID serves as the unique key here    processed_at TIMESTAMP WITH TIME ZONE DEFAULT CURRENT_TIMESTAMP,    status VARCHAR(50) NOT NULL           -- SUCCESS or FAILED);&quot;&gt;&lt;div&gt;&lt;/div&gt;&lt;/button&gt;&lt;/div&gt;&lt;/figure&gt;&lt;/div&gt;
&lt;p&gt;&lt;strong&gt;Step 2: Atomic Transaction Implementation Code&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;Now let us use Node.js and the Prisma ORM to see how we create an order and insert an outbox record inside a single atomic transaction block. Notice that we make zero external Kafka or network calls inside this block.&lt;/p&gt;
&lt;div class=&quot;expressive-code&quot;&gt;&lt;figure class=&quot;frame has-title&quot;&gt;&lt;figcaption class=&quot;header&quot;&gt;&lt;span class=&quot;title&quot;&gt;TypeScript&lt;/span&gt;&lt;/figcaption&gt;&lt;pre data-language=&quot;typescript&quot;&gt;&lt;code&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;import&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; { PrismaClient } &lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;from&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; &lt;/span&gt;&lt;span style=&quot;--0:#A5D6FF&quot;&gt;&apos;@prisma/client&apos;&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;;&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;import&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; { randomUUID } &lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;from&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; &lt;/span&gt;&lt;span style=&quot;--0:#A5D6FF&quot;&gt;&apos;crypto&apos;&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;;&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;
&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;const&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; &lt;/span&gt;&lt;span style=&quot;--0:#79C0FF&quot;&gt;prisma&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; &lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;=&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; &lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;new&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; &lt;/span&gt;&lt;span style=&quot;--0:#D2A8FF&quot;&gt;PrismaClient&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;();&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;
&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;async&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; &lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;function&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; &lt;/span&gt;&lt;span style=&quot;--0:#D2A8FF&quot;&gt;createOrderWithOutbox&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;(&lt;/span&gt;&lt;span style=&quot;--0:#FFA657&quot;&gt;userId&lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;:&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; &lt;/span&gt;&lt;span style=&quot;--0:#79C0FF&quot;&gt;string&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;, &lt;/span&gt;&lt;span style=&quot;--0:#FFA657&quot;&gt;totalAmount&lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;:&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; &lt;/span&gt;&lt;span style=&quot;--0:#79C0FF&quot;&gt;number&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;, &lt;/span&gt;&lt;span style=&quot;--0:#FFA657&quot;&gt;items&lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;:&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; &lt;/span&gt;&lt;span style=&quot;--0:#79C0FF&quot;&gt;any&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;[]) {&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span class=&quot;indent&quot;&gt;  &lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;const&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; &lt;/span&gt;&lt;span style=&quot;--0:#79C0FF&quot;&gt;orderId&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; &lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;=&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; &lt;/span&gt;&lt;span style=&quot;--0:#D2A8FF&quot;&gt;randomUUID&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;();&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span class=&quot;indent&quot;&gt;  &lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;const&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; &lt;/span&gt;&lt;span style=&quot;--0:#79C0FF&quot;&gt;eventId&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; &lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;=&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; &lt;/span&gt;&lt;span style=&quot;--0:#D2A8FF&quot;&gt;randomUUID&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;();&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;
&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span class=&quot;indent&quot;&gt;  &lt;/span&gt;&lt;span style=&quot;--0:#8B949E&quot;&gt;// Starting a single atomic transaction&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span class=&quot;indent&quot;&gt;  &lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;try&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; {&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span class=&quot;indent&quot;&gt;    &lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;const&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; &lt;/span&gt;&lt;span style=&quot;--0:#79C0FF&quot;&gt;result&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; &lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;=&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; &lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;await&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; prisma.&lt;/span&gt;&lt;span style=&quot;--0:#D2A8FF&quot;&gt;$transaction&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;(&lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;async&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; (&lt;/span&gt;&lt;span style=&quot;--0:#FFA657&quot;&gt;tx&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;) &lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;=&gt;&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; {&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span class=&quot;indent&quot;&gt;      &lt;/span&gt;&lt;span style=&quot;--0:#8B949E&quot;&gt;// 1. Save the order in the main business table&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span class=&quot;indent&quot;&gt;      &lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;const&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; &lt;/span&gt;&lt;span style=&quot;--0:#79C0FF&quot;&gt;newOrder&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; &lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;=&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; &lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;await&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; tx.orders.&lt;/span&gt;&lt;span style=&quot;--0:#D2A8FF&quot;&gt;create&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;({&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span class=&quot;indent&quot;&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;        &lt;/span&gt;&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;data: {&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span class=&quot;indent&quot;&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;          &lt;/span&gt;&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;id: orderId,&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span class=&quot;indent&quot;&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;          &lt;/span&gt;&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;userId: userId,&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span class=&quot;indent&quot;&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;          &lt;/span&gt;&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;totalAmount: totalAmount,&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span class=&quot;indent&quot;&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;          &lt;/span&gt;&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;status: &lt;/span&gt;&lt;span style=&quot;--0:#A5D6FF&quot;&gt;&apos;CREATED&apos;&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;,&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span class=&quot;indent&quot;&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;        &lt;/span&gt;&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;},&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span class=&quot;indent&quot;&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;      &lt;/span&gt;&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;});&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;
&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span class=&quot;indent&quot;&gt;      &lt;/span&gt;&lt;span style=&quot;--0:#8B949E&quot;&gt;// 2. Save the event payload in the outbox table&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span class=&quot;indent&quot;&gt;      &lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;await&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; tx.outbox_messages.&lt;/span&gt;&lt;span style=&quot;--0:#D2A8FF&quot;&gt;create&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;({&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span class=&quot;indent&quot;&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;        &lt;/span&gt;&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;data: {&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span class=&quot;indent&quot;&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;          &lt;/span&gt;&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;id: eventId,&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span class=&quot;indent&quot;&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;          &lt;/span&gt;&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;aggregate_type: &lt;/span&gt;&lt;span style=&quot;--0:#A5D6FF&quot;&gt;&apos;ORDER&apos;&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;,&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span class=&quot;indent&quot;&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;          &lt;/span&gt;&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;aggregate_id: orderId,&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span class=&quot;indent&quot;&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;          &lt;/span&gt;&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;event_type: &lt;/span&gt;&lt;span style=&quot;--0:#A5D6FF&quot;&gt;&apos;ORDER_CREATED&apos;&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;,&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span class=&quot;indent&quot;&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;          &lt;/span&gt;&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;payload: &lt;/span&gt;&lt;span style=&quot;--0:#79C0FF&quot;&gt;JSON&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;.&lt;/span&gt;&lt;span style=&quot;--0:#D2A8FF&quot;&gt;stringify&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;({&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span class=&quot;indent&quot;&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;            &lt;/span&gt;&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;orderId: newOrder.id,&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span class=&quot;indent&quot;&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;            &lt;/span&gt;&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;userId: newOrder.userId,&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span class=&quot;indent&quot;&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;            &lt;/span&gt;&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;amount: newOrder.totalAmount,&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span class=&quot;indent&quot;&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;            &lt;/span&gt;&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;items: items,&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span class=&quot;indent&quot;&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;          &lt;/span&gt;&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;}),&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span class=&quot;indent&quot;&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;          &lt;/span&gt;&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;status: &lt;/span&gt;&lt;span style=&quot;--0:#A5D6FF&quot;&gt;&apos;PENDING&apos;&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;,&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span class=&quot;indent&quot;&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;        &lt;/span&gt;&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;},&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span class=&quot;indent&quot;&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;      &lt;/span&gt;&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;});&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;
&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span class=&quot;indent&quot;&gt;      &lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;return&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; newOrder;&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span class=&quot;indent&quot;&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;    &lt;/span&gt;&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;});&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;
&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span class=&quot;indent&quot;&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;    &lt;/span&gt;&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;console.&lt;/span&gt;&lt;span style=&quot;--0:#D2A8FF&quot;&gt;log&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;(&lt;/span&gt;&lt;span style=&quot;--0:#A5D6FF&quot;&gt;`Order and Outbox entry created atomically with ID: ${&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;result&lt;/span&gt;&lt;span style=&quot;--0:#A5D6FF&quot;&gt;.&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;id&lt;/span&gt;&lt;span style=&quot;--0:#A5D6FF&quot;&gt;}`&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;);&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span class=&quot;indent&quot;&gt;    &lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;return&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; result;&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span class=&quot;indent&quot;&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;  &lt;/span&gt;&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;} &lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;catch&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; (error) {&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span class=&quot;indent&quot;&gt;    &lt;/span&gt;&lt;span style=&quot;--0:#8B949E&quot;&gt;// If any database error occurs, both table write operations roll back together&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span class=&quot;indent&quot;&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;    &lt;/span&gt;&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;console.&lt;/span&gt;&lt;span style=&quot;--0:#D2A8FF&quot;&gt;error&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;(&lt;/span&gt;&lt;span style=&quot;--0:#A5D6FF&quot;&gt;&apos;Failed to execute atomic transaction, rollback completed.&apos;&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;, error);&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span class=&quot;indent&quot;&gt;    &lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;throw&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; error;&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span class=&quot;indent&quot;&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;  &lt;/span&gt;&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;}&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;}&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;/code&gt;&lt;/pre&gt;&lt;div class=&quot;copy&quot;&gt;&lt;div aria-live=&quot;polite&quot;&gt;&lt;/div&gt;&lt;button title=&quot;Copy to clipboard&quot; data-copied=&quot;Copied!&quot; data-code=&quot;import { PrismaClient } from &amp;#x27;@prisma/client&amp;#x27;;import { randomUUID } from &amp;#x27;crypto&amp;#x27;;const prisma = new PrismaClient();async function createOrderWithOutbox(userId: string, totalAmount: number, items: any[]) {  const orderId = randomUUID();  const eventId = randomUUID();  // Starting a single atomic transaction  try {    const result = await prisma.$transaction(async (tx) =&gt; {      // 1. Save the order in the main business table      const newOrder = await tx.orders.create({        data: {          id: orderId,          userId: userId,          totalAmount: totalAmount,          status: &amp;#x27;CREATED&amp;#x27;,        },      });      // 2. Save the event payload in the outbox table      await tx.outbox_messages.create({        data: {          id: eventId,          aggregate_type: &amp;#x27;ORDER&amp;#x27;,          aggregate_id: orderId,          event_type: &amp;#x27;ORDER_CREATED&amp;#x27;,          payload: JSON.stringify({            orderId: newOrder.id,            userId: newOrder.userId,            amount: newOrder.totalAmount,            items: items,          }),          status: &amp;#x27;PENDING&amp;#x27;,        },      });      return newOrder;    });    console.log(&amp;#x60;Order and Outbox entry created atomically with ID: ${result.id}&amp;#x60;);    return result;  } catch (error) {    // If any database error occurs, both table write operations roll back together    console.error(&amp;#x27;Failed to execute atomic transaction, rollback completed.&amp;#x27;, error);    throw error;  }}&quot;&gt;&lt;div&gt;&lt;/div&gt;&lt;/button&gt;&lt;/div&gt;&lt;/figure&gt;&lt;/div&gt;
&lt;div class=&quot;callout&quot; role=&quot;note&quot; data-type=&quot;warning&quot;&gt;
&lt;p class=&quot;callout-title&quot;&gt;Warning&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;External Network Calls Inside DB Transactions:&lt;/strong&gt; Never place external message broker publishing code (such as &lt;code&gt;await kafka.send()&lt;/code&gt;) inside your local database transaction blocks. If the external network call experiences latency or times out, it will keep your database connection pool locked for an extended period. Other users will be blocked from getting database connections, causing cascading failures that take your entire application down.&lt;/p&gt;
&lt;/div&gt;
&lt;p&gt;&lt;strong&gt;Step 3: The Outbox Publisher (Poller vs CDC)&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;Our database is now storing events in a &lt;code&gt;PENDING&lt;/code&gt; state. We need a background worker to pick up these records and send them to our message broker. Engineers generally use two distinct mechanisms for this task: custom polling or Change Data Capture (CDC).&lt;/p&gt;
&lt;p&gt;In a custom polling mechanism, your application runs a scheduled cron job or background thread that executes a query like &lt;code&gt;SELECT * FROM outbox_messages WHERE status = &apos;PENDING&apos; ORDER BY created_at ASC LIMIT 100&lt;/code&gt; every few milliseconds. The worker reads those messages, sends them to Kafka, and then updates the database records to a &lt;code&gt;PROCESSED&lt;/code&gt; state. This works fine for small or medium-scale applications, but in high-throughput systems, it generates intense read-write pressure on your database.&lt;/p&gt;
&lt;p&gt;The modern production solution for this bottleneck is using a Change Data Capture tool, with Debezium being the industry favorite. Debezium never executes standard SQL queries against your database. Instead, it reads your database engine&apos;s Write-Ahead Log or binary log files directly as a continuous, low-level byte stream. Whenever a new row is inserted into the &lt;code&gt;outbox_messages&lt;/code&gt; table, Debezium captures the event from the log file and pushes it to Kafka within milliseconds without generating any database table locks.&lt;/p&gt;
&lt;figure&gt;&lt;img src=&quot;https://raw.githubusercontent.com/rafeuddaraj/rafes-blog-assets/refs/heads/distributed-systems-transactional-outbox-idempotency-deep-dive/assets/execution-trace-timeline.svg&quot; alt=&quot;Execution Trace Timeline&quot; loading=&quot;lazy&quot; decoding=&quot;async&quot; width=&quot;1000&quot; height=&quot;480&quot;&gt;&lt;figcaption&gt;Execution Trace Timeline&lt;/figcaption&gt;&lt;/figure&gt;
&lt;p&gt;In the timeline diagram above, you can trace the exact millisecond-level flow from the initial client HTTP request to the database commit, the CDC log reading, the Kafka broker publishing, and finally the idempotent processing in the consumer service.&lt;/p&gt;
&lt;h2 id=&quot;5-distributed-failure-modes-what-breaks-how-to-fix&quot;&gt;5. Distributed Failure Modes (What Breaks &amp;#x26; How to Fix)&lt;/h2&gt;
&lt;p&gt;The true measure of any software architecture is how it behaves when hardware and networks fail. Let us analyze three realistic failure scenarios in distributed systems and examine their structural solutions.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Scenario 1: The Message Broker Goes Completely Down&lt;/strong&gt;&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;
&lt;p&gt;&lt;em&gt;The Architectural Disaster:&lt;/em&gt; Your outbox publisher or CDC engine tries to send messages to Kafka, but the broker has crashed and refuses connections. A massive backlog of thousands of &lt;code&gt;PENDING&lt;/code&gt; messages builds up inside your outbox table, while your background workers continuously retry and exhaust your database connection pool.&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;&lt;em&gt;The Structural Solution:&lt;/em&gt; You must implement an exponential backoff with jitter mechanism. Instead of retrying immediately, the background worker should increase its waiting period after every failed attempt, scaling from 2 seconds to 4, 8, and 16 seconds. You must also add randomized timing, known as jitter, so all your background workers do not hit the database or broker at the exact same millisecond and trigger a thundering herd problem.&lt;/p&gt;
&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;&lt;strong&gt;Scenario 2: Dual Message Delivery&lt;/strong&gt;&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;
&lt;p&gt;&lt;em&gt;The Architectural Disaster:&lt;/em&gt; Your outbox publisher successfully sends an event to Kafka, and Kafka delivers it to the consumer service. The consumer service processes a user payment completely, but right as it sends an acknowledgment back to Kafka, the network connection drops. Kafka assumes the message was never processed, so its internal retry logic sends the exact same message to the consumer again. This results in a catastrophic failure where the user gets charged twice for the exact same order.&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;&lt;em&gt;The Structural Solution:&lt;/em&gt; You solve this by building an idempotent consumer layer inside your target service. When a message arrives, the service does not execute its business logic immediately. Instead, it extracts the unique &lt;code&gt;message_id&lt;/code&gt; and checks its own database inside the &lt;code&gt;idempotent_consumers&lt;/code&gt; table. If that ID already exists, the service skips the operation entirely and sends a success acknowledgment back to Kafka. If the ID is missing, the service executes the business logic and inserts the ID into the &lt;code&gt;idempotent_consumers&lt;/code&gt; table within the same database transaction.&lt;/p&gt;
&lt;/li&gt;
&lt;/ul&gt;
&lt;div class=&quot;callout&quot; role=&quot;note&quot; data-type=&quot;tip&quot;&gt;
&lt;p class=&quot;callout-title&quot;&gt;Tip&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;High-Throughput Distributed Locking:&lt;/strong&gt; When your consumer service receives hundreds of thousands of requests per second, performing constant read-write checks against a relational database for idempotency can degrade performance. In these extreme high-throughput scenarios, you can use a Redis distributed lock (such as the Redlock algorithm) to complete idempotency checks directly in memory. However, always keep a unique key constraint on your relational database as your final safety net.&lt;/p&gt;
&lt;/div&gt;
&lt;p&gt;&lt;strong&gt;Scenario 3: Out-of-Order Event Processing&lt;/strong&gt;&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;
&lt;p&gt;&lt;em&gt;The Architectural Disaster:&lt;/em&gt; Network latency or Kafka partition rebalancing causes messages to arrive out of their original sequence. Imagine an &lt;code&gt;Order_Updated&lt;/code&gt; or &lt;code&gt;Order_Cancelled&lt;/code&gt; event arriving at your consumer service before the initial &lt;code&gt;Order_Created&lt;/code&gt; event gets there. If the consumer tries to process an update on an order that does not exist in its local database yet, the entire operation crashes.&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;&lt;em&gt;The Structural Solution:&lt;/em&gt; You must include an incremental version number or a precise timestamp inside your event payload. Your consumer service must implement state machine logic to check if the incoming event&apos;s version is greater than the current database record&apos;s version. If an event arrives out of order, the consumer places it into a temporary buffer or a Dead Letter Queue (DLQ) and reprocesses it after the missing sequence events arrive.&lt;/p&gt;
&lt;/li&gt;
&lt;/ul&gt;
&lt;h2 id=&quot;6-high-throughput-performance-tuning&quot;&gt;6. High-Throughput Performance Tuning&lt;/h2&gt;
&lt;p&gt;When your system scales up to handle 10,000 or more events per second, standard basic implementations quickly turn into performance bottlenecks. You must apply specific low-level optimization strategies to keep your system running smoothly under heavy loads.&lt;/p&gt;
&lt;p&gt;First, we need to understand the technical justification for choosing Change Data Capture over custom polling in production. When you run &lt;code&gt;SELECT * FROM outbox_messages WHERE status = &apos;PENDING&apos;&lt;/code&gt; hundreds of times a second, you force the database engine to perform repeated table scans. Furthermore, when your worker updates thousands of records after publishing (&lt;code&gt;UPDATE outbox_messages SET status = &apos;PROCESSED&apos;&lt;/code&gt;), it triggers row-level locks across the table. This constant read-write friction slows down your primary business transactions. Debezium avoids this entirely by reading the WAL file externally, adding zero read load or locking overhead to your database tables.&lt;/p&gt;
&lt;p&gt;Second, if you decide to use a polling mechanism for smaller deployments, you must build an optimized indexing strategy. Creating an index on just the &lt;code&gt;status&lt;/code&gt; column is useless because almost every record in the table eventually turns into &lt;code&gt;PROCESSED&lt;/code&gt;, which creates low cardinality. Instead, you must create a composite B-Tree index on the &lt;code&gt;(status, created_at)&lt;/code&gt; columns. This allows your database engine to locate the oldest pending messages instantly with &lt;span class=&quot;katex&quot;&gt;&lt;span class=&quot;katex-html&quot; aria-hidden=&quot;true&quot;&gt;&lt;span class=&quot;base&quot;&gt;&lt;span class=&quot;strut&quot; style=&quot;height:1em;vertical-align:-0.25em;&quot;&gt;&lt;/span&gt;&lt;span class=&quot;mord mathnormal&quot; style=&quot;margin-right:0.0278em;&quot;&gt;O&lt;/span&gt;&lt;span class=&quot;mopen&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mop&quot;&gt;lo&lt;span style=&quot;margin-right:0.0139em;&quot;&gt;g&lt;/span&gt;&lt;/span&gt;&lt;span class=&quot;mspace&quot; style=&quot;margin-right:0.1667em;&quot;&gt;&lt;/span&gt;&lt;span class=&quot;mord mathnormal&quot;&gt;n&lt;/span&gt;&lt;span class=&quot;mclose&quot;&gt;)&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/span&gt; time complexity without ever scanning the entire table.&lt;/p&gt;
&lt;p&gt;Third, you should use batching and pipelining when transferring data to your message broker instead of sending single network calls. Wasting TCP handshakes and network round-trip times (RTT) to publish messages one by one is highly inefficient. Instead, your worker should read 500 or 1,000 messages into a memory buffer and use the broker&apos;s batch producer API to send the entire payload over a single network request. This massively multiplies your network throughput and drops end-to-end system latency.&lt;/p&gt;
&lt;div class=&quot;callout&quot; role=&quot;note&quot; data-type=&quot;note&quot;&gt;
&lt;p class=&quot;callout-title&quot;&gt;Important&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Outbox Table Cleanup and Purge Policy:&lt;/strong&gt; Never treat your outbox table as permanent storage. Once messages are successfully published to your broker, your table will rapidly accumulate millions of &lt;code&gt;PROCESSED&lt;/code&gt; rows. This bloats your database size and degrades index performance. You must run a scheduled cron job or a dedicated purge policy (such as running daily at 3:00 AM) to archive or delete old processed records.&lt;/p&gt;
&lt;/div&gt;
&lt;h2 id=&quot;7-alternative-solutions-and-trade-off-matrix&quot;&gt;7. Alternative Solutions and Trade-off Matrix&lt;/h2&gt;
&lt;p&gt;A core responsibility of a senior architect is evaluating trade-offs instead of blindly implementing patterns. Beyond the outbox pattern, the software industry uses several other techniques to handle data consistency across distributed systems. Let us look at a direct comparison.&lt;/p&gt;
&lt;p&gt;The Two-Phase Commit (2PC) protocol is a classic distributed transaction mechanism where a central coordinator tells all participating databases and brokers to prepare for a commit (the Prepare Phase), and only commands them to commit once every participant agrees (the Commit Phase). While this guarantees strong consistency, its biggest drawback is that it is a blocking protocol. If a single node experiences slowdowns, every transaction across the entire system locks up and waits, making it completely unsuitable for modern high-scale microservices.&lt;/p&gt;
&lt;p&gt;You can easily evaluate the trade-offs of these architectural approaches using the comparison matrix below:&lt;/p&gt;
&lt;section class=&quot;table-wrap&quot; tabindex=&quot;0&quot; aria-label=&quot;Table 1&quot;&gt;




























&lt;table&gt;&lt;thead&gt;&lt;tr&gt;&lt;th&gt;Architectural Approach&lt;/th&gt;&lt;th&gt;Data Consistency&lt;/th&gt;&lt;th&gt;System Complexity&lt;/th&gt;&lt;th&gt;Performance and Latency&lt;/th&gt;&lt;/tr&gt;&lt;/thead&gt;&lt;tbody&gt;&lt;tr&gt;&lt;td&gt;&lt;strong&gt;Dual Write (Anti-Pattern)&lt;/strong&gt;&lt;/td&gt;&lt;td&gt;Very Low (Partial failure prone)&lt;/td&gt;&lt;td&gt;Low&lt;/td&gt;&lt;td&gt;Low Latency (High Risk)&lt;/td&gt;&lt;/tr&gt;&lt;tr&gt;&lt;td&gt;&lt;strong&gt;Two-Phase Commit (2PC)&lt;/strong&gt;&lt;/td&gt;&lt;td&gt;High (Strict synchronous)&lt;/td&gt;&lt;td&gt;Very High&lt;/td&gt;&lt;td&gt;High Latency (Blocking)&lt;/td&gt;&lt;/tr&gt;&lt;tr&gt;&lt;td&gt;&lt;strong&gt;Transactional Outbox&lt;/strong&gt;&lt;/td&gt;&lt;td&gt;Guaranteed Eventual Consistency&lt;/td&gt;&lt;td&gt;Medium&lt;/td&gt;&lt;td&gt;Low Latency (Asynchronous)&lt;/td&gt;&lt;/tr&gt;&lt;/tbody&gt;&lt;/table&gt;&lt;/section&gt;
&lt;p&gt;This matrix shows clearly that when we want the best balance between system complexity and operational latency, the Transactional Outbox Pattern provides the most reliable, production-ready solution.&lt;/p&gt;
&lt;h2 id=&quot;8-summary-and-production-decision-rules&quot;&gt;8. Summary and Production Decision Rules&lt;/h2&gt;
&lt;p&gt;We have explored the engineering principles behind reliable distributed data, and now it is time to apply them to your daily system design decisions. Keep in mind that you do not need to use this pattern everywhere. Follow these production decision rules to guide your architectural choices:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;
&lt;p&gt;&lt;strong&gt;When to use the Outbox Pattern:&lt;/strong&gt; Use this pattern whenever you are handling critical business transactions where losing data or having inconsistent states is unacceptable. If you are building systems for financial transactions, payment processing, order placement, or inventory management, implementing a Transactional Outbox and idempotent consumers is mandatory.&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;&lt;strong&gt;When simple event publishing is enough:&lt;/strong&gt; If you are only publishing events for analytics tracking, general user activity logging, or non-critical background notifications where dropping or duplicating a few messages will not hurt the business, you can publish directly to the broker. There is no need to add the engineering complexity of an outbox table for non-critical data.&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;&lt;strong&gt;The Architect Mindset Shift:&lt;/strong&gt; Junior and mid-level developers often write code assuming their networks and servers will work perfectly 100% of the time. A senior architect writes code assuming by default that networks will partition, databases will experience slowdowns, and brokers will deliver duplicate messages. Shifting your mindset toward expecting failure is what moves you from building basic applications to designing resilient, fault-tolerant distributed systems.&lt;/p&gt;
&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;When you understand these low-level mechanics and implement them cleanly in your production architecture, your systems will handle massive traffic spikes and unexpected infrastructure failures with complete reliability.&lt;/p&gt;</content:encoded><category>System Design</category><category>Deep Dive</category><category>Distributed Systems</category><category>Microservices</category><category>Transactional Outbox</category><category>Idempotency</category><category>Kafka</category><category>System Architecture</category><category>Under the hood</category></item><item><title>How to Block AI Crawlers with Cloudflare WAF Without Losing SEO Traffic</title><link>https://www.rafeuddaraj.me/blog/block-ai-crawlers-cloudflare-waf-guide/</link><guid isPermaLink="true">https://www.rafeuddaraj.me/blog/block-ai-crawlers-cloudflare-waf-guide/</guid><description>A step-by-step developer guide on using Cloudflare WAF custom rules and cf.client.bot to block AI web scrapers while preventing Google Search Console 403 errors.</description><pubDate>Sun, 12 Jul 2026 20:25:23 GMT</pubDate><content:encoded>&lt;p&gt;These days, AI scrapers and large language model crawlers, like ChatGPT-User, ClaudeBot, and Perplexity, are constantly scraping entire websites without permission. This drains your server resources and wastes your bandwidth, while your website receives zero organic traffic or credit in return. To solve this, many developers quickly set up a blanket custom rule inside the Cloudflare WAF dashboard. The problem with this rough approach is that it often accidentally blocks legitimate SEO crawlers, like Googlebot and Bingbot, along with essential indexing files such as your &lt;code&gt;/sitemap.xml&lt;/code&gt;. When this happens, Google Search Console throws a &lt;code&gt;General HTTP error: 403&lt;/code&gt;, and your organic search rankings can drop significantly. Our main goal today is to build a production-grade, resilient Cloudflare WAF rule that blocks unverified AI scrapers and bots while allowing verified search engines and regular visitors to access your site smoothly.&lt;/p&gt;
&lt;p&gt;Before diving into the configuration, you will need to get a few basic tools and permissions ready. First, you must have active Admin or Operator access to your domain&apos;s DNS and WAF dashboard inside Cloudflare. Second, you will need a terminal with &lt;code&gt;curl&lt;/code&gt; installed, or a tool like Postman, along with access to your Google Search Console account for testing. Having a basic understanding of Cloudflare&apos;s Expression Builder and HTTP headers, particularly how the User-Agent header works, will make this setup much easier to follow.&lt;/p&gt;
&lt;p&gt;To understand how edge layer blocking actually works, let us look at a practical real-world analogy. When a request travels toward your server, Cloudflare&apos;s edge network intercepts it before it ever reaches your origin server. Imagine a security guard standing at the front gate of your office building. If you tell the guard, &quot;Do not let anyone in who claims to be a police officer,&quot; and a real police officer arrives showing an official ID badge, the guard would still block them based purely on spoken words. That is exactly what basic User-Agent blocking does. Our solution today teaches the security guard to ignore spoken claims and instead check for an official, verified ID badge, known as &lt;code&gt;cf.client.bot&lt;/code&gt;, to easily separate real search engines from fake AI scrapers.&lt;/p&gt;
&lt;figure&gt;&lt;img src=&quot;https://raw.githubusercontent.com/rafeuddaraj/rafes-blog-assets/refs/heads/block-ai-crawlers-cloudflare-waf-guide/assets/cloudflare-waf-edge-routing.svg&quot; alt=&quot;Cloudflare WAF Edge Routing Architecture&quot; loading=&quot;lazy&quot; decoding=&quot;async&quot; width=&quot;900&quot; height=&quot;550&quot;&gt;&lt;figcaption&gt;Cloudflare WAF Edge Routing Architecture&lt;/figcaption&gt;&lt;/figure&gt;
&lt;p&gt;Let us jump into the step-by-step implementation. For the first step, log in to your Cloudflare dashboard and select your target domain. Navigate to the &lt;strong&gt;Security &gt; Security rules&lt;/strong&gt; section in the left sidebar and click on the &lt;strong&gt;Custom rules&lt;/strong&gt; tab. Click the &lt;strong&gt;Create rule&lt;/strong&gt; button to build a new rule, and give it a clear name like &lt;code&gt;AI Crawl Control - Block Unverified Scrapers&lt;/code&gt;. Make sure to set the proper priority order so that this rule runs before your normal routing rules. For the second step, we will skip the visual Expression Builder and use the Advanced Editor to write code-level logic. Click the blue &lt;strong&gt;Edit expression&lt;/strong&gt; link on the right side of the Expression Preview box. This opens an editor where you can write SQL-like syntax directly.&lt;/p&gt;
&lt;p&gt;In the third step, we will inject the core AI bot blocking logic. Paste the expression below into the editor. This targets the User-Agents of known AI scrapers while keeping your &lt;code&gt;/robots.txt&lt;/code&gt; file excluded from the block, allowing crawlers to read your site&apos;s indexing rules:&lt;/p&gt;
&lt;div class=&quot;expressive-code&quot;&gt;&lt;style&gt;.expressive-code{font-family:var(--ec-uiFontFml);font-size:var(--ec-uiFontSize);font-weight:var(--ec-uiFontWg);line-height:var(--ec-uiLineHt);text-size-adjust:none;-webkit-text-size-adjust:none}.expressive-code *:not(:is(svg, svg *)){all:revert;box-sizing:border-box}.expressive-code pre{display:flex;margin:0;padding:0;border:var(--ec-brdWd) solid var(--ec-brdCol);border-radius:calc(var(--ec-brdRad) + var(--ec-brdWd));background:var(--ec-codeBg)}.expressive-code pre:focus-visible{outline:3px solid var(--ec-focusBrd);outline-offset:-3px}.expressive-code pre &gt; code{all:unset;display:block;flex:1 0 100%;padding:var(--ec-codePadBlk) 0;color:var(--ec-codeFg);font-family:var(--ec-codeFontFml);font-size:var(--ec-codeFontSize);font-weight:var(--ec-codeFontWg);line-height:var(--ec-codeLineHt)}.expressive-code pre{overflow-x:auto}.expressive-code pre.wrap .ec-line .code{white-space:pre-wrap;overflow-wrap:break-word;min-width:min(20ch, var(--ecMaxLine, 20ch))}.expressive-code pre.wrap .ec-line .code span.indent{white-space:pre}.expressive-code pre::-webkit-scrollbar,.expressive-code pre::-webkit-scrollbar-track{background-color:inherit;border-radius:calc(var(--ec-brdRad) + var(--ec-brdWd));border-top-left-radius:0;border-top-right-radius:0}.expressive-code pre::-webkit-scrollbar-thumb{background-color:var(--ec-sbThumbCol);border:4px solid transparent;background-clip:content-box;border-radius:10px}.expressive-code pre::-webkit-scrollbar-thumb:hover{background-color:var(--ec-sbThumbHoverCol)}.expressive-code pre::-webkit-scrollbar-corner{background:transparent}.expressive-code .ec-line{direction:ltr;unicode-bidi:isolate;display:grid;grid-template-areas:&apos;gutter code&apos;;grid-template-columns:auto 1fr;position:relative}.expressive-code .ec-line .gutter{grid-area:gutter;color:var(--ec-gtrFg)}.expressive-code .ec-line .gutter &gt; *{pointer-events:none;user-select:none;-webkit-user-select:none}.expressive-code .ec-line .gutter ~ .code{--ecLineBrdCol:var(--ec-gtrBrdCol)}.expressive-code .ec-line.highlight .gutter{color:var(--ec-gtrHlFg)}.expressive-code .ec-line .code{grid-area:code;position:relative;box-sizing:content-box;padding-inline-start:calc(var(--ecIndent, 0ch) + var(--ec-codePadInl) - var(--ecGtrBrdWd));padding-inline-end:var(--ec-codePadInl);text-indent:calc(var(--ecIndent, 0ch) * -1)}.expressive-code .ec-line .code::before,.expressive-code .ec-line .code::after,.expressive-code .ec-line .code :where(*){text-indent:0}.expressive-code .ec-line .code{--ecGtrBrdWd:var(--ec-gtrBrdWd);border-inline-start:var(--ecGtrBrdWd) solid var(--ecLineBrdCol, transparent)}.expressive-code .sr-only{position:absolute;width:1px;height:1px;padding:0;margin:-1px;overflow:hidden;clip:rect(0, 0, 0, 0);white-space:nowrap;border-width:0}.expressive-code .ec-line.mark{--tmLineBgCol:var(--ec-tm-markBg)}.expressive-code .ec-line.mark .code{--ecLineBrdCol:var(--ec-tm-markBrdCol)}.expressive-code .ec-line.ins{--tmLineBgCol:var(--ec-tm-insBg);--tmLabel:var(--ec-tm-insDiffIndContent)}.expressive-code .ec-line.ins .code{--ecLineBrdCol:var(--ec-tm-insBrdCol)}.expressive-code .ec-line.ins .code::before{color:var(--ec-tm-insDiffIndCol)}.expressive-code .ec-line.del{--tmLineBgCol:var(--ec-tm-delBg);--tmLabel:var(--ec-tm-delDiffIndContent)}.expressive-code .ec-line.del .code{--ecLineBrdCol:var(--ec-tm-delBrdCol)}.expressive-code .ec-line.del .code::before{color:var(--ec-tm-delDiffIndCol)}.expressive-code .ec-line.mark,.expressive-code .ec-line.ins,.expressive-code .ec-line.del{background:var(--tmLineBgCol)}.expressive-code .ec-line.mark .code,.expressive-code .ec-line.ins .code,.expressive-code .ec-line.del .code{--ecGtrBrdWd:var(--ec-tm-lineMarkerAccentWd)}.expressive-code .ec-line.mark .code::before,.expressive-code .ec-line.ins .code::before,.expressive-code .ec-line.del .code::before{display:block;position:absolute;left:0;box-sizing:border-box;content:var(--tmLabel, &apos; &apos;);padding-inline-start:var(--ec-tm-lineDiffIndMargLeft);text-align:center;white-space:pre}.expressive-code .ec-line.mark.tm-label .code::before,.expressive-code .ec-line.ins.tm-label .code::before,.expressive-code .ec-line.del.tm-label .code::before{background:var(--ecLineBrdCol);padding:0 calc(var(--ec-tm-lineMarkerLabelPadInl) + var(--ec-tm-lineMarkerAccentWd)) 0 var(--ec-tm-lineMarkerLabelPadInl);color:var(--ec-tm-lineMarkerLabelCol)}.expressive-code .ec-line mark{--tmInlineBgCol:var(--ec-tm-markBg);--tmInlineBrdCol:var(--ec-tm-markBrdCol)}.expressive-code .ec-line ins{--tmInlineBgCol:var(--ec-tm-insBg);--tmInlineBrdCol:var(--ec-tm-insBrdCol)}.expressive-code .ec-line del{--tmInlineBgCol:var(--ec-tm-delBg);--tmInlineBrdCol:var(--ec-tm-delBrdCol)}.expressive-code .ec-line mark,.expressive-code .ec-line ins,.expressive-code .ec-line del{all:unset;display:inline-block;position:relative;--tmBrdL:var(--ec-tm-inlMarkerBrdWd);--tmBrdR:var(--ec-tm-inlMarkerBrdWd);--tmRadL:var(--ec-tm-inlMarkerBrdRad);--tmRadR:var(--ec-tm-inlMarkerBrdRad);margin-inline:0.025rem;padding-inline:var(--ec-tm-inlMarkerPad);border-radius:var(--tmRadL) var(--tmRadR) var(--tmRadR) var(--tmRadL);background:var(--tmInlineBgCol);background-clip:padding-box}.expressive-code .ec-line mark.open-start,.expressive-code .ec-line ins.open-start,.expressive-code .ec-line del.open-start{margin-inline-start:0;padding-inline-start:0;--tmBrdL:0px;--tmRadL:0}.expressive-code .ec-line mark.open-end,.expressive-code .ec-line ins.open-end,.expressive-code .ec-line del.open-end{margin-inline-end:0;padding-inline-end:0;--tmBrdR:0px;--tmRadR:0}.expressive-code .ec-line mark::before,.expressive-code .ec-line ins::before,.expressive-code .ec-line del::before{content:&apos;&apos;;position:absolute;pointer-events:none;display:inline-block;inset:0;border-radius:var(--tmRadL) var(--tmRadR) var(--tmRadR) var(--tmRadL);border:var(--ec-tm-inlMarkerBrdWd) solid var(--tmInlineBrdCol);border-inline-width:var(--tmBrdL) var(--tmBrdR)}.expressive-code .frame{all:unset;position:relative;display:block;--header-border-radius:calc(var(--ec-brdRad) + var(--ec-brdWd));--tab-border-radius:calc(var(--ec-frm-edTabBrdRad) + var(--ec-brdWd));--button-spacing:0.4rem;--code-background:var(--ec-frm-edBg);border-radius:var(--header-border-radius);box-shadow:var(--ec-frm-frameBoxShdCssVal)}.expressive-code .frame .header{display:none;z-index:1;position:relative;border-radius:var(--header-border-radius) var(--header-border-radius) 0 0}.expressive-code .frame.has-title pre,.expressive-code .frame.has-title code,.expressive-code .frame.is-terminal pre,.expressive-code .frame.is-terminal code{border-top:none;border-top-left-radius:0;border-top-right-radius:0}.expressive-code .frame .title:empty:before{content:&apos;\a0&apos;}.expressive-code .frame.has-title:not(.is-terminal){--button-spacing:calc(1.9rem + 2 * (var(--ec-uiPadBlk) + var(--ec-frm-edActTabIndHt)))}.expressive-code .frame.has-title:not(.is-terminal) .title{position:relative;color:var(--ec-frm-edActTabFg);background:var(--ec-frm-edActTabBg);background-clip:padding-box;margin-block-start:var(--ec-frm-edTabsMargBlkStart);padding:calc(var(--ec-uiPadBlk) + var(--ec-frm-edActTabIndHt)) var(--ec-uiPadInl);border:var(--ec-brdWd) solid var(--ec-frm-edActTabBrdCol);border-radius:var(--tab-border-radius) var(--tab-border-radius) 0 0;border-bottom:none;overflow:hidden}.expressive-code .frame.has-title:not(.is-terminal) .title::after{content:&apos;&apos;;position:absolute;pointer-events:none;inset:0;border-top:var(--ec-frm-edActTabIndHt) solid var(--ec-frm-edActTabIndTopCol);border-bottom:var(--ec-frm-edActTabIndHt) solid var(--ec-frm-edActTabIndBtmCol)}.expressive-code .frame.has-title:not(.is-terminal) .header{display:flex;background:linear-gradient(to top, var(--ec-frm-edTabBarBrdBtmCol) var(--ec-brdWd), transparent var(--ec-brdWd)),linear-gradient(var(--ec-frm-edTabBarBg), var(--ec-frm-edTabBarBg));background-repeat:no-repeat;padding-inline-start:var(--ec-frm-edTabsMargInlStart)}.expressive-code .frame.has-title:not(.is-terminal) .header::before{content:&apos;&apos;;position:absolute;pointer-events:none;inset:0;border:var(--ec-brdWd) solid var(--ec-frm-edTabBarBrdCol);border-radius:inherit;border-bottom:none}.expressive-code .frame.is-terminal{--button-spacing:calc(1.9rem + var(--ec-brdWd) + 2 * var(--ec-uiPadBlk));--code-background:var(--ec-frm-trmBg)}.expressive-code .frame.is-terminal .header{display:flex;align-items:center;justify-content:center;padding-block:var(--ec-uiPadBlk);padding-block-end:calc(var(--ec-uiPadBlk) + var(--ec-brdWd));position:relative;font-weight:500;letter-spacing:0.025ch;color:var(--ec-frm-trmTtbFg);background:var(--ec-frm-trmTtbBg);border:var(--ec-brdWd) solid var(--ec-brdCol);border-bottom:none}.expressive-code .frame.is-terminal .header::before{content:&apos;&apos;;position:absolute;pointer-events:none;left:var(--ec-uiPadInl);width:2.1rem;height:0.56rem;line-height:0;background-color:var(--ec-frm-trmTtbDotsFg);opacity:var(--ec-frm-trmTtbDotsOpa);-webkit-mask-image:var(--ec-frm-trmIcon);-webkit-mask-repeat:no-repeat;mask-image:var(--ec-frm-trmIcon);mask-repeat:no-repeat}.expressive-code .frame.is-terminal .header::after{content:&apos;&apos;;position:absolute;pointer-events:none;inset:0;border-bottom:var(--ec-brdWd) solid var(--ec-frm-trmTtbBrdBtmCol)}.expressive-code .frame pre{background:var(--code-background)}.expressive-code .copy{display:flex;gap:0.25rem;flex-direction:row;position:absolute;inset-block-start:calc(var(--ec-brdWd) + var(--button-spacing));inset-inline-end:calc(var(--ec-brdWd) + var(--ec-uiPadInl) / 2)}@media (scripting: none){.expressive-code .copy{display:none}}.expressive-code .copy{direction:ltr;unicode-bidi:isolate}.expressive-code .copy button{position:relative;align-self:flex-end;margin:0;padding:0;border:none;border-radius:0.2rem;z-index:1;cursor:pointer;transition-property:opacity, background, border-color;transition-duration:0.2s;transition-timing-function:cubic-bezier(0.25, 0.46, 0.45, 0.94);width:2.5rem;height:2.5rem;background:var(--code-background);opacity:0.75}.expressive-code .copy button div{position:absolute;inset:0;border-radius:inherit;background:var(--ec-frm-inlBtnBg);opacity:var(--ec-frm-inlBtnBgIdleOpa);transition-property:inherit;transition-duration:inherit;transition-timing-function:inherit}.expressive-code .copy button::before{content:&apos;&apos;;position:absolute;pointer-events:none;inset:0;border-radius:inherit;border:var(--ec-brdWd) solid var(--ec-frm-inlBtnBrd);opacity:var(--ec-frm-inlBtnBrdOpa)}.expressive-code .copy button::after{content:&apos;&apos;;position:absolute;pointer-events:none;inset:0;background-color:var(--ec-frm-inlBtnFg);-webkit-mask-image:var(--ec-frm-copyIcon);-webkit-mask-repeat:no-repeat;mask-image:var(--ec-frm-copyIcon);mask-repeat:no-repeat;margin:0.475rem;line-height:0}.expressive-code .copy button:hover,.expressive-code .copy button:focus:focus-visible{opacity:1}.expressive-code .copy button:hover div,.expressive-code .copy button:focus:focus-visible div{opacity:var(--ec-frm-inlBtnBgHoverOrFocusOpa)}.expressive-code .copy button:active{opacity:1}.expressive-code .copy button:active div{opacity:var(--ec-frm-inlBtnBgActOpa)}.expressive-code .copy .feedback{--tooltip-arrow-size:0.35rem;--tooltip-bg:var(--ec-frm-tooltipSuccessBg);color:var(--ec-frm-tooltipSuccessFg);pointer-events:none;user-select:none;-webkit-user-select:none;position:relative;align-self:center;background-color:var(--tooltip-bg);z-index:99;padding:0.125rem 0.75rem;border-radius:0.2rem;margin-inline-end:var(--tooltip-arrow-size);opacity:0;transition-property:opacity, transform;transition-duration:0.2s;transition-timing-function:ease-in-out;transform:translate3d(0, 0.25rem, 0)}.expressive-code .copy .feedback::after{content:&apos;&apos;;position:absolute;pointer-events:none;top:calc(50% - var(--tooltip-arrow-size));inset-inline-end:calc(-2 * (var(--tooltip-arrow-size) - 0.5px));border:var(--tooltip-arrow-size) solid transparent;border-inline-start-color:var(--tooltip-bg)}.expressive-code .copy .feedback.show{opacity:1;transform:translate3d(0, 0, 0)}@media (hover: hover){.expressive-code{}.expressive-code .copy button{opacity:0;width:2rem;height:2rem}.expressive-code .frame:hover .copy button:not(:hover),.expressive-code .frame:focus-within :focus-visible ~ .copy button:not(:hover),.expressive-code .frame .copy .feedback.show ~ button:not(:hover){opacity:0.75}}.expressive-code :nth-child(1 of .ec-line) .code{padding-inline-end:calc(2rem + var(--ec-codePadInl))}:root{--ec-brdRad:0.75rem;--ec-brdWd:1.5px;--ec-brdCol:var(--code-line);--ec-codeFontFml:var(--font-code);--ec-codeFontSize:0.875rem;--ec-codeFontWg:400;--ec-codeLineHt:1.75;--ec-codePadBlk:1rem;--ec-codePadInl:1.125rem;--ec-codeBg:var(--code-bg);--ec-codeFg:#e6edf3;--ec-codeSelBg:#264f78;--ec-gtrFg:#6e7681;--ec-gtrBrdCol:#6e768133;--ec-gtrBrdWd:1.5px;--ec-gtrHlFg:#e6edf3;--ec-uiFontFml:var(--font-mono);--ec-uiFontSize:0.75rem;--ec-uiFontWg:400;--ec-uiLineHt:1.65;--ec-uiPadBlk:0.25rem;--ec-uiPadInl:1rem;--ec-uiSelBg:#6e768166;--ec-uiSelFg:#e6edf3;--ec-focusBrd:#1f6feb;--ec-sbThumbCol:#8b949e33;--ec-sbThumbHoverCol:#8b949e3d;--ec-tm-lineMarkerAccentMarg:0rem;--ec-tm-lineMarkerAccentWd:0.15rem;--ec-tm-lineMarkerLabelPadInl:0.2rem;--ec-tm-lineMarkerLabelCol:white;--ec-tm-lineDiffIndMargLeft:0.3rem;--ec-tm-inlMarkerBrdWd:1.5px;--ec-tm-inlMarkerBrdRad:0.2rem;--ec-tm-inlMarkerPad:0.15rem;--ec-tm-insDiffIndContent:&apos;+&apos;;--ec-tm-delDiffIndContent:&apos;-&apos;;--ec-tm-markBg:#264a8980;--ec-tm-markBrdCol:#5570b3d0;--ec-tm-insBg:#26561c80;--ec-tm-insBrdCol:#4e7e41d0;--ec-tm-insDiffIndCol:#7eb070d0;--ec-tm-delBg:#81322b80;--ec-tm-delBrdCol:#ae594fd0;--ec-tm-delDiffIndCol:#e68a7ed0;--ec-frm-shdCol:#0000005b;--ec-frm-frameBoxShdCssVal:none;--ec-frm-edActTabBg:var(--code-bg);--ec-frm-edActTabFg:var(--code-muted);--ec-frm-edActTabBrdCol:transparent;--ec-frm-edActTabIndHt:1.5px;--ec-frm-edActTabIndTopCol:transparent;--ec-frm-edActTabIndBtmCol:#0d1117;--ec-frm-edTabsMargInlStart:0;--ec-frm-edTabsMargBlkStart:0;--ec-frm-edTabBrdRad:0.75rem;--ec-frm-edTabBarBg:var(--code-bg);--ec-frm-edTabBarBrdCol:var(--code-line);--ec-frm-edTabBarBrdBtmCol:var(--code-line);--ec-frm-edBg:var(--code-bg);--ec-frm-trmTtbFg:var(--code-muted);--ec-frm-trmTtbDotsFg:var(--code-muted);--ec-frm-trmTtbDotsOpa:0.15;--ec-frm-trmTtbBg:var(--code-bg);--ec-frm-trmTtbBrdBtmCol:var(--code-line);--ec-frm-trmBg:var(--code-bg);--ec-frm-inlBtnBg:var(--code-ink);--ec-frm-inlBtnBgIdleOpa:0;--ec-frm-inlBtnBgHoverOrFocusOpa:0.2;--ec-frm-inlBtnBgActOpa:0.3;--ec-frm-inlBtnFg:var(--code-ink);--ec-frm-inlBtnBrd:var(--code-line);--ec-frm-inlBtnBrdOpa:0.4;--ec-frm-tooltipSuccessBg:var(--color-emerald);--ec-frm-tooltipSuccessFg:var(--color-bg);--ec-frm-copyIcon:url(&quot;data:image/svg+xml,%3Csvg%20xmlns%3D&apos;http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg&apos;%20viewBox%3D&apos;0%200%2024%2024&apos;%20fill%3D&apos;none&apos;%20stroke%3D&apos;black&apos;%20stroke-width%3D&apos;1.75&apos;%3E%3Cpath%20d%3D&apos;M3%2019a2%202%200%200%201-1-2V2a2%202%200%200%201%201-1h13a2%202%200%200%201%202%201&apos;%2F%3E%3Crect%20x%3D&apos;6&apos;%20y%3D&apos;5&apos;%20width%3D&apos;16&apos;%20height%3D&apos;18&apos;%20rx%3D&apos;1.5&apos;%20ry%3D&apos;1.5&apos;%2F%3E%3C%2Fsvg%3E&quot;);--ec-frm-trmIcon:url(&quot;data:image/svg+xml,%3Csvg%20xmlns%3D&apos;http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg&apos;%20viewBox%3D&apos;0%200%2060%2016&apos;%20preserveAspectRatio%3D&apos;xMidYMid%20meet&apos;%3E%3Ccircle%20cx%3D&apos;8&apos;%20cy%3D&apos;8&apos;%20r%3D&apos;8&apos;%2F%3E%3Ccircle%20cx%3D&apos;30&apos;%20cy%3D&apos;8&apos;%20r%3D&apos;8&apos;%2F%3E%3Ccircle%20cx%3D&apos;52&apos;%20cy%3D&apos;8&apos;%20r%3D&apos;8&apos;%2F%3E%3C%2Fsvg%3E&quot;)}.expressive-code .ec-line :where(span[style^=&apos;--&apos;]:not([class])){color:var(--0, inherit);background-color:var(--0bg, transparent);font-style:var(--0fs, inherit);font-weight:var(--0fw, inherit);text-decoration:var(--0td, inherit)}&lt;/style&gt;&lt;script type=&quot;module&quot; src=&quot;/_astro/ec.0vx5m.js&quot;&gt;&lt;/script&gt;&lt;figure class=&quot;frame has-title&quot;&gt;&lt;figcaption class=&quot;header&quot;&gt;&lt;span class=&quot;title&quot;&gt;SQL&lt;/span&gt;&lt;/figcaption&gt;&lt;pre data-language=&quot;sql&quot;&gt;&lt;code&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;(&lt;/span&gt;&lt;span style=&quot;--0:#79C0FF&quot;&gt;http&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;.&lt;/span&gt;&lt;span style=&quot;--0:#79C0FF&quot;&gt;request&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;.&lt;/span&gt;&lt;span style=&quot;--0:#79C0FF&quot;&gt;uri&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;.&lt;/span&gt;&lt;span style=&quot;--0:#79C0FF&quot;&gt;path&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; ne &lt;/span&gt;&lt;span style=&quot;--0:#A5D6FF&quot;&gt;&quot;/robots.txt&quot;&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; &lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;and&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; (&lt;/span&gt;&lt;span style=&quot;--0:#79C0FF&quot;&gt;http&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;.&lt;/span&gt;&lt;span style=&quot;--0:#79C0FF&quot;&gt;user_agent&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; contains &lt;/span&gt;&lt;span style=&quot;--0:#A5D6FF&quot;&gt;&quot;Applebot&quot;&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; &lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;or&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; &lt;/span&gt;&lt;span style=&quot;--0:#79C0FF&quot;&gt;http&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;.&lt;/span&gt;&lt;span style=&quot;--0:#79C0FF&quot;&gt;user_agent&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; contains &lt;/span&gt;&lt;span style=&quot;--0:#A5D6FF&quot;&gt;&quot;archive.org_bot&quot;&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; &lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;or&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; &lt;/span&gt;&lt;span style=&quot;--0:#79C0FF&quot;&gt;http&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;.&lt;/span&gt;&lt;span style=&quot;--0:#79C0FF&quot;&gt;user_agent&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; contains &lt;/span&gt;&lt;span style=&quot;--0:#A5D6FF&quot;&gt;&quot;ChatGPT-User&quot;&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; &lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;or&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; &lt;/span&gt;&lt;span style=&quot;--0:#79C0FF&quot;&gt;http&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;.&lt;/span&gt;&lt;span style=&quot;--0:#79C0FF&quot;&gt;user_agent&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; contains &lt;/span&gt;&lt;span style=&quot;--0:#A5D6FF&quot;&gt;&quot;ClaudeBot&quot;&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; &lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;or&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; &lt;/span&gt;&lt;span style=&quot;--0:#79C0FF&quot;&gt;http&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;.&lt;/span&gt;&lt;span style=&quot;--0:#79C0FF&quot;&gt;user_agent&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; contains &lt;/span&gt;&lt;span style=&quot;--0:#A5D6FF&quot;&gt;&quot;DuckAssistBot&quot;&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; &lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;or&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; &lt;/span&gt;&lt;span style=&quot;--0:#79C0FF&quot;&gt;http&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;.&lt;/span&gt;&lt;span style=&quot;--0:#79C0FF&quot;&gt;user_agent&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; contains &lt;/span&gt;&lt;span style=&quot;--0:#A5D6FF&quot;&gt;&quot;MistralAI-User&quot;&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; &lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;or&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; &lt;/span&gt;&lt;span style=&quot;--0:#79C0FF&quot;&gt;http&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;.&lt;/span&gt;&lt;span style=&quot;--0:#79C0FF&quot;&gt;user_agent&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; contains &lt;/span&gt;&lt;span style=&quot;--0:#A5D6FF&quot;&gt;&quot;OAI-SearchBot&quot;&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; &lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;or&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; &lt;/span&gt;&lt;span style=&quot;--0:#79C0FF&quot;&gt;http&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;.&lt;/span&gt;&lt;span style=&quot;--0:#79C0FF&quot;&gt;user_agent&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; contains &lt;/span&gt;&lt;span style=&quot;--0:#A5D6FF&quot;&gt;&quot;Perplexity-User&quot;&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; &lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;or&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; &lt;/span&gt;&lt;span style=&quot;--0:#79C0FF&quot;&gt;http&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;.&lt;/span&gt;&lt;span style=&quot;--0:#79C0FF&quot;&gt;user_agent&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; contains &lt;/span&gt;&lt;span style=&quot;--0:#A5D6FF&quot;&gt;&quot;PerplexityBot&quot;&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;))&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;/code&gt;&lt;/pre&gt;&lt;div class=&quot;copy&quot;&gt;&lt;div aria-live=&quot;polite&quot;&gt;&lt;/div&gt;&lt;button title=&quot;Copy to clipboard&quot; data-copied=&quot;Copied!&quot; data-code=&quot;(http.request.uri.path ne &amp;#x22;/robots.txt&amp;#x22; and (http.user_agent contains &amp;#x22;Applebot&amp;#x22; or http.user_agent contains &amp;#x22;archive.org_bot&amp;#x22; or http.user_agent contains &amp;#x22;ChatGPT-User&amp;#x22; or http.user_agent contains &amp;#x22;ClaudeBot&amp;#x22; or http.user_agent contains &amp;#x22;DuckAssistBot&amp;#x22; or http.user_agent contains &amp;#x22;MistralAI-User&amp;#x22; or http.user_agent contains &amp;#x22;OAI-SearchBot&amp;#x22; or http.user_agent contains &amp;#x22;Perplexity-User&amp;#x22; or http.user_agent contains &amp;#x22;PerplexityBot&amp;#x22;))&quot;&gt;&lt;div&gt;&lt;/div&gt;&lt;/button&gt;&lt;/div&gt;&lt;/figure&gt;&lt;/div&gt;
&lt;p&gt;For the fourth step, we will upgrade this rule with verified bot protection. Relying solely on User-Agent strings is risky because clever scrapers can easily spoof their header to look like Googlebot. On the other hand, trying to manually whitelist Googlebot leaves room for human error. To fix this, we will integrate Cloudflare&apos;s native &lt;code&gt;cf.client.bot&lt;/code&gt; field. Cloudflare automatically uses reverse DNS lookups and IP reputation to verify legitimate search engines behind the scenes. Add &lt;code&gt;not cf.client.bot and&lt;/code&gt; to the beginning of your expression so the final code looks like this:&lt;/p&gt;
&lt;div class=&quot;expressive-code&quot;&gt;&lt;figure class=&quot;frame has-title&quot;&gt;&lt;figcaption class=&quot;header&quot;&gt;&lt;span class=&quot;title&quot;&gt;SQL&lt;/span&gt;&lt;/figcaption&gt;&lt;pre data-language=&quot;sql&quot;&gt;&lt;code&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;(&lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;not&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; &lt;/span&gt;&lt;span style=&quot;--0:#79C0FF&quot;&gt;cf&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;.&lt;/span&gt;&lt;span style=&quot;--0:#79C0FF&quot;&gt;client&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;.bot &lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;and&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; &lt;/span&gt;&lt;span style=&quot;--0:#79C0FF&quot;&gt;http&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;.&lt;/span&gt;&lt;span style=&quot;--0:#79C0FF&quot;&gt;request&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;.&lt;/span&gt;&lt;span style=&quot;--0:#79C0FF&quot;&gt;uri&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;.&lt;/span&gt;&lt;span style=&quot;--0:#79C0FF&quot;&gt;path&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; ne &lt;/span&gt;&lt;span style=&quot;--0:#A5D6FF&quot;&gt;&quot;/robots.txt&quot;&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; &lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;and&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; (&lt;/span&gt;&lt;span style=&quot;--0:#79C0FF&quot;&gt;http&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;.&lt;/span&gt;&lt;span style=&quot;--0:#79C0FF&quot;&gt;user_agent&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; contains &lt;/span&gt;&lt;span style=&quot;--0:#A5D6FF&quot;&gt;&quot;Applebot&quot;&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; &lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;or&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; &lt;/span&gt;&lt;span style=&quot;--0:#79C0FF&quot;&gt;http&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;.&lt;/span&gt;&lt;span style=&quot;--0:#79C0FF&quot;&gt;user_agent&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; contains &lt;/span&gt;&lt;span style=&quot;--0:#A5D6FF&quot;&gt;&quot;archive.org_bot&quot;&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; &lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;or&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; &lt;/span&gt;&lt;span style=&quot;--0:#79C0FF&quot;&gt;http&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;.&lt;/span&gt;&lt;span style=&quot;--0:#79C0FF&quot;&gt;user_agent&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; contains &lt;/span&gt;&lt;span style=&quot;--0:#A5D6FF&quot;&gt;&quot;ChatGPT-User&quot;&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; &lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;or&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; &lt;/span&gt;&lt;span style=&quot;--0:#79C0FF&quot;&gt;http&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;.&lt;/span&gt;&lt;span style=&quot;--0:#79C0FF&quot;&gt;user_agent&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; contains &lt;/span&gt;&lt;span style=&quot;--0:#A5D6FF&quot;&gt;&quot;ClaudeBot&quot;&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; &lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;or&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; &lt;/span&gt;&lt;span style=&quot;--0:#79C0FF&quot;&gt;http&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;.&lt;/span&gt;&lt;span style=&quot;--0:#79C0FF&quot;&gt;user_agent&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; contains &lt;/span&gt;&lt;span style=&quot;--0:#A5D6FF&quot;&gt;&quot;DuckAssistBot&quot;&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; &lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;or&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; &lt;/span&gt;&lt;span style=&quot;--0:#79C0FF&quot;&gt;http&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;.&lt;/span&gt;&lt;span style=&quot;--0:#79C0FF&quot;&gt;user_agent&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; contains &lt;/span&gt;&lt;span style=&quot;--0:#A5D6FF&quot;&gt;&quot;MistralAI-User&quot;&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; &lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;or&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; &lt;/span&gt;&lt;span style=&quot;--0:#79C0FF&quot;&gt;http&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;.&lt;/span&gt;&lt;span style=&quot;--0:#79C0FF&quot;&gt;user_agent&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; contains &lt;/span&gt;&lt;span style=&quot;--0:#A5D6FF&quot;&gt;&quot;OAI-SearchBot&quot;&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; &lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;or&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; &lt;/span&gt;&lt;span style=&quot;--0:#79C0FF&quot;&gt;http&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;.&lt;/span&gt;&lt;span style=&quot;--0:#79C0FF&quot;&gt;user_agent&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; contains &lt;/span&gt;&lt;span style=&quot;--0:#A5D6FF&quot;&gt;&quot;Perplexity-User&quot;&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; &lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;or&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; &lt;/span&gt;&lt;span style=&quot;--0:#79C0FF&quot;&gt;http&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;.&lt;/span&gt;&lt;span style=&quot;--0:#79C0FF&quot;&gt;user_agent&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; contains &lt;/span&gt;&lt;span style=&quot;--0:#A5D6FF&quot;&gt;&quot;PerplexityBot&quot;&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;))&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;/code&gt;&lt;/pre&gt;&lt;div class=&quot;copy&quot;&gt;&lt;div aria-live=&quot;polite&quot;&gt;&lt;/div&gt;&lt;button title=&quot;Copy to clipboard&quot; data-copied=&quot;Copied!&quot; data-code=&quot;(not cf.client.bot and http.request.uri.path ne &amp;#x22;/robots.txt&amp;#x22; and (http.user_agent contains &amp;#x22;Applebot&amp;#x22; or http.user_agent contains &amp;#x22;archive.org_bot&amp;#x22; or http.user_agent contains &amp;#x22;ChatGPT-User&amp;#x22; or http.user_agent contains &amp;#x22;ClaudeBot&amp;#x22; or http.user_agent contains &amp;#x22;DuckAssistBot&amp;#x22; or http.user_agent contains &amp;#x22;MistralAI-User&amp;#x22; or http.user_agent contains &amp;#x22;OAI-SearchBot&amp;#x22; or http.user_agent contains &amp;#x22;Perplexity-User&amp;#x22; or http.user_agent contains &amp;#x22;PerplexityBot&amp;#x22;))&quot;&gt;&lt;div&gt;&lt;/div&gt;&lt;/button&gt;&lt;/div&gt;&lt;/figure&gt;&lt;/div&gt;
&lt;p&gt;Finally, select &lt;strong&gt;Block&lt;/strong&gt; in the Action section at the bottom and click the &lt;strong&gt;Deploy&lt;/strong&gt; button to make your new rule live.&lt;/p&gt;
&lt;div class=&quot;callout&quot; role=&quot;note&quot; data-type=&quot;note&quot;&gt;
&lt;p class=&quot;callout-title&quot;&gt;Important&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Why should you use &lt;code&gt;not cf.client.bot&lt;/code&gt;?&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;If an unverified scraper hits your server using &lt;code&gt;Googlebot&lt;/code&gt; in its User-Agent header, Cloudflare checks the backend to see if the IP address genuinely belongs to Google. If it does not match, &lt;code&gt;cf.client.bot&lt;/code&gt; returns false, and the scraper is blocked instantly. This keeps your website completely safe from User-Agent spoofing attacks.&lt;/p&gt;
&lt;/div&gt;
&lt;p&gt;Now that your deployment is live, it is time for verification and testing. First, open your terminal and send a test request to your site using a fake AI bot User-Agent. You should immediately receive a &lt;strong&gt;403 Forbidden&lt;/strong&gt; response:&lt;/p&gt;
&lt;div class=&quot;expressive-code&quot;&gt;&lt;figure class=&quot;frame is-terminal has-title&quot;&gt;&lt;figcaption class=&quot;header&quot;&gt;&lt;span class=&quot;title&quot;&gt;Terminal&lt;/span&gt;&lt;/figcaption&gt;&lt;pre data-language=&quot;bash&quot;&gt;&lt;code&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span style=&quot;--0:#FFA657&quot;&gt;curl&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; &lt;/span&gt;&lt;span style=&quot;--0:#79C0FF&quot;&gt;-I&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; &lt;/span&gt;&lt;span style=&quot;--0:#79C0FF&quot;&gt;-A&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; &lt;/span&gt;&lt;span style=&quot;--0:#A5D6FF&quot;&gt;&quot;Mozilla/5.0 AppleWebKit/537.36 (KHTML, like Gecko); compatible; ChatGPT-User/1.0; +https://openai.com/bot&quot;&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; &lt;/span&gt;&lt;span style=&quot;--0:#A5D6FF&quot;&gt;https://yourdomain.com/sitemap.xml&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;/code&gt;&lt;/pre&gt;&lt;div class=&quot;copy&quot;&gt;&lt;div aria-live=&quot;polite&quot;&gt;&lt;/div&gt;&lt;button title=&quot;Copy to clipboard&quot; data-copied=&quot;Copied!&quot; data-code=&quot;curl -I -A &amp;#x22;Mozilla/5.0 AppleWebKit/537.36 (KHTML, like Gecko); compatible; ChatGPT-User/1.0; +https://openai.com/bot&amp;#x22; https://yourdomain.com/sitemap.xml&quot;&gt;&lt;div&gt;&lt;/div&gt;&lt;/button&gt;&lt;/div&gt;&lt;/figure&gt;&lt;/div&gt;
&lt;p&gt;Next, test the same URL using a normal browser User-Agent. This time, you should see a successful &lt;strong&gt;200 OK&lt;/strong&gt; status code:&lt;/p&gt;
&lt;div class=&quot;expressive-code&quot;&gt;&lt;figure class=&quot;frame is-terminal has-title&quot;&gt;&lt;figcaption class=&quot;header&quot;&gt;&lt;span class=&quot;title&quot;&gt;Terminal&lt;/span&gt;&lt;/figcaption&gt;&lt;pre data-language=&quot;bash&quot;&gt;&lt;code&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span style=&quot;--0:#FFA657&quot;&gt;curl&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; &lt;/span&gt;&lt;span style=&quot;--0:#79C0FF&quot;&gt;-I&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; &lt;/span&gt;&lt;span style=&quot;--0:#79C0FF&quot;&gt;-A&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; &lt;/span&gt;&lt;span style=&quot;--0:#A5D6FF&quot;&gt;&quot;Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36&quot;&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; &lt;/span&gt;&lt;span style=&quot;--0:#A5D6FF&quot;&gt;https://yourdomain.com&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;/code&gt;&lt;/pre&gt;&lt;div class=&quot;copy&quot;&gt;&lt;div aria-live=&quot;polite&quot;&gt;&lt;/div&gt;&lt;button title=&quot;Copy to clipboard&quot; data-copied=&quot;Copied!&quot; data-code=&quot;curl -I -A &amp;#x22;Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36&amp;#x22; https://yourdomain.com&quot;&gt;&lt;div&gt;&lt;/div&gt;&lt;/button&gt;&lt;/div&gt;&lt;/figure&gt;&lt;/div&gt;
&lt;p&gt;Second, go back to your Cloudflare dashboard and navigate to &lt;strong&gt;Security &gt; Events&lt;/strong&gt;. Check the activity logs to verify that your new rule is triggering correctly. Confirm the IP addresses, User-Agents, and Action status (which should show as Block) for the intercepted requests. Third, go directly to Google Search Console and click on your site&apos;s &lt;strong&gt;Sitemaps&lt;/strong&gt; section. Resubmit or resync your &lt;code&gt;/sitemap.xml&lt;/code&gt; file. Within a few moments, you should see the status update to &lt;strong&gt;Success&lt;/strong&gt; without any frustrating 403 errors.&lt;/p&gt;
&lt;div class=&quot;callout&quot; role=&quot;note&quot; data-type=&quot;warning&quot;&gt;
&lt;p class=&quot;callout-title&quot;&gt;Warning&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Common Debugging Tip:&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;If you still see a 403 error in Google Search Console after deploying the rule, double-check your syntax to ensure you did not accidentally leave out &lt;code&gt;not cf.client.bot&lt;/code&gt;. Also, check if any older firewall policies or rate-limiting rules are actively blocking Google&apos;s IPs.&lt;/p&gt;
&lt;/div&gt;
&lt;p&gt;Finally, keep in mind a few operational trade-offs before applying this rule. If your users ever paste a direct link to your website into an AI chat tool like ChatGPT or Perplexity to summarize or analyze the content, the AI will fail to read it because the crawler will be blocked at the edge. If your business model relies heavily on AI tools reading your direct links, it is better not to enable this block. As you plan for future scaling and maintenance, remember that the AI landscape evolves rapidly, and new bots appear every day. Make it a habit to check your Cloudflare &lt;strong&gt;Security &gt; Events&lt;/strong&gt; logs once a month, and add the User-Agents of any new, unverified scrapers to your WAF expression. You can also explore premium Cloudflare Bot Management features if you need more advanced protection.&lt;/p&gt;</content:encoded><category>Web Security</category><category>Cloudflare</category><category>WAF</category><category>Security</category><category>SEO</category><category>AI Scrapers</category><category>Tutorial</category><category>How-To</category><category>Web Development</category></item><item><title>How Distributed Sagas and Compensating Transactions Actually Work Under the Hood</title><link>https://www.rafeuddaraj.me/blog/distributed-sagas-compensating-transactions-deep-dive/</link><guid isPermaLink="true">https://www.rafeuddaraj.me/blog/distributed-sagas-compensating-transactions-deep-dive/</guid><description>A production engineering guide explaining why Two-Phase Commit is dead in microservice architectures and how Distributed Sagas work. Explore the low-level mechanics of orchestration, choreography, Write-Ahead Log replay, and concurrency anomalies.</description><pubDate>Thu, 09 Jul 2026 16:47:36 GMT</pubDate><content:encoded>&lt;p&gt;When we leave monolithic architectures behind and move to microservices, the hardest reality we face is the complete loss of our database transactions. In a monolith, you have a single database. You can easily rely on ACID properties (Atomicity, Consistency, Isolation, Durability) to keep your data perfectly balanced. But once your system becomes distributed, with each microservice owning its own isolated database, maintaining a global transaction turns into an engineering nightmare.&lt;/p&gt;
&lt;p&gt;Many developers assume they can solve this problem by leaning on the traditional Two-Phase Commit, or 2PC protocol. In high-scale production realities, however, 2PC is a dead architecture. Today, we are going to treat this like a real whiteboard session. We will analyze from the lowest system levels why distributed locking mechanisms fail under load, and explore how to use Distributed Sagas and Compensating Transactions to build a resilient, production-grade state machine.&lt;/p&gt;
&lt;h2 id=&quot;1-the-core-distributed-nightmare-and-why-it-matters&quot;&gt;1. The Core Distributed Nightmare and Why It Matters&lt;/h2&gt;
&lt;p&gt;The biggest weakness of the Two-Phase Commit architecture is its synchronous lock trap. Under the 2PC protocol, a central coordinator tells all participating databases to get ready for a transaction during the Prepare Phase. While this happens, every single database places a distributed lock on its own local records. Those locks do not get released until the coordinator sends the final instructions during the Commit Phase. Imagine you have five microservices in your system. If just one of those services experiences a slight network hiccup and takes 200 milliseconds to respond, every database thread across your entire architecture sits there blocked for that full 200 milliseconds. In a high-throughput system, this blocking behavior drains your database connection pools in seconds, spikes your system latency, and grinds your overall throughput down to zero.&lt;/p&gt;
&lt;p&gt;This is exactly why modern cloud-native architectures completely abandon the strict Isolation (I) property of ACID. Instead, we adopt the BASE model, which stands for Basically Available, Soft state, and Eventual consistency. In a distributed system, maintaining perfect transaction isolation across networks is mathematically and practically impossible. We simply have to accept that the system&apos;s state will remain temporarily out of sync, living in a soft state. However, we design the architecture so that after a specific window of time, all data eventually becomes consistent and balanced across every service.&lt;/p&gt;
&lt;p&gt;This mental shift introduces a dangerous linear execution problem. Let us say you run an e-commerce order chain where data moves from the Order Service to the Payment Service, and finally to the Inventory Service. What happens if the payment succeeds, but the Inventory Service crashes or returns an out-of-stock error right after? In a monolith, you just issue a simple &lt;code&gt;ROLLBACK&lt;/code&gt; command and everything resets. In a microservice mesh, the payment database transaction has already committed, and its previous state is wiped from memory. Because of this downstream failure, your user just got charged, but they will never receive their product. To prevent this silent data corruption, we need to implement a Distributed Saga architecture.&lt;/p&gt;
&lt;h2 id=&quot;2-the-foundational-mental-model-and-analogy&quot;&gt;2. The Foundational Mental Model and Analogy&lt;/h2&gt;
&lt;p&gt;The core concept behind a Distributed Saga is both powerful and logical. Instead of wrapping an entire business process inside a global database lock, we break that process down into a sequential chain of independent local transactions. Each service performs its local work, commits the changes directly to its own database, and then publishes an asynchronous message or event. This event tells the next service in the line to wake up and start its part of the job.&lt;/p&gt;
&lt;p&gt;To see this clearly, let us look at a familiar real-world analogy. Imagine you are booking a multi-city vacation from Dhaka to Paris through a travel agency. The package requires three separate steps: booking a flight, reserving a hotel room, and renting a car. Notice that the travel agent never locks all three company servers at the exact same time. Instead, the agent logs into the airline system first, books the flight, and grabs a confirmation token. Next, they reserve the hotel room. But when they try to rent a car, the system says no vehicles are available. Can the agent simply hack into the airline database and delete the previous booking record? Absolutely not, because that transaction is already finished and committed. What the agent actually does is send a brand new cancellation request to the hotel and the airline to undo the bookings.&lt;/p&gt;
&lt;p&gt;In distributed systems, we call this mental framework an Eventual Consistency boundary. We know that while a transaction is actively running, our system stays in an in-flight state for a few milliseconds or seconds. We design our architecture so that only two outcomes exist: either the entire vacation package gets booked successfully, or every completed step gets systematically reversed until the system returns to its original balanced state.&lt;/p&gt;
&lt;h2 id=&quot;3-structural-typology-orchestration-vs-choreography-under-the-hood&quot;&gt;3. Structural Typology: Orchestration vs Choreography (Under the Hood)&lt;/h2&gt;
&lt;p&gt;When engineering teams implement the saga pattern, they choose between two main architectural models: Orchestration and Choreography. Let us examine how both approaches behave down at the low-level memory and networking layers.&lt;/p&gt;
&lt;p&gt;In the Orchestration model, you rely on a central brain called the Orchestrator Engine. Tools like Temporal or Camunda fit this role well. This engine maintains the entire state machine of your saga workflow inside its own memory and database. When a new order arrives, the orchestrator sends a direct command to the Payment Service. Once the payment succeeds, the response routes back to the orchestrator, which then tells the Inventory Service to deduct the stock.&lt;/p&gt;
&lt;p&gt;Under the hood, this engine relies on a brilliant mechanism known as Event Sourcing. Imagine the orchestrator engine crashes right after the payment succeeds. When the server reboots, how does it know where the transaction left off? The orchestrator never updates its current state in place. Instead, it writes every single step sequentially to an immutable Write-Ahead Log, or event store. It records events like &lt;code&gt;OrderStarted&lt;/code&gt;, &lt;code&gt;PaymentCommandSent&lt;/code&gt;, and &lt;code&gt;PaymentSucceeded&lt;/code&gt;. When the server reboots, it simply replays those event logs from zero. This completely reconstructs the in-memory state machine back to the exact millisecond before the crash occurred.&lt;/p&gt;
&lt;figure&gt;&lt;img src=&quot;https://raw.githubusercontent.com/rafeuddaraj/rafes-blog-assets/refs/heads/distributed-sagas-compensating-transactions-deep-dive/assets/saga-orchestrator-state-flow.svg&quot; alt=&quot;Saga Orchestrator Forward Execution and Backward Recovery State Flow&quot; loading=&quot;lazy&quot; decoding=&quot;async&quot; width=&quot;1000&quot; height=&quot;520&quot;&gt;&lt;figcaption&gt;Saga Orchestrator Forward Execution and Backward Recovery State Flow&lt;/figcaption&gt;&lt;/figure&gt;
&lt;p&gt;The Choreography model takes the opposite path by eliminating the central brain entirely. It is a fully decentralized, event-driven architecture. Here, every microservice listens to specific topics inside a message broker, like Kafka or RabbitMQ. When a service hears an event, it executes its local database transaction and immediately drops a new event back into the broker. For example, the Order Service emits an &lt;code&gt;OrderCreated&lt;/code&gt; event. The Payment Service catches that event, charges the user, and emits a &lt;code&gt;PaymentBilled&lt;/code&gt; event. Finally, the Inventory Service catches the billing event and updates its stock levels.&lt;/p&gt;
&lt;p&gt;However, the choreography model introduces a dangerous trap known as the cyclic dependency loop dilemma. Imagine Service A sends an event to Service B, Service B sends one to Service C, and due to some routing bug or custom business logic, Service C sends an event right back to Service A. Under high traffic loads, this decentralized event chain turns into an infinite loop or distributed deadlock. It quickly floods your broker memory buffers and crashes the messaging infrastructure. Because of this risk, whenever a workflow grows beyond five services, you should always pick the Orchestration model.&lt;/p&gt;
&lt;h2 id=&quot;4-anatomy-of-a-saga-transaction-the-tri-partition-rule&quot;&gt;4. Anatomy of a Saga Transaction: The Tri-Partition Rule&lt;/h2&gt;
&lt;p&gt;A common architectural mistake is treating every local transaction inside a saga chain equally. When you design a robust system, you must split every saga chain into three distinct failure boundaries. We call this framework the Tri-Partition Rule:&lt;/p&gt;
&lt;ol&gt;
&lt;li&gt;
&lt;p&gt;&lt;strong&gt;Compensable Transactions:&lt;/strong&gt; These are the early steps in your saga sequence that you can easily reverse if a downstream failure happens. Placing a temporary hold on a user&apos;s bank balance or reserving items in a warehouse are classic examples. If something breaks later, you just fire a reverse command to roll these actions back.&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;&lt;strong&gt;The Pivot Transaction:&lt;/strong&gt; This is the absolute critical junction of your saga workflow. Think of it as the point of no return. If your pivot transaction succeeds, the saga will never run backward. You lose the ability to perform a backward recovery or rollback. Capturing funds from a third-party payment gateway like Stripe or PayPal is a standard pivot transaction. Once the actual money leaves the customer&apos;s bank account, a simple database rollback cannot magically bring it back.&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;&lt;strong&gt;Retriable Transactions:&lt;/strong&gt; These are all the downstream steps that execute immediately after the pivot transaction finishes. From an architectural standpoint, these steps are never allowed to fail permanently. Examples include sending an email receipt to the user or updating an inventory status from reserved to sold. If the notification service experiences a network drop, the saga does not trigger a rollback. Instead, it uses exponential backoff and retries the step infinitely until the task succeeds. We call this pattern forward recovery.&lt;/p&gt;
&lt;/li&gt;
&lt;/ol&gt;
&lt;h2 id=&quot;5-the-reverse-engine-compensating-transactions-and-recovery-patterns&quot;&gt;5. The Reverse Engine: Compensating Transactions and Recovery Patterns&lt;/h2&gt;
&lt;p&gt;When you run a &lt;code&gt;ROLLBACK&lt;/code&gt; command in a monolithic database, the storage engine simply throws away the uncommitted pages in memory and restores the disk to its previous snapshot. You cannot do this in a microservice architecture. Your local transaction already committed to the database, and other concurrent threads might have read that data. To undo the work, you have to build a semantic rollback mechanism.&lt;/p&gt;
&lt;p&gt;A semantic rollback is a process where you do not delete old data. Instead, you insert a brand new, opposite entry into the database called a Compensating Transaction. This new entry mathematically cancels out the effects of the original operation. For example, if your original local transaction ran &lt;code&gt;UPDATE accounts SET balance = balance - 500 WHERE id = 1&lt;/code&gt;, your compensating transaction must run &lt;code&gt;UPDATE accounts SET balance = balance + 500 WHERE id = 1&lt;/code&gt;. You balance the ledger by matching every debit entry with a complementary credit entry.&lt;/p&gt;
&lt;p&gt;Saga patterns rely on two primary recovery workflows to handle errors:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;
&lt;p&gt;&lt;strong&gt;Backward Recovery Workflow:&lt;/strong&gt; If a step fails before you reach the pivot transaction, the system starts walking backward. Imagine your normal sequence flows through steps &lt;span class=&quot;katex&quot;&gt;&lt;span class=&quot;katex-html&quot; aria-hidden=&quot;true&quot;&gt;&lt;span class=&quot;base&quot;&gt;&lt;span class=&quot;strut&quot; style=&quot;height:0.8333em;vertical-align:-0.15em;&quot;&gt;&lt;/span&gt;&lt;span class=&quot;mord&quot;&gt;&lt;span class=&quot;mord mathnormal&quot; style=&quot;margin-right:0.1389em;&quot;&gt;T&lt;/span&gt;&lt;span class=&quot;msupsub&quot;&gt;&lt;span class=&quot;vlist-t vlist-t2&quot;&gt;&lt;span class=&quot;vlist-r&quot;&gt;&lt;span class=&quot;vlist&quot; style=&quot;height:0.3011em;&quot;&gt;&lt;span style=&quot;top:-2.55em;margin-left:-0.1389em;margin-right:0.05em;&quot;&gt;&lt;span class=&quot;pstrut&quot; style=&quot;height:2.7em;&quot;&gt;&lt;/span&gt;&lt;span class=&quot;sizing reset-size6 size3 mtight&quot;&gt;&lt;span class=&quot;mord mtight&quot;&gt;1&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class=&quot;vlist-s&quot;&gt;​&lt;/span&gt;&lt;/span&gt;&lt;span class=&quot;vlist-r&quot;&gt;&lt;span class=&quot;vlist&quot; style=&quot;height:0.15em;&quot;&gt;&lt;span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class=&quot;mspace&quot; style=&quot;margin-right:0.2778em;&quot;&gt;&lt;/span&gt;&lt;span class=&quot;mrel&quot;&gt;→&lt;/span&gt;&lt;span class=&quot;mspace&quot; style=&quot;margin-right:0.2778em;&quot;&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class=&quot;base&quot;&gt;&lt;span class=&quot;strut&quot; style=&quot;height:0.8333em;vertical-align:-0.15em;&quot;&gt;&lt;/span&gt;&lt;span class=&quot;mord&quot;&gt;&lt;span class=&quot;mord mathnormal&quot; style=&quot;margin-right:0.1389em;&quot;&gt;T&lt;/span&gt;&lt;span class=&quot;msupsub&quot;&gt;&lt;span class=&quot;vlist-t vlist-t2&quot;&gt;&lt;span class=&quot;vlist-r&quot;&gt;&lt;span class=&quot;vlist&quot; style=&quot;height:0.3011em;&quot;&gt;&lt;span style=&quot;top:-2.55em;margin-left:-0.1389em;margin-right:0.05em;&quot;&gt;&lt;span class=&quot;pstrut&quot; style=&quot;height:2.7em;&quot;&gt;&lt;/span&gt;&lt;span class=&quot;sizing reset-size6 size3 mtight&quot;&gt;&lt;span class=&quot;mord mtight&quot;&gt;2&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class=&quot;vlist-s&quot;&gt;​&lt;/span&gt;&lt;/span&gt;&lt;span class=&quot;vlist-r&quot;&gt;&lt;span class=&quot;vlist&quot; style=&quot;height:0.15em;&quot;&gt;&lt;span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class=&quot;mspace&quot; style=&quot;margin-right:0.2778em;&quot;&gt;&lt;/span&gt;&lt;span class=&quot;mrel&quot;&gt;→&lt;/span&gt;&lt;span class=&quot;mspace&quot; style=&quot;margin-right:0.2778em;&quot;&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class=&quot;base&quot;&gt;&lt;span class=&quot;strut&quot; style=&quot;height:0.8333em;vertical-align:-0.15em;&quot;&gt;&lt;/span&gt;&lt;span class=&quot;mord&quot;&gt;&lt;span class=&quot;mord mathnormal&quot; style=&quot;margin-right:0.1389em;&quot;&gt;T&lt;/span&gt;&lt;span class=&quot;msupsub&quot;&gt;&lt;span class=&quot;vlist-t vlist-t2&quot;&gt;&lt;span class=&quot;vlist-r&quot;&gt;&lt;span class=&quot;vlist&quot; style=&quot;height:0.3011em;&quot;&gt;&lt;span style=&quot;top:-2.55em;margin-left:-0.1389em;margin-right:0.05em;&quot;&gt;&lt;span class=&quot;pstrut&quot; style=&quot;height:2.7em;&quot;&gt;&lt;/span&gt;&lt;span class=&quot;sizing reset-size6 size3 mtight&quot;&gt;&lt;span class=&quot;mord mtight&quot;&gt;3&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class=&quot;vlist-s&quot;&gt;​&lt;/span&gt;&lt;/span&gt;&lt;span class=&quot;vlist-r&quot;&gt;&lt;span class=&quot;vlist&quot; style=&quot;height:0.15em;&quot;&gt;&lt;span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;. If step &lt;span class=&quot;katex&quot;&gt;&lt;span class=&quot;katex-html&quot; aria-hidden=&quot;true&quot;&gt;&lt;span class=&quot;base&quot;&gt;&lt;span class=&quot;strut&quot; style=&quot;height:0.8333em;vertical-align:-0.15em;&quot;&gt;&lt;/span&gt;&lt;span class=&quot;mord&quot;&gt;&lt;span class=&quot;mord mathnormal&quot; style=&quot;margin-right:0.1389em;&quot;&gt;T&lt;/span&gt;&lt;span class=&quot;msupsub&quot;&gt;&lt;span class=&quot;vlist-t vlist-t2&quot;&gt;&lt;span class=&quot;vlist-r&quot;&gt;&lt;span class=&quot;vlist&quot; style=&quot;height:0.3011em;&quot;&gt;&lt;span style=&quot;top:-2.55em;margin-left:-0.1389em;margin-right:0.05em;&quot;&gt;&lt;span class=&quot;pstrut&quot; style=&quot;height:2.7em;&quot;&gt;&lt;/span&gt;&lt;span class=&quot;sizing reset-size6 size3 mtight&quot;&gt;&lt;span class=&quot;mord mtight&quot;&gt;3&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class=&quot;vlist-s&quot;&gt;​&lt;/span&gt;&lt;/span&gt;&lt;span class=&quot;vlist-r&quot;&gt;&lt;span class=&quot;vlist&quot; style=&quot;height:0.15em;&quot;&gt;&lt;span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/span&gt; throws an error, the orchestrator fires your compensating commands in reverse order: &lt;span class=&quot;katex&quot;&gt;&lt;span class=&quot;katex-html&quot; aria-hidden=&quot;true&quot;&gt;&lt;span class=&quot;base&quot;&gt;&lt;span class=&quot;strut&quot; style=&quot;height:0.8333em;vertical-align:-0.15em;&quot;&gt;&lt;/span&gt;&lt;span class=&quot;mord&quot;&gt;&lt;span class=&quot;mord mathnormal&quot; style=&quot;margin-right:0.0715em;&quot;&gt;C&lt;/span&gt;&lt;span class=&quot;msupsub&quot;&gt;&lt;span class=&quot;vlist-t vlist-t2&quot;&gt;&lt;span class=&quot;vlist-r&quot;&gt;&lt;span class=&quot;vlist&quot; style=&quot;height:0.3011em;&quot;&gt;&lt;span style=&quot;top:-2.55em;margin-left:-0.0715em;margin-right:0.05em;&quot;&gt;&lt;span class=&quot;pstrut&quot; style=&quot;height:2.7em;&quot;&gt;&lt;/span&gt;&lt;span class=&quot;sizing reset-size6 size3 mtight&quot;&gt;&lt;span class=&quot;mord mtight&quot;&gt;2&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class=&quot;vlist-s&quot;&gt;​&lt;/span&gt;&lt;/span&gt;&lt;span class=&quot;vlist-r&quot;&gt;&lt;span class=&quot;vlist&quot; style=&quot;height:0.15em;&quot;&gt;&lt;span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class=&quot;mspace&quot; style=&quot;margin-right:0.2778em;&quot;&gt;&lt;/span&gt;&lt;span class=&quot;mrel&quot;&gt;→&lt;/span&gt;&lt;span class=&quot;mspace&quot; style=&quot;margin-right:0.2778em;&quot;&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class=&quot;base&quot;&gt;&lt;span class=&quot;strut&quot; style=&quot;height:0.8333em;vertical-align:-0.15em;&quot;&gt;&lt;/span&gt;&lt;span class=&quot;mord&quot;&gt;&lt;span class=&quot;mord mathnormal&quot; style=&quot;margin-right:0.0715em;&quot;&gt;C&lt;/span&gt;&lt;span class=&quot;msupsub&quot;&gt;&lt;span class=&quot;vlist-t vlist-t2&quot;&gt;&lt;span class=&quot;vlist-r&quot;&gt;&lt;span class=&quot;vlist&quot; style=&quot;height:0.3011em;&quot;&gt;&lt;span style=&quot;top:-2.55em;margin-left:-0.0715em;margin-right:0.05em;&quot;&gt;&lt;span class=&quot;pstrut&quot; style=&quot;height:2.7em;&quot;&gt;&lt;/span&gt;&lt;span class=&quot;sizing reset-size6 size3 mtight&quot;&gt;&lt;span class=&quot;mord mtight&quot;&gt;1&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class=&quot;vlist-s&quot;&gt;​&lt;/span&gt;&lt;/span&gt;&lt;span class=&quot;vlist-r&quot;&gt;&lt;span class=&quot;vlist&quot; style=&quot;height:0.15em;&quot;&gt;&lt;span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;. Keep in mind that the step that failed, step &lt;span class=&quot;katex&quot;&gt;&lt;span class=&quot;katex-html&quot; aria-hidden=&quot;true&quot;&gt;&lt;span class=&quot;base&quot;&gt;&lt;span class=&quot;strut&quot; style=&quot;height:0.8333em;vertical-align:-0.15em;&quot;&gt;&lt;/span&gt;&lt;span class=&quot;mord&quot;&gt;&lt;span class=&quot;mord mathnormal&quot; style=&quot;margin-right:0.1389em;&quot;&gt;T&lt;/span&gt;&lt;span class=&quot;msupsub&quot;&gt;&lt;span class=&quot;vlist-t vlist-t2&quot;&gt;&lt;span class=&quot;vlist-r&quot;&gt;&lt;span class=&quot;vlist&quot; style=&quot;height:0.3011em;&quot;&gt;&lt;span style=&quot;top:-2.55em;margin-left:-0.1389em;margin-right:0.05em;&quot;&gt;&lt;span class=&quot;pstrut&quot; style=&quot;height:2.7em;&quot;&gt;&lt;/span&gt;&lt;span class=&quot;sizing reset-size6 size3 mtight&quot;&gt;&lt;span class=&quot;mord mtight&quot;&gt;3&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class=&quot;vlist-s&quot;&gt;​&lt;/span&gt;&lt;/span&gt;&lt;span class=&quot;vlist-r&quot;&gt;&lt;span class=&quot;vlist&quot; style=&quot;height:0.15em;&quot;&gt;&lt;span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;, never gets a compensating command. Since its original action never succeeded, there is nothing to undo.&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;&lt;strong&gt;Forward Recovery Workflow:&lt;/strong&gt; If an error occurs after you pass the pivot transaction, the system never walks backward. It refuses to roll back and keeps pushing forward. The orchestrator places the failed step into a retry buffer and attempts to run it again until the entire process completes from end to end.&lt;/p&gt;
&lt;/li&gt;
&lt;/ul&gt;
&lt;figure&gt;&lt;img src=&quot;https://raw.githubusercontent.com/rafeuddaraj/rafes-blog-assets/refs/heads/distributed-sagas-compensating-transactions-deep-dive/assets/choreography-event-mesh-timings.svg&quot; alt=&quot;Choreography Event Mesh Timings and Cascading Rollback&quot; loading=&quot;lazy&quot; decoding=&quot;async&quot; width=&quot;1000&quot; height=&quot;480&quot;&gt;&lt;figcaption&gt;Choreography Event Mesh Timings and Cascading Rollback&lt;/figcaption&gt;&lt;/figure&gt;
&lt;p&gt;When you look at execution timelines, you can clearly trace how asynchronous events pass between microservices in parallel. The moment a downstream failure occurs, cascading reverse events immediately trigger your compensating transactions to restore system equilibrium.&lt;/p&gt;
&lt;h2 id=&quot;6-step-by-step-execution-trace-and-code-mechanics&quot;&gt;6. Step-by-Step Execution Trace and Code Mechanics&lt;/h2&gt;
&lt;p&gt;To really understand how a production-grade saga orchestrator operates at the code level, let us build a clean blueprint using Node.js and TypeScript. This memory-safe coordinator engine will execute steps sequentially and automatically trigger reverse compensating functions whenever a failure occurs.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Step 1: The Orchestrator Coordinator Code Structure&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;We will build a class that holds an internal map of transaction steps alongside their corresponding compensating actions.&lt;/p&gt;
&lt;div class=&quot;expressive-code&quot;&gt;&lt;style&gt;.expressive-code{font-family:var(--ec-uiFontFml);font-size:var(--ec-uiFontSize);font-weight:var(--ec-uiFontWg);line-height:var(--ec-uiLineHt);text-size-adjust:none;-webkit-text-size-adjust:none}.expressive-code *:not(:is(svg, svg *)){all:revert;box-sizing:border-box}.expressive-code pre{display:flex;margin:0;padding:0;border:var(--ec-brdWd) solid var(--ec-brdCol);border-radius:calc(var(--ec-brdRad) + var(--ec-brdWd));background:var(--ec-codeBg)}.expressive-code pre:focus-visible{outline:3px solid var(--ec-focusBrd);outline-offset:-3px}.expressive-code pre &gt; code{all:unset;display:block;flex:1 0 100%;padding:var(--ec-codePadBlk) 0;color:var(--ec-codeFg);font-family:var(--ec-codeFontFml);font-size:var(--ec-codeFontSize);font-weight:var(--ec-codeFontWg);line-height:var(--ec-codeLineHt)}.expressive-code pre{overflow-x:auto}.expressive-code pre.wrap .ec-line .code{white-space:pre-wrap;overflow-wrap:break-word;min-width:min(20ch, var(--ecMaxLine, 20ch))}.expressive-code pre.wrap .ec-line .code span.indent{white-space:pre}.expressive-code pre::-webkit-scrollbar,.expressive-code pre::-webkit-scrollbar-track{background-color:inherit;border-radius:calc(var(--ec-brdRad) + var(--ec-brdWd));border-top-left-radius:0;border-top-right-radius:0}.expressive-code pre::-webkit-scrollbar-thumb{background-color:var(--ec-sbThumbCol);border:4px solid transparent;background-clip:content-box;border-radius:10px}.expressive-code pre::-webkit-scrollbar-thumb:hover{background-color:var(--ec-sbThumbHoverCol)}.expressive-code pre::-webkit-scrollbar-corner{background:transparent}.expressive-code .ec-line{direction:ltr;unicode-bidi:isolate;display:grid;grid-template-areas:&apos;gutter code&apos;;grid-template-columns:auto 1fr;position:relative}.expressive-code .ec-line .gutter{grid-area:gutter;color:var(--ec-gtrFg)}.expressive-code .ec-line .gutter &gt; *{pointer-events:none;user-select:none;-webkit-user-select:none}.expressive-code .ec-line .gutter ~ .code{--ecLineBrdCol:var(--ec-gtrBrdCol)}.expressive-code .ec-line.highlight .gutter{color:var(--ec-gtrHlFg)}.expressive-code .ec-line .code{grid-area:code;position:relative;box-sizing:content-box;padding-inline-start:calc(var(--ecIndent, 0ch) + var(--ec-codePadInl) - var(--ecGtrBrdWd));padding-inline-end:var(--ec-codePadInl);text-indent:calc(var(--ecIndent, 0ch) * -1)}.expressive-code .ec-line .code::before,.expressive-code .ec-line .code::after,.expressive-code .ec-line .code :where(*){text-indent:0}.expressive-code .ec-line .code{--ecGtrBrdWd:var(--ec-gtrBrdWd);border-inline-start:var(--ecGtrBrdWd) solid var(--ecLineBrdCol, transparent)}.expressive-code .sr-only{position:absolute;width:1px;height:1px;padding:0;margin:-1px;overflow:hidden;clip:rect(0, 0, 0, 0);white-space:nowrap;border-width:0}.expressive-code .ec-line.mark{--tmLineBgCol:var(--ec-tm-markBg)}.expressive-code .ec-line.mark .code{--ecLineBrdCol:var(--ec-tm-markBrdCol)}.expressive-code .ec-line.ins{--tmLineBgCol:var(--ec-tm-insBg);--tmLabel:var(--ec-tm-insDiffIndContent)}.expressive-code .ec-line.ins .code{--ecLineBrdCol:var(--ec-tm-insBrdCol)}.expressive-code .ec-line.ins .code::before{color:var(--ec-tm-insDiffIndCol)}.expressive-code .ec-line.del{--tmLineBgCol:var(--ec-tm-delBg);--tmLabel:var(--ec-tm-delDiffIndContent)}.expressive-code .ec-line.del .code{--ecLineBrdCol:var(--ec-tm-delBrdCol)}.expressive-code .ec-line.del .code::before{color:var(--ec-tm-delDiffIndCol)}.expressive-code .ec-line.mark,.expressive-code .ec-line.ins,.expressive-code .ec-line.del{background:var(--tmLineBgCol)}.expressive-code .ec-line.mark .code,.expressive-code .ec-line.ins .code,.expressive-code .ec-line.del .code{--ecGtrBrdWd:var(--ec-tm-lineMarkerAccentWd)}.expressive-code .ec-line.mark .code::before,.expressive-code .ec-line.ins .code::before,.expressive-code .ec-line.del .code::before{display:block;position:absolute;left:0;box-sizing:border-box;content:var(--tmLabel, &apos; &apos;);padding-inline-start:var(--ec-tm-lineDiffIndMargLeft);text-align:center;white-space:pre}.expressive-code .ec-line.mark.tm-label .code::before,.expressive-code .ec-line.ins.tm-label .code::before,.expressive-code .ec-line.del.tm-label .code::before{background:var(--ecLineBrdCol);padding:0 calc(var(--ec-tm-lineMarkerLabelPadInl) + var(--ec-tm-lineMarkerAccentWd)) 0 var(--ec-tm-lineMarkerLabelPadInl);color:var(--ec-tm-lineMarkerLabelCol)}.expressive-code .ec-line mark{--tmInlineBgCol:var(--ec-tm-markBg);--tmInlineBrdCol:var(--ec-tm-markBrdCol)}.expressive-code .ec-line ins{--tmInlineBgCol:var(--ec-tm-insBg);--tmInlineBrdCol:var(--ec-tm-insBrdCol)}.expressive-code .ec-line del{--tmInlineBgCol:var(--ec-tm-delBg);--tmInlineBrdCol:var(--ec-tm-delBrdCol)}.expressive-code .ec-line mark,.expressive-code .ec-line ins,.expressive-code .ec-line del{all:unset;display:inline-block;position:relative;--tmBrdL:var(--ec-tm-inlMarkerBrdWd);--tmBrdR:var(--ec-tm-inlMarkerBrdWd);--tmRadL:var(--ec-tm-inlMarkerBrdRad);--tmRadR:var(--ec-tm-inlMarkerBrdRad);margin-inline:0.025rem;padding-inline:var(--ec-tm-inlMarkerPad);border-radius:var(--tmRadL) var(--tmRadR) var(--tmRadR) var(--tmRadL);background:var(--tmInlineBgCol);background-clip:padding-box}.expressive-code .ec-line mark.open-start,.expressive-code .ec-line ins.open-start,.expressive-code .ec-line del.open-start{margin-inline-start:0;padding-inline-start:0;--tmBrdL:0px;--tmRadL:0}.expressive-code .ec-line mark.open-end,.expressive-code .ec-line ins.open-end,.expressive-code .ec-line del.open-end{margin-inline-end:0;padding-inline-end:0;--tmBrdR:0px;--tmRadR:0}.expressive-code .ec-line mark::before,.expressive-code .ec-line ins::before,.expressive-code .ec-line del::before{content:&apos;&apos;;position:absolute;pointer-events:none;display:inline-block;inset:0;border-radius:var(--tmRadL) var(--tmRadR) var(--tmRadR) var(--tmRadL);border:var(--ec-tm-inlMarkerBrdWd) solid var(--tmInlineBrdCol);border-inline-width:var(--tmBrdL) var(--tmBrdR)}.expressive-code .frame{all:unset;position:relative;display:block;--header-border-radius:calc(var(--ec-brdRad) + var(--ec-brdWd));--tab-border-radius:calc(var(--ec-frm-edTabBrdRad) + var(--ec-brdWd));--button-spacing:0.4rem;--code-background:var(--ec-frm-edBg);border-radius:var(--header-border-radius);box-shadow:var(--ec-frm-frameBoxShdCssVal)}.expressive-code .frame .header{display:none;z-index:1;position:relative;border-radius:var(--header-border-radius) var(--header-border-radius) 0 0}.expressive-code .frame.has-title pre,.expressive-code .frame.has-title code,.expressive-code .frame.is-terminal pre,.expressive-code .frame.is-terminal code{border-top:none;border-top-left-radius:0;border-top-right-radius:0}.expressive-code .frame .title:empty:before{content:&apos;\a0&apos;}.expressive-code .frame.has-title:not(.is-terminal){--button-spacing:calc(1.9rem + 2 * (var(--ec-uiPadBlk) + var(--ec-frm-edActTabIndHt)))}.expressive-code .frame.has-title:not(.is-terminal) .title{position:relative;color:var(--ec-frm-edActTabFg);background:var(--ec-frm-edActTabBg);background-clip:padding-box;margin-block-start:var(--ec-frm-edTabsMargBlkStart);padding:calc(var(--ec-uiPadBlk) + var(--ec-frm-edActTabIndHt)) var(--ec-uiPadInl);border:var(--ec-brdWd) solid var(--ec-frm-edActTabBrdCol);border-radius:var(--tab-border-radius) var(--tab-border-radius) 0 0;border-bottom:none;overflow:hidden}.expressive-code .frame.has-title:not(.is-terminal) .title::after{content:&apos;&apos;;position:absolute;pointer-events:none;inset:0;border-top:var(--ec-frm-edActTabIndHt) solid var(--ec-frm-edActTabIndTopCol);border-bottom:var(--ec-frm-edActTabIndHt) solid var(--ec-frm-edActTabIndBtmCol)}.expressive-code .frame.has-title:not(.is-terminal) .header{display:flex;background:linear-gradient(to top, var(--ec-frm-edTabBarBrdBtmCol) var(--ec-brdWd), transparent var(--ec-brdWd)),linear-gradient(var(--ec-frm-edTabBarBg), var(--ec-frm-edTabBarBg));background-repeat:no-repeat;padding-inline-start:var(--ec-frm-edTabsMargInlStart)}.expressive-code .frame.has-title:not(.is-terminal) .header::before{content:&apos;&apos;;position:absolute;pointer-events:none;inset:0;border:var(--ec-brdWd) solid var(--ec-frm-edTabBarBrdCol);border-radius:inherit;border-bottom:none}.expressive-code .frame.is-terminal{--button-spacing:calc(1.9rem + var(--ec-brdWd) + 2 * var(--ec-uiPadBlk));--code-background:var(--ec-frm-trmBg)}.expressive-code .frame.is-terminal .header{display:flex;align-items:center;justify-content:center;padding-block:var(--ec-uiPadBlk);padding-block-end:calc(var(--ec-uiPadBlk) + var(--ec-brdWd));position:relative;font-weight:500;letter-spacing:0.025ch;color:var(--ec-frm-trmTtbFg);background:var(--ec-frm-trmTtbBg);border:var(--ec-brdWd) solid var(--ec-brdCol);border-bottom:none}.expressive-code .frame.is-terminal .header::before{content:&apos;&apos;;position:absolute;pointer-events:none;left:var(--ec-uiPadInl);width:2.1rem;height:0.56rem;line-height:0;background-color:var(--ec-frm-trmTtbDotsFg);opacity:var(--ec-frm-trmTtbDotsOpa);-webkit-mask-image:var(--ec-frm-trmIcon);-webkit-mask-repeat:no-repeat;mask-image:var(--ec-frm-trmIcon);mask-repeat:no-repeat}.expressive-code .frame.is-terminal .header::after{content:&apos;&apos;;position:absolute;pointer-events:none;inset:0;border-bottom:var(--ec-brdWd) solid var(--ec-frm-trmTtbBrdBtmCol)}.expressive-code .frame pre{background:var(--code-background)}.expressive-code .copy{display:flex;gap:0.25rem;flex-direction:row;position:absolute;inset-block-start:calc(var(--ec-brdWd) + var(--button-spacing));inset-inline-end:calc(var(--ec-brdWd) + var(--ec-uiPadInl) / 2)}@media (scripting: none){.expressive-code .copy{display:none}}.expressive-code .copy{direction:ltr;unicode-bidi:isolate}.expressive-code .copy button{position:relative;align-self:flex-end;margin:0;padding:0;border:none;border-radius:0.2rem;z-index:1;cursor:pointer;transition-property:opacity, background, border-color;transition-duration:0.2s;transition-timing-function:cubic-bezier(0.25, 0.46, 0.45, 0.94);width:2.5rem;height:2.5rem;background:var(--code-background);opacity:0.75}.expressive-code .copy button div{position:absolute;inset:0;border-radius:inherit;background:var(--ec-frm-inlBtnBg);opacity:var(--ec-frm-inlBtnBgIdleOpa);transition-property:inherit;transition-duration:inherit;transition-timing-function:inherit}.expressive-code .copy button::before{content:&apos;&apos;;position:absolute;pointer-events:none;inset:0;border-radius:inherit;border:var(--ec-brdWd) solid var(--ec-frm-inlBtnBrd);opacity:var(--ec-frm-inlBtnBrdOpa)}.expressive-code .copy button::after{content:&apos;&apos;;position:absolute;pointer-events:none;inset:0;background-color:var(--ec-frm-inlBtnFg);-webkit-mask-image:var(--ec-frm-copyIcon);-webkit-mask-repeat:no-repeat;mask-image:var(--ec-frm-copyIcon);mask-repeat:no-repeat;margin:0.475rem;line-height:0}.expressive-code .copy button:hover,.expressive-code .copy button:focus:focus-visible{opacity:1}.expressive-code .copy button:hover div,.expressive-code .copy button:focus:focus-visible div{opacity:var(--ec-frm-inlBtnBgHoverOrFocusOpa)}.expressive-code .copy button:active{opacity:1}.expressive-code .copy button:active div{opacity:var(--ec-frm-inlBtnBgActOpa)}.expressive-code .copy .feedback{--tooltip-arrow-size:0.35rem;--tooltip-bg:var(--ec-frm-tooltipSuccessBg);color:var(--ec-frm-tooltipSuccessFg);pointer-events:none;user-select:none;-webkit-user-select:none;position:relative;align-self:center;background-color:var(--tooltip-bg);z-index:99;padding:0.125rem 0.75rem;border-radius:0.2rem;margin-inline-end:var(--tooltip-arrow-size);opacity:0;transition-property:opacity, transform;transition-duration:0.2s;transition-timing-function:ease-in-out;transform:translate3d(0, 0.25rem, 0)}.expressive-code .copy .feedback::after{content:&apos;&apos;;position:absolute;pointer-events:none;top:calc(50% - var(--tooltip-arrow-size));inset-inline-end:calc(-2 * (var(--tooltip-arrow-size) - 0.5px));border:var(--tooltip-arrow-size) solid transparent;border-inline-start-color:var(--tooltip-bg)}.expressive-code .copy .feedback.show{opacity:1;transform:translate3d(0, 0, 0)}@media (hover: hover){.expressive-code{}.expressive-code .copy button{opacity:0;width:2rem;height:2rem}.expressive-code .frame:hover .copy button:not(:hover),.expressive-code .frame:focus-within :focus-visible ~ .copy button:not(:hover),.expressive-code .frame .copy .feedback.show ~ button:not(:hover){opacity:0.75}}.expressive-code :nth-child(1 of .ec-line) .code{padding-inline-end:calc(2rem + var(--ec-codePadInl))}:root{--ec-brdRad:0.75rem;--ec-brdWd:1.5px;--ec-brdCol:var(--code-line);--ec-codeFontFml:var(--font-code);--ec-codeFontSize:0.875rem;--ec-codeFontWg:400;--ec-codeLineHt:1.75;--ec-codePadBlk:1rem;--ec-codePadInl:1.125rem;--ec-codeBg:var(--code-bg);--ec-codeFg:#e6edf3;--ec-codeSelBg:#264f78;--ec-gtrFg:#6e7681;--ec-gtrBrdCol:#6e768133;--ec-gtrBrdWd:1.5px;--ec-gtrHlFg:#e6edf3;--ec-uiFontFml:var(--font-mono);--ec-uiFontSize:0.75rem;--ec-uiFontWg:400;--ec-uiLineHt:1.65;--ec-uiPadBlk:0.25rem;--ec-uiPadInl:1rem;--ec-uiSelBg:#6e768166;--ec-uiSelFg:#e6edf3;--ec-focusBrd:#1f6feb;--ec-sbThumbCol:#8b949e33;--ec-sbThumbHoverCol:#8b949e3d;--ec-tm-lineMarkerAccentMarg:0rem;--ec-tm-lineMarkerAccentWd:0.15rem;--ec-tm-lineMarkerLabelPadInl:0.2rem;--ec-tm-lineMarkerLabelCol:white;--ec-tm-lineDiffIndMargLeft:0.3rem;--ec-tm-inlMarkerBrdWd:1.5px;--ec-tm-inlMarkerBrdRad:0.2rem;--ec-tm-inlMarkerPad:0.15rem;--ec-tm-insDiffIndContent:&apos;+&apos;;--ec-tm-delDiffIndContent:&apos;-&apos;;--ec-tm-markBg:#264a8980;--ec-tm-markBrdCol:#5570b3d0;--ec-tm-insBg:#26561c80;--ec-tm-insBrdCol:#4e7e41d0;--ec-tm-insDiffIndCol:#7eb070d0;--ec-tm-delBg:#81322b80;--ec-tm-delBrdCol:#ae594fd0;--ec-tm-delDiffIndCol:#e68a7ed0;--ec-frm-shdCol:#0000005b;--ec-frm-frameBoxShdCssVal:none;--ec-frm-edActTabBg:var(--code-bg);--ec-frm-edActTabFg:var(--code-muted);--ec-frm-edActTabBrdCol:transparent;--ec-frm-edActTabIndHt:1.5px;--ec-frm-edActTabIndTopCol:transparent;--ec-frm-edActTabIndBtmCol:#0d1117;--ec-frm-edTabsMargInlStart:0;--ec-frm-edTabsMargBlkStart:0;--ec-frm-edTabBrdRad:0.75rem;--ec-frm-edTabBarBg:var(--code-bg);--ec-frm-edTabBarBrdCol:var(--code-line);--ec-frm-edTabBarBrdBtmCol:var(--code-line);--ec-frm-edBg:var(--code-bg);--ec-frm-trmTtbFg:var(--code-muted);--ec-frm-trmTtbDotsFg:var(--code-muted);--ec-frm-trmTtbDotsOpa:0.15;--ec-frm-trmTtbBg:var(--code-bg);--ec-frm-trmTtbBrdBtmCol:var(--code-line);--ec-frm-trmBg:var(--code-bg);--ec-frm-inlBtnBg:var(--code-ink);--ec-frm-inlBtnBgIdleOpa:0;--ec-frm-inlBtnBgHoverOrFocusOpa:0.2;--ec-frm-inlBtnBgActOpa:0.3;--ec-frm-inlBtnFg:var(--code-ink);--ec-frm-inlBtnBrd:var(--code-line);--ec-frm-inlBtnBrdOpa:0.4;--ec-frm-tooltipSuccessBg:var(--color-emerald);--ec-frm-tooltipSuccessFg:var(--color-bg);--ec-frm-copyIcon:url(&quot;data:image/svg+xml,%3Csvg%20xmlns%3D&apos;http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg&apos;%20viewBox%3D&apos;0%200%2024%2024&apos;%20fill%3D&apos;none&apos;%20stroke%3D&apos;black&apos;%20stroke-width%3D&apos;1.75&apos;%3E%3Cpath%20d%3D&apos;M3%2019a2%202%200%200%201-1-2V2a2%202%200%200%201%201-1h13a2%202%200%200%201%202%201&apos;%2F%3E%3Crect%20x%3D&apos;6&apos;%20y%3D&apos;5&apos;%20width%3D&apos;16&apos;%20height%3D&apos;18&apos;%20rx%3D&apos;1.5&apos;%20ry%3D&apos;1.5&apos;%2F%3E%3C%2Fsvg%3E&quot;);--ec-frm-trmIcon:url(&quot;data:image/svg+xml,%3Csvg%20xmlns%3D&apos;http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg&apos;%20viewBox%3D&apos;0%200%2060%2016&apos;%20preserveAspectRatio%3D&apos;xMidYMid%20meet&apos;%3E%3Ccircle%20cx%3D&apos;8&apos;%20cy%3D&apos;8&apos;%20r%3D&apos;8&apos;%2F%3E%3Ccircle%20cx%3D&apos;30&apos;%20cy%3D&apos;8&apos;%20r%3D&apos;8&apos;%2F%3E%3Ccircle%20cx%3D&apos;52&apos;%20cy%3D&apos;8&apos;%20r%3D&apos;8&apos;%2F%3E%3C%2Fsvg%3E&quot;)}.expressive-code .ec-line :where(span[style^=&apos;--&apos;]:not([class])){color:var(--0, inherit);background-color:var(--0bg, transparent);font-style:var(--0fs, inherit);font-weight:var(--0fw, inherit);text-decoration:var(--0td, inherit)}&lt;/style&gt;&lt;script type=&quot;module&quot; src=&quot;/_astro/ec.0vx5m.js&quot;&gt;&lt;/script&gt;&lt;figure class=&quot;frame has-title&quot;&gt;&lt;figcaption class=&quot;header&quot;&gt;&lt;span class=&quot;title&quot;&gt;TypeScript&lt;/span&gt;&lt;/figcaption&gt;&lt;pre data-language=&quot;typescript&quot;&gt;&lt;code&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;type&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; &lt;/span&gt;&lt;span style=&quot;--0:#FFA657&quot;&gt;SagaStep&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; &lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;=&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; {&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span class=&quot;indent&quot;&gt;  &lt;/span&gt;&lt;span style=&quot;--0:#FFA657&quot;&gt;name&lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;:&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; &lt;/span&gt;&lt;span style=&quot;--0:#79C0FF&quot;&gt;string&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;;&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span class=&quot;indent&quot;&gt;  &lt;/span&gt;&lt;span style=&quot;--0:#D2A8FF&quot;&gt;action&lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;:&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; () &lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;=&gt;&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; &lt;/span&gt;&lt;span style=&quot;--0:#FFA657&quot;&gt;Promise&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;&amp;#x3C;&lt;/span&gt;&lt;span style=&quot;--0:#79C0FF&quot;&gt;any&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;&gt;;&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span class=&quot;indent&quot;&gt;  &lt;/span&gt;&lt;span style=&quot;--0:#D2A8FF&quot;&gt;compensate&lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;:&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; () &lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;=&gt;&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; &lt;/span&gt;&lt;span style=&quot;--0:#FFA657&quot;&gt;Promise&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;&amp;#x3C;&lt;/span&gt;&lt;span style=&quot;--0:#79C0FF&quot;&gt;any&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;&gt;;&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;};&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;
&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;export&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; &lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;class&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; &lt;/span&gt;&lt;span style=&quot;--0:#FFA657&quot;&gt;SagaOrchestrator&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; {&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span class=&quot;indent&quot;&gt;  &lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;private&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; &lt;/span&gt;&lt;span style=&quot;--0:#FFA657&quot;&gt;steps&lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;:&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; &lt;/span&gt;&lt;span style=&quot;--0:#FFA657&quot;&gt;SagaStep&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;[] &lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;=&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; [];&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span class=&quot;indent&quot;&gt;  &lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;private&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; &lt;/span&gt;&lt;span style=&quot;--0:#FFA657&quot;&gt;executedSteps&lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;:&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; &lt;/span&gt;&lt;span style=&quot;--0:#FFA657&quot;&gt;SagaStep&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;[] &lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;=&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; [];&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;
&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span class=&quot;indent&quot;&gt;  &lt;/span&gt;&lt;span style=&quot;--0:#8B949E&quot;&gt;// Register a new saga step alongside its reverse compensation logic&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span class=&quot;indent&quot;&gt;  &lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;public&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; &lt;/span&gt;&lt;span style=&quot;--0:#D2A8FF&quot;&gt;addStep&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;(&lt;/span&gt;&lt;span style=&quot;--0:#FFA657&quot;&gt;name&lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;:&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; &lt;/span&gt;&lt;span style=&quot;--0:#79C0FF&quot;&gt;string&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;, &lt;/span&gt;&lt;span style=&quot;--0:#D2A8FF&quot;&gt;action&lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;:&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; () &lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;=&gt;&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; &lt;/span&gt;&lt;span style=&quot;--0:#FFA657&quot;&gt;Promise&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;&amp;#x3C;&lt;/span&gt;&lt;span style=&quot;--0:#79C0FF&quot;&gt;any&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;&gt;, &lt;/span&gt;&lt;span style=&quot;--0:#D2A8FF&quot;&gt;compensate&lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;:&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; () &lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;=&gt;&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; &lt;/span&gt;&lt;span style=&quot;--0:#FFA657&quot;&gt;Promise&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;&amp;#x3C;&lt;/span&gt;&lt;span style=&quot;--0:#79C0FF&quot;&gt;any&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;&gt;)&lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;:&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; &lt;/span&gt;&lt;span style=&quot;--0:#79C0FF&quot;&gt;void&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; {&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span class=&quot;indent&quot;&gt;    &lt;/span&gt;&lt;span style=&quot;--0:#79C0FF&quot;&gt;this&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;.steps.&lt;/span&gt;&lt;span style=&quot;--0:#D2A8FF&quot;&gt;push&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;({ name, action, compensate });&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span class=&quot;indent&quot;&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;  &lt;/span&gt;&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;}&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;
&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span class=&quot;indent&quot;&gt;  &lt;/span&gt;&lt;span style=&quot;--0:#8B949E&quot;&gt;// Execute the saga sequentially and trigger backward recovery on failure&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span class=&quot;indent&quot;&gt;  &lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;public&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; &lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;async&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; &lt;/span&gt;&lt;span style=&quot;--0:#D2A8FF&quot;&gt;execute&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;(&lt;/span&gt;&lt;span style=&quot;--0:#FFA657&quot;&gt;sagaId&lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;:&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; &lt;/span&gt;&lt;span style=&quot;--0:#79C0FF&quot;&gt;string&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;)&lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;:&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; &lt;/span&gt;&lt;span style=&quot;--0:#FFA657&quot;&gt;Promise&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;&amp;#x3C;&lt;/span&gt;&lt;span style=&quot;--0:#79C0FF&quot;&gt;boolean&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;&gt; {&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span class=&quot;indent&quot;&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;    &lt;/span&gt;&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;console.&lt;/span&gt;&lt;span style=&quot;--0:#D2A8FF&quot;&gt;log&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;(&lt;/span&gt;&lt;span style=&quot;--0:#A5D6FF&quot;&gt;`[Saga Engine] Starting Saga Execution: ${&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;sagaId&lt;/span&gt;&lt;span style=&quot;--0:#A5D6FF&quot;&gt;}`&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;);&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;
&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span class=&quot;indent&quot;&gt;    &lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;for&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; (&lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;const&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; &lt;/span&gt;&lt;span style=&quot;--0:#79C0FF&quot;&gt;step&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; &lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;of&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; &lt;/span&gt;&lt;span style=&quot;--0:#79C0FF&quot;&gt;this&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;.steps) {&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span class=&quot;indent&quot;&gt;      &lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;try&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; {&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span class=&quot;indent&quot;&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;        &lt;/span&gt;&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;console.&lt;/span&gt;&lt;span style=&quot;--0:#D2A8FF&quot;&gt;log&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;(&lt;/span&gt;&lt;span style=&quot;--0:#A5D6FF&quot;&gt;`[Saga Engine] Executing Step: ${&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;step&lt;/span&gt;&lt;span style=&quot;--0:#A5D6FF&quot;&gt;.&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;name&lt;/span&gt;&lt;span style=&quot;--0:#A5D6FF&quot;&gt;}`&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;);&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span class=&quot;indent&quot;&gt;        &lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;await&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; step.&lt;/span&gt;&lt;span style=&quot;--0:#D2A8FF&quot;&gt;action&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;();&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span class=&quot;indent&quot;&gt;        &lt;/span&gt;&lt;span style=&quot;--0:#8B949E&quot;&gt;// Store successful steps in the execution log&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span class=&quot;indent&quot;&gt;        &lt;/span&gt;&lt;span style=&quot;--0:#79C0FF&quot;&gt;this&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;.executedSteps.&lt;/span&gt;&lt;span style=&quot;--0:#D2A8FF&quot;&gt;push&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;(step);&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span class=&quot;indent&quot;&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;      &lt;/span&gt;&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;} &lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;catch&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; (error) {&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span class=&quot;indent&quot;&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;        &lt;/span&gt;&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;console.&lt;/span&gt;&lt;span style=&quot;--0:#D2A8FF&quot;&gt;error&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;(&lt;/span&gt;&lt;span style=&quot;--0:#A5D6FF&quot;&gt;`[Saga Engine] Step Failed: ${&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;step&lt;/span&gt;&lt;span style=&quot;--0:#A5D6FF&quot;&gt;.&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;name&lt;/span&gt;&lt;span style=&quot;--0:#A5D6FF&quot;&gt;}. Triggering Backward Recovery!`&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;, error);&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span class=&quot;indent&quot;&gt;        &lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;await&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; &lt;/span&gt;&lt;span style=&quot;--0:#79C0FF&quot;&gt;this&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;.&lt;/span&gt;&lt;span style=&quot;--0:#D2A8FF&quot;&gt;rollback&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;(sagaId);&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span class=&quot;indent&quot;&gt;        &lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;return&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; &lt;/span&gt;&lt;span style=&quot;--0:#79C0FF&quot;&gt;false&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;;&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span class=&quot;indent&quot;&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;      &lt;/span&gt;&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;}&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span class=&quot;indent&quot;&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;    &lt;/span&gt;&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;}&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;
&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span class=&quot;indent&quot;&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;    &lt;/span&gt;&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;console.&lt;/span&gt;&lt;span style=&quot;--0:#D2A8FF&quot;&gt;log&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;(&lt;/span&gt;&lt;span style=&quot;--0:#A5D6FF&quot;&gt;`[Saga Engine] Saga Execution Completed Successfully: ${&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;sagaId&lt;/span&gt;&lt;span style=&quot;--0:#A5D6FF&quot;&gt;}`&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;);&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span class=&quot;indent&quot;&gt;    &lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;return&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; &lt;/span&gt;&lt;span style=&quot;--0:#79C0FF&quot;&gt;true&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;;&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span class=&quot;indent&quot;&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;  &lt;/span&gt;&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;}&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;
&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span class=&quot;indent&quot;&gt;  &lt;/span&gt;&lt;span style=&quot;--0:#8B949E&quot;&gt;// Execute compensating transactions in reverse order&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span class=&quot;indent&quot;&gt;  &lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;private&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; &lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;async&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; &lt;/span&gt;&lt;span style=&quot;--0:#D2A8FF&quot;&gt;rollback&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;(&lt;/span&gt;&lt;span style=&quot;--0:#FFA657&quot;&gt;sagaId&lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;:&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; &lt;/span&gt;&lt;span style=&quot;--0:#79C0FF&quot;&gt;string&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;)&lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;:&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; &lt;/span&gt;&lt;span style=&quot;--0:#FFA657&quot;&gt;Promise&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;&amp;#x3C;&lt;/span&gt;&lt;span style=&quot;--0:#79C0FF&quot;&gt;void&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;&gt; {&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span class=&quot;indent&quot;&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;    &lt;/span&gt;&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;console.&lt;/span&gt;&lt;span style=&quot;--0:#D2A8FF&quot;&gt;log&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;(&lt;/span&gt;&lt;span style=&quot;--0:#A5D6FF&quot;&gt;`[Saga Engine] Starting Rollback for Saga: ${&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;sagaId&lt;/span&gt;&lt;span style=&quot;--0:#A5D6FF&quot;&gt;}`&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;);&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;
&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span class=&quot;indent&quot;&gt;    &lt;/span&gt;&lt;span style=&quot;--0:#8B949E&quot;&gt;// Reverse the execution list to walk backward from the last successful step&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span class=&quot;indent&quot;&gt;    &lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;const&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; &lt;/span&gt;&lt;span style=&quot;--0:#79C0FF&quot;&gt;reversedSteps&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; &lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;=&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; [&lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;...&lt;/span&gt;&lt;span style=&quot;--0:#79C0FF&quot;&gt;this&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;.executedSteps].&lt;/span&gt;&lt;span style=&quot;--0:#D2A8FF&quot;&gt;reverse&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;();&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;
&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span class=&quot;indent&quot;&gt;    &lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;for&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; (&lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;const&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; &lt;/span&gt;&lt;span style=&quot;--0:#79C0FF&quot;&gt;step&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; &lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;of&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; reversedSteps) {&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span class=&quot;indent&quot;&gt;      &lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;try&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; {&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span class=&quot;indent&quot;&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;        &lt;/span&gt;&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;console.&lt;/span&gt;&lt;span style=&quot;--0:#D2A8FF&quot;&gt;log&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;(&lt;/span&gt;&lt;span style=&quot;--0:#A5D6FF&quot;&gt;`[Saga Engine] Compensating Step: ${&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;step&lt;/span&gt;&lt;span style=&quot;--0:#A5D6FF&quot;&gt;.&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;name&lt;/span&gt;&lt;span style=&quot;--0:#A5D6FF&quot;&gt;}`&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;);&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span class=&quot;indent&quot;&gt;        &lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;await&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; step.&lt;/span&gt;&lt;span style=&quot;--0:#D2A8FF&quot;&gt;compensate&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;();&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span class=&quot;indent&quot;&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;      &lt;/span&gt;&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;} &lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;catch&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; (compensateError) {&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span class=&quot;indent&quot;&gt;        &lt;/span&gt;&lt;span style=&quot;--0:#8B949E&quot;&gt;// If a compensating step fails, push it to a Dead Letter Queue (DLQ)&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span class=&quot;indent&quot;&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;        &lt;/span&gt;&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;console.&lt;/span&gt;&lt;span style=&quot;--0:#D2A8FF&quot;&gt;error&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;(&lt;/span&gt;&lt;span style=&quot;--0:#A5D6FF&quot;&gt;`[CRITICAL] Compensation Failed for Step: ${&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;step&lt;/span&gt;&lt;span style=&quot;--0:#A5D6FF&quot;&gt;.&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;name&lt;/span&gt;&lt;span style=&quot;--0:#A5D6FF&quot;&gt;}. Manual intervention required!`&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;, compensateError);&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span class=&quot;indent&quot;&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;      &lt;/span&gt;&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;}&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span class=&quot;indent&quot;&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;    &lt;/span&gt;&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;}&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span class=&quot;indent&quot;&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;  &lt;/span&gt;&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;}&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;}&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;/code&gt;&lt;/pre&gt;&lt;div class=&quot;copy&quot;&gt;&lt;div aria-live=&quot;polite&quot;&gt;&lt;/div&gt;&lt;button title=&quot;Copy to clipboard&quot; data-copied=&quot;Copied!&quot; data-code=&quot;type SagaStep = {  name: string;  action: () =&gt; Promise&lt;any&gt;;  compensate: () =&gt; Promise&lt;any&gt;;};export class SagaOrchestrator {  private steps: SagaStep[] = [];  private executedSteps: SagaStep[] = [];  // Register a new saga step alongside its reverse compensation logic  public addStep(name: string, action: () =&gt; Promise&lt;any&gt;, compensate: () =&gt; Promise&lt;any&gt;): void {    this.steps.push({ name, action, compensate });  }  // Execute the saga sequentially and trigger backward recovery on failure  public async execute(sagaId: string): Promise&lt;boolean&gt; {    console.log(&amp;#x60;[Saga Engine] Starting Saga Execution: ${sagaId}&amp;#x60;);    for (const step of this.steps) {      try {        console.log(&amp;#x60;[Saga Engine] Executing Step: ${step.name}&amp;#x60;);        await step.action();        // Store successful steps in the execution log        this.executedSteps.push(step);      } catch (error) {        console.error(&amp;#x60;[Saga Engine] Step Failed: ${step.name}. Triggering Backward Recovery!&amp;#x60;, error);        await this.rollback(sagaId);        return false;      }    }    console.log(&amp;#x60;[Saga Engine] Saga Execution Completed Successfully: ${sagaId}&amp;#x60;);    return true;  }  // Execute compensating transactions in reverse order  private async rollback(sagaId: string): Promise&lt;void&gt; {    console.log(&amp;#x60;[Saga Engine] Starting Rollback for Saga: ${sagaId}&amp;#x60;);    // Reverse the execution list to walk backward from the last successful step    const reversedSteps = [...this.executedSteps].reverse();    for (const step of reversedSteps) {      try {        console.log(&amp;#x60;[Saga Engine] Compensating Step: ${step.name}&amp;#x60;);        await step.compensate();      } catch (compensateError) {        // If a compensating step fails, push it to a Dead Letter Queue (DLQ)        console.error(&amp;#x60;[CRITICAL] Compensation Failed for Step: ${step.name}. Manual intervention required!&amp;#x60;, compensateError);      }    }  }}&quot;&gt;&lt;div&gt;&lt;/div&gt;&lt;/button&gt;&lt;/div&gt;&lt;/figure&gt;&lt;/div&gt;
&lt;p&gt;&lt;strong&gt;Step 2: Idempotent Compensations and Composite Key Design&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;In distributed environments, network hiccups mean a single compensating command, like &lt;code&gt;cancelInventory&lt;/code&gt;, might hit your server multiple times. If your compensation logic lacks idempotency, your database will accidentally restore the stock twice. To protect against duplicate requests, you must build database guards using a unique saga identifier (&lt;code&gt;saga_id&lt;/code&gt;) and composite keys.&lt;/p&gt;
&lt;div class=&quot;expressive-code&quot;&gt;&lt;figure class=&quot;frame has-title&quot;&gt;&lt;figcaption class=&quot;header&quot;&gt;&lt;span class=&quot;title&quot;&gt;TypeScript&lt;/span&gt;&lt;/figcaption&gt;&lt;pre data-language=&quot;typescript&quot;&gt;&lt;code&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;import&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; { PrismaClient } &lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;from&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; &lt;/span&gt;&lt;span style=&quot;--0:#A5D6FF&quot;&gt;&apos;@prisma/client&apos;&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;;&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;
&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;const&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; &lt;/span&gt;&lt;span style=&quot;--0:#79C0FF&quot;&gt;prisma&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; &lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;=&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; &lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;new&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; &lt;/span&gt;&lt;span style=&quot;--0:#D2A8FF&quot;&gt;PrismaClient&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;();&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;
&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;async&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; &lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;function&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; &lt;/span&gt;&lt;span style=&quot;--0:#D2A8FF&quot;&gt;compensateInventory&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;(&lt;/span&gt;&lt;span style=&quot;--0:#FFA657&quot;&gt;sagaId&lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;:&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; &lt;/span&gt;&lt;span style=&quot;--0:#79C0FF&quot;&gt;string&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;, &lt;/span&gt;&lt;span style=&quot;--0:#FFA657&quot;&gt;productId&lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;:&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; &lt;/span&gt;&lt;span style=&quot;--0:#79C0FF&quot;&gt;string&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;, &lt;/span&gt;&lt;span style=&quot;--0:#FFA657&quot;&gt;quantity&lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;:&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; &lt;/span&gt;&lt;span style=&quot;--0:#79C0FF&quot;&gt;number&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;) {&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span class=&quot;indent&quot;&gt;  &lt;/span&gt;&lt;span style=&quot;--0:#8B949E&quot;&gt;// Check idempotency and restore inventory inside a single database transaction&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span class=&quot;indent&quot;&gt;  &lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;return&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; &lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;await&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; prisma.&lt;/span&gt;&lt;span style=&quot;--0:#D2A8FF&quot;&gt;$transaction&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;(&lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;async&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; (&lt;/span&gt;&lt;span style=&quot;--0:#FFA657&quot;&gt;tx&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;) &lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;=&gt;&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; {&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span class=&quot;indent&quot;&gt;    &lt;/span&gt;&lt;span style=&quot;--0:#8B949E&quot;&gt;// 1. Verify if this specific saga ID already executed its rollback&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span class=&quot;indent&quot;&gt;    &lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;const&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; &lt;/span&gt;&lt;span style=&quot;--0:#79C0FF&quot;&gt;existingCompensation&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; &lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;=&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; &lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;await&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; tx.compensation_logs.&lt;/span&gt;&lt;span style=&quot;--0:#D2A8FF&quot;&gt;findUnique&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;({&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span class=&quot;indent&quot;&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;      &lt;/span&gt;&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;where: {&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span class=&quot;indent&quot;&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;        &lt;/span&gt;&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;saga_id_step_name: {&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span class=&quot;indent&quot;&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;          &lt;/span&gt;&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;saga_id: sagaId,&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span class=&quot;indent&quot;&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;          &lt;/span&gt;&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;step_name: &lt;/span&gt;&lt;span style=&quot;--0:#A5D6FF&quot;&gt;&apos;INVENTORY_DEDUCT_COMPENSATION&apos;&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;,&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span class=&quot;indent&quot;&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;        &lt;/span&gt;&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;},&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span class=&quot;indent&quot;&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;      &lt;/span&gt;&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;},&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span class=&quot;indent&quot;&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;    &lt;/span&gt;&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;});&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;
&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span class=&quot;indent&quot;&gt;    &lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;if&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; (existingCompensation) {&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span class=&quot;indent&quot;&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;      &lt;/span&gt;&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;console.&lt;/span&gt;&lt;span style=&quot;--0:#D2A8FF&quot;&gt;log&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;(&lt;/span&gt;&lt;span style=&quot;--0:#A5D6FF&quot;&gt;`[Idempotency Guard] Compensation already processed for Saga: ${&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;sagaId&lt;/span&gt;&lt;span style=&quot;--0:#A5D6FF&quot;&gt;}. Skipping.`&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;);&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span class=&quot;indent&quot;&gt;      &lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;return&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;;&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span class=&quot;indent&quot;&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;    &lt;/span&gt;&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;}&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;
&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span class=&quot;indent&quot;&gt;    &lt;/span&gt;&lt;span style=&quot;--0:#8B949E&quot;&gt;// 2. Restore the inventory stock&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span class=&quot;indent&quot;&gt;    &lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;await&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; tx.products.&lt;/span&gt;&lt;span style=&quot;--0:#D2A8FF&quot;&gt;update&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;({&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span class=&quot;indent&quot;&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;      &lt;/span&gt;&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;where: { id: productId },&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span class=&quot;indent&quot;&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;      &lt;/span&gt;&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;data: { stock: { increment: quantity } },&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span class=&quot;indent&quot;&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;    &lt;/span&gt;&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;});&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;
&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span class=&quot;indent&quot;&gt;    &lt;/span&gt;&lt;span style=&quot;--0:#8B949E&quot;&gt;// 3. Create a compensation log entry to permanently block duplicate requests&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span class=&quot;indent&quot;&gt;    &lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;await&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; tx.compensation_logs.&lt;/span&gt;&lt;span style=&quot;--0:#D2A8FF&quot;&gt;create&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;({&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span class=&quot;indent&quot;&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;      &lt;/span&gt;&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;data: {&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span class=&quot;indent&quot;&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;        &lt;/span&gt;&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;saga_id: sagaId,&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span class=&quot;indent&quot;&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;        &lt;/span&gt;&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;step_name: &lt;/span&gt;&lt;span style=&quot;--0:#A5D6FF&quot;&gt;&apos;INVENTORY_DEDUCT_COMPENSATION&apos;&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;,&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span class=&quot;indent&quot;&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;        &lt;/span&gt;&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;processed_at: &lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;new&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; &lt;/span&gt;&lt;span style=&quot;--0:#D2A8FF&quot;&gt;Date&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;(),&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span class=&quot;indent&quot;&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;      &lt;/span&gt;&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;},&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span class=&quot;indent&quot;&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;    &lt;/span&gt;&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;});&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;
&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span class=&quot;indent&quot;&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;    &lt;/span&gt;&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;console.&lt;/span&gt;&lt;span style=&quot;--0:#D2A8FF&quot;&gt;log&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;(&lt;/span&gt;&lt;span style=&quot;--0:#A5D6FF&quot;&gt;`[Saga Engine] Inventory successfully restored for Product: ${&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;productId&lt;/span&gt;&lt;span style=&quot;--0:#A5D6FF&quot;&gt;}`&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;);&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span class=&quot;indent&quot;&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;  &lt;/span&gt;&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;});&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;}&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;/code&gt;&lt;/pre&gt;&lt;div class=&quot;copy&quot;&gt;&lt;div aria-live=&quot;polite&quot;&gt;&lt;/div&gt;&lt;button title=&quot;Copy to clipboard&quot; data-copied=&quot;Copied!&quot; data-code=&quot;import { PrismaClient } from &amp;#x27;@prisma/client&amp;#x27;;const prisma = new PrismaClient();async function compensateInventory(sagaId: string, productId: string, quantity: number) {  // Check idempotency and restore inventory inside a single database transaction  return await prisma.$transaction(async (tx) =&gt; {    // 1. Verify if this specific saga ID already executed its rollback    const existingCompensation = await tx.compensation_logs.findUnique({      where: {        saga_id_step_name: {          saga_id: sagaId,          step_name: &amp;#x27;INVENTORY_DEDUCT_COMPENSATION&amp;#x27;,        },      },    });    if (existingCompensation) {      console.log(&amp;#x60;[Idempotency Guard] Compensation already processed for Saga: ${sagaId}. Skipping.&amp;#x60;);      return;    }    // 2. Restore the inventory stock    await tx.products.update({      where: { id: productId },      data: { stock: { increment: quantity } },    });    // 3. Create a compensation log entry to permanently block duplicate requests    await tx.compensation_logs.create({      data: {        saga_id: sagaId,        step_name: &amp;#x27;INVENTORY_DEDUCT_COMPENSATION&amp;#x27;,        processed_at: new Date(),      },    });    console.log(&amp;#x60;[Saga Engine] Inventory successfully restored for Product: ${productId}&amp;#x60;);  });}&quot;&gt;&lt;div&gt;&lt;/div&gt;&lt;/button&gt;&lt;/div&gt;&lt;/figure&gt;&lt;/div&gt;
&lt;h2 id=&quot;7-distributed-isolation-anomalies-the-hidden-traps&quot;&gt;7. Distributed Isolation Anomalies: The Hidden Traps&lt;/h2&gt;
&lt;p&gt;Because saga patterns lack a global database lock, intermediate or partial system states sit out in the open where concurrent transactions can read them. This complete lack of transaction isolation creates serious concurrency anomalies and system traps:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;Lost Updates:&lt;/strong&gt; Suppose Saga A checks a user&apos;s credit limit and temporarily reduces it by 100 dollars. At the exact same moment, Saga B jumps in and updates that same user&apos;s credit limit. If Saga A fails later and triggers a rollback, its compensating command will overwrite the changes made by Saga B. As a result, the update from Saga B is permanently lost.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Dirty Reads:&lt;/strong&gt; Imagine a saga is sitting halfway through its workflow, where payment succeeded but inventory verification is still pending. A second user sees that uncommitted product sitting in stock and places an order. A moment later, the original saga fails and triggers a rollback. That second user just ordered an item that never actually existed in the warehouse.&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;To eliminate these isolation problems, you have to build specific architectural countermeasures into your production system:&lt;/p&gt;
&lt;ol&gt;
&lt;li&gt;
&lt;p&gt;&lt;strong&gt;Semantic Lock:&lt;/strong&gt; Instead of relying on low-level database engine locks, you build application-level locks directly into your business logic. For example, instead of immediately setting an order status to &lt;code&gt;ACTIVE&lt;/code&gt;, you use intermediate states like &lt;code&gt;PENDING_CHECKOUT&lt;/code&gt;, &lt;code&gt;RESERVED&lt;/code&gt;, or &lt;code&gt;LOCK_ACQUIRED&lt;/code&gt;. When other transactions attempt to read that record, the status tells them a saga is actively modifying the data, and they know to leave it alone.&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;&lt;strong&gt;Pessimistic View:&lt;/strong&gt; You design your read-heavy APIs to always display a conservative or pessimistic view of the system state. When showing a user&apos;s account balance, for instance, you subtract the &lt;code&gt;Reserved Balance&lt;/code&gt; from the &lt;code&gt;Actual Balance&lt;/code&gt; and only display the &lt;code&gt;Available Balance&lt;/code&gt;. This guarantees that even if a running saga fails and rolls back later, the user never experiences a jarring UI glitch or data discrepancy.&lt;/p&gt;
&lt;/li&gt;
&lt;/ol&gt;
&lt;h2 id=&quot;8-production-warnings-safety-nets&quot;&gt;8. Production Warnings &amp;#x26; Safety Nets&lt;/h2&gt;
&lt;div class=&quot;callout&quot; role=&quot;note&quot; data-type=&quot;danger&quot;&gt;
&lt;p class=&quot;callout-title&quot;&gt;&lt;strong&gt;The Infinite Rollback Loop&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;You must ensure your compensating transaction functions never throw unhandled exceptions. If a rollback function crashes due to a database connection error or a bug in your business logic, the entire orchestrator gets trapped in an infinite retry loop. This leaves your data permanently unbalanced. Always write fault-tolerant compensation logic, and use a Dead Letter Queue (DLQ) as your final safety net.&lt;/p&gt;
&lt;/div&gt;
&lt;div class=&quot;callout&quot; role=&quot;note&quot; data-type=&quot;warning&quot;&gt;
&lt;p class=&quot;callout-title&quot;&gt;&lt;strong&gt;Asynchronous Deadlocks in Choreography&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;Never design cyclic dependencies inside a choreography saga. If Service A sends an event to Service B, Service B sends to Service C, and Service C routes back to Service A, you are asking for trouble. During traffic spikes, this circular loop creates distributed deadlocks that overflow message broker buffers and crash your network. Keep your event flows strictly unidirectional or organized in a clear tree structure.&lt;/p&gt;
&lt;/div&gt;
&lt;h2 id=&quot;9-summary-production-decision-rules&quot;&gt;9. Summary &amp;#x26; Production Decision Rules&lt;/h2&gt;
&lt;p&gt;This deep dive shows us that a distributed saga is much more than a simple coding trick. It represents a fundamental paradigm shift in system architecture. To successfully apply this pattern in your production environments, stick to these core decision rules:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;Architectural Selection Framework:&lt;/strong&gt; If your system relies on two to four microservices with simple, linear workflows, use the Choreography model. However, if your architecture spans more than five services, or involves complex conditional logic and strict timeouts, pick an Orchestration engine like Temporal without hesitation. Debugging large-scale saga failures without central visibility is practically impossible.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Release and Tracking Mechanisms:&lt;/strong&gt; Once you deploy a distributed saga architecture to production, building full observability is mandatory. Generate a unique &lt;code&gt;trace_id&lt;/code&gt; or &lt;code&gt;saga_id&lt;/code&gt; at the very start of every user request. Use tools like OpenTelemetry to propagate that identifier across every microservice log and event payload. If a transaction fails in production, your distributed tracing dashboard will let you pinpoint the exact service and root cause behind the rollback in seconds.&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;When you master these low-level distributed mechanisms and build them cleanly into your production architecture, your system will handle network failures and heavy concurrency loads effortlessly.&lt;/p&gt;</content:encoded><category>System Design</category><category>Deep Dive</category><category>Distributed Systems</category><category>Microservices</category><category>Saga Pattern</category><category>Compensating Transactions</category><category>System Architecture</category><category>Under the hood</category><category>Kafka</category></item><item><title>The Ultimate System Design Handbook: Global Scale Architecture Through Real-World Case Studies</title><link>https://www.rafeuddaraj.me/blog/ultimate-system-design-handbook-case-study-global-scale/</link><guid isPermaLink="true">https://www.rafeuddaraj.me/blog/ultimate-system-design-handbook-case-study-global-scale/</guid><description>A complete engineering roadmap detailing how to scale a startup MVP to 10 million concurrent users, covering distributed databases, caching strategies, and microservice design patterns.</description><pubDate>Tue, 07 Jul 2026 18:59:54 GMT</pubDate><content:encoded>&lt;p&gt;When we start a new software project, we usually focus our energy on fast feature development, clean code, and building a polished user interface. However, the real test of our code and architecture only begins when actual user traffic starts hitting our production servers. A standard Monolith application can easily handle a load of 1,000 users, but when that user base scales to 1 million or 10 million, bottlenecks begin to emerge across every layer of the system. Servers crash, database tables lock up, and page load times stretch past 3 to 4 seconds-a delay that directly translates to lost revenue in the modern web era.&lt;/p&gt;
&lt;p&gt;System design is not about memorizing theoretical definitions; it is the practice of real-world engineering trade-off analysis. The core philosophy of this handbook is to identify bottlenecks through real-world case studies and engineer the correct architectural solutions. Rather than reading through standard dictionary definitions, we will analyze the scaling journey of a fictional startup platform called &quot;FoodFast&quot; alongside the actual system design patterns used by global tech giants. If you are a software engineer looking to take your skills to the next level and build production-grade systems, this handbook will serve as your complete, end-to-end roadmap.&lt;/p&gt;
&lt;hr&gt;
&lt;h2 id=&quot;foundational-mental-models-and-engineering-analogies&quot;&gt;Foundational Mental Models and Engineering Analogies&lt;/h2&gt;
&lt;p&gt;Before writing any code, we need to internalize a few real-world mental models to understand how large-scale systems fit together. When we design complex architectures, the same fundamental patterns appear over and over again. To understand these patterns easily, we can map them to familiar analogies from our daily lives. Below, we discuss four core engineering concepts alongside their real-world counterparts.&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;Vertical vs Horizontal Scaling (The Elevator vs. New Stairs Analogy):&lt;/strong&gt; When the foot traffic in your building increases, upgrading the elevator&apos;s motor to carry more weight is Vertical Scaling, or scaling up. However, there is a physical limit to how large that motor can be before you hit mechanical constraints. Instead of overworking that single motor, building a new staircase or installing additional elevators right next to it represents Horizontal Scaling, or scaling out. In software engineering, rather than buying an infinitely large CPU or adding endless RAM to a single machine, we connect multiple standard servers across a network to share the workload.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Load Balancer (The Traffic Officer Analogy):&lt;/strong&gt; When thousands of cars suddenly flood an intersection, a traffic officer stands in the center directing vehicles into different lanes to keep traffic moving smoothly. In our software systems, a Load Balancer performs that exact same duty. When millions of client requests hit our infrastructure, the load balancer uses round-robin or other routing algorithms to distribute that pressure evenly across our backend servers.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Monolith vs Microservices (The Single Kitchen vs. Food Court Analogy):&lt;/strong&gt; A Monolith is like running an entire restaurant out of one massive kitchen where all prepping, cooking, and plating happen together. If a major gas pipe leak occurs in that kitchen, the entire restaurant shuts down. On the other hand, Microservices operate like a large food court where the pizza booth, burger stand, and coffee shop are completely separated. If the espresso machine breaks down at the coffee shop, the pizza booth continues selling slices without interruption, keeping the overall business operational.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Database Indexing (The Book Index Analogy):&lt;/strong&gt; If you need to find a specific topic in a 1,000-page book, flipping through every single page from cover to cover is a Full Table Scan, which runs at an &lt;span class=&quot;katex&quot;&gt;&lt;span class=&quot;katex-html&quot; aria-hidden=&quot;true&quot;&gt;&lt;span class=&quot;base&quot;&gt;&lt;span class=&quot;strut&quot; style=&quot;height:1em;vertical-align:-0.25em;&quot;&gt;&lt;/span&gt;&lt;span class=&quot;mord mathnormal&quot; style=&quot;margin-right:0.0278em;&quot;&gt;O&lt;/span&gt;&lt;span class=&quot;mopen&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mord mathnormal&quot;&gt;n&lt;/span&gt;&lt;span class=&quot;mclose&quot;&gt;)&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/span&gt; time complexity. Looking at the index at the back of the book to jump directly to the correct page is Indexing. In our databases, we implement indexing using B-Tree data structures, allowing us to pinpoint the exact data we need from billions of records in &lt;span class=&quot;katex&quot;&gt;&lt;span class=&quot;katex-html&quot; aria-hidden=&quot;true&quot;&gt;&lt;span class=&quot;base&quot;&gt;&lt;span class=&quot;strut&quot; style=&quot;height:1em;vertical-align:-0.25em;&quot;&gt;&lt;/span&gt;&lt;span class=&quot;mord mathnormal&quot; style=&quot;margin-right:0.0278em;&quot;&gt;O&lt;/span&gt;&lt;span class=&quot;mopen&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mop&quot;&gt;lo&lt;span style=&quot;margin-right:0.0139em;&quot;&gt;g&lt;/span&gt;&lt;/span&gt;&lt;span class=&quot;mspace&quot; style=&quot;margin-right:0.1667em;&quot;&gt;&lt;/span&gt;&lt;span class=&quot;mord mathnormal&quot;&gt;n&lt;/span&gt;&lt;span class=&quot;mclose&quot;&gt;)&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/span&gt; time.&lt;/li&gt;
&lt;/ul&gt;
&lt;hr&gt;
&lt;h2 id=&quot;case-study-1-foodfast-mvp-launch-and-the-first-10000-users-monolith-separation&quot;&gt;Case Study 1: FoodFast MVP Launch and the First 10,000 Users (Monolith &amp;#x26; Separation)&lt;/h2&gt;
&lt;p&gt;Imagine you are the Chief Architect of a new food delivery startup called &quot;FoodFast.&quot; Your primary goal is to build a Minimum Viable Product (MVP) rapidly to validate your business idea in the market. At this stage, your budget is tight, and your engineering team is small. Therefore, instead of building a complex distributed architecture right away, you launch using a single-server Monolith application connected to a single relational database. For the first few months, everything runs smoothly, and your daily active user count hovers around a few hundred. However, after a successful digital marketing campaign, your user base explodes rapidly, reaching 10,000 active users.&lt;/p&gt;
&lt;p&gt;Right at this milestone, your system hits its first major engineering bottleneck. You notice that during peak lunch and dinner hours, the application&apos;s page load time increases dramatically, and the server&apos;s CPU utilization gets pegged at 100%. The root cause is simple: your web server code and your database queries are competing for the exact same CPU cores and memory resources on a single machine. As thousands of users simultaneously browse restaurant menus and place orders, memory exhaustion and disk I/O contention take over. Your application&apos;s thread pool becomes completely blocked while waiting for database queries to return, preventing the server from accepting any new incoming client requests.&lt;/p&gt;
&lt;p&gt;To solve this initial crisis, our first architectural move is App and DB Separation. We physically or virtually decouple the web server and the database into two separate machines. This allows the application server&apos;s CPU and thread pool to focus entirely on handling incoming HTTP requests, while the database server utilizes its own dedicated memory and disk resources to process queries. At the same time, we apply Vertical Scaling by upgrading our server hardware. We bump the application server from a 4-core CPU to a 16-core CPU, and we upgrade the database server&apos;s RAM from 16 GB to 64 GB. This immediate hardware upgrade restores system speed and stability. Below is an example of a production-ready database connection pool configuration after separating the app and database layers:&lt;/p&gt;
&lt;div class=&quot;expressive-code&quot;&gt;&lt;style&gt;.expressive-code{font-family:var(--ec-uiFontFml);font-size:var(--ec-uiFontSize);font-weight:var(--ec-uiFontWg);line-height:var(--ec-uiLineHt);text-size-adjust:none;-webkit-text-size-adjust:none}.expressive-code *:not(:is(svg, svg *)){all:revert;box-sizing:border-box}.expressive-code pre{display:flex;margin:0;padding:0;border:var(--ec-brdWd) solid var(--ec-brdCol);border-radius:calc(var(--ec-brdRad) + var(--ec-brdWd));background:var(--ec-codeBg)}.expressive-code pre:focus-visible{outline:3px solid var(--ec-focusBrd);outline-offset:-3px}.expressive-code pre &gt; code{all:unset;display:block;flex:1 0 100%;padding:var(--ec-codePadBlk) 0;color:var(--ec-codeFg);font-family:var(--ec-codeFontFml);font-size:var(--ec-codeFontSize);font-weight:var(--ec-codeFontWg);line-height:var(--ec-codeLineHt)}.expressive-code pre{overflow-x:auto}.expressive-code pre.wrap .ec-line .code{white-space:pre-wrap;overflow-wrap:break-word;min-width:min(20ch, var(--ecMaxLine, 20ch))}.expressive-code pre.wrap .ec-line .code span.indent{white-space:pre}.expressive-code pre::-webkit-scrollbar,.expressive-code pre::-webkit-scrollbar-track{background-color:inherit;border-radius:calc(var(--ec-brdRad) + var(--ec-brdWd));border-top-left-radius:0;border-top-right-radius:0}.expressive-code pre::-webkit-scrollbar-thumb{background-color:var(--ec-sbThumbCol);border:4px solid transparent;background-clip:content-box;border-radius:10px}.expressive-code pre::-webkit-scrollbar-thumb:hover{background-color:var(--ec-sbThumbHoverCol)}.expressive-code pre::-webkit-scrollbar-corner{background:transparent}.expressive-code .ec-line{direction:ltr;unicode-bidi:isolate;display:grid;grid-template-areas:&apos;gutter code&apos;;grid-template-columns:auto 1fr;position:relative}.expressive-code .ec-line .gutter{grid-area:gutter;color:var(--ec-gtrFg)}.expressive-code .ec-line .gutter &gt; *{pointer-events:none;user-select:none;-webkit-user-select:none}.expressive-code .ec-line .gutter ~ .code{--ecLineBrdCol:var(--ec-gtrBrdCol)}.expressive-code .ec-line.highlight .gutter{color:var(--ec-gtrHlFg)}.expressive-code .ec-line .code{grid-area:code;position:relative;box-sizing:content-box;padding-inline-start:calc(var(--ecIndent, 0ch) + var(--ec-codePadInl) - var(--ecGtrBrdWd));padding-inline-end:var(--ec-codePadInl);text-indent:calc(var(--ecIndent, 0ch) * -1)}.expressive-code .ec-line .code::before,.expressive-code .ec-line .code::after,.expressive-code .ec-line .code :where(*){text-indent:0}.expressive-code .ec-line .code{--ecGtrBrdWd:var(--ec-gtrBrdWd);border-inline-start:var(--ecGtrBrdWd) solid var(--ecLineBrdCol, transparent)}.expressive-code .sr-only{position:absolute;width:1px;height:1px;padding:0;margin:-1px;overflow:hidden;clip:rect(0, 0, 0, 0);white-space:nowrap;border-width:0}.expressive-code .ec-line.mark{--tmLineBgCol:var(--ec-tm-markBg)}.expressive-code .ec-line.mark .code{--ecLineBrdCol:var(--ec-tm-markBrdCol)}.expressive-code .ec-line.ins{--tmLineBgCol:var(--ec-tm-insBg);--tmLabel:var(--ec-tm-insDiffIndContent)}.expressive-code .ec-line.ins .code{--ecLineBrdCol:var(--ec-tm-insBrdCol)}.expressive-code .ec-line.ins .code::before{color:var(--ec-tm-insDiffIndCol)}.expressive-code .ec-line.del{--tmLineBgCol:var(--ec-tm-delBg);--tmLabel:var(--ec-tm-delDiffIndContent)}.expressive-code .ec-line.del .code{--ecLineBrdCol:var(--ec-tm-delBrdCol)}.expressive-code .ec-line.del .code::before{color:var(--ec-tm-delDiffIndCol)}.expressive-code .ec-line.mark,.expressive-code .ec-line.ins,.expressive-code .ec-line.del{background:var(--tmLineBgCol)}.expressive-code .ec-line.mark .code,.expressive-code .ec-line.ins .code,.expressive-code .ec-line.del .code{--ecGtrBrdWd:var(--ec-tm-lineMarkerAccentWd)}.expressive-code .ec-line.mark .code::before,.expressive-code .ec-line.ins .code::before,.expressive-code .ec-line.del .code::before{display:block;position:absolute;left:0;box-sizing:border-box;content:var(--tmLabel, &apos; &apos;);padding-inline-start:var(--ec-tm-lineDiffIndMargLeft);text-align:center;white-space:pre}.expressive-code .ec-line.mark.tm-label .code::before,.expressive-code .ec-line.ins.tm-label .code::before,.expressive-code .ec-line.del.tm-label .code::before{background:var(--ecLineBrdCol);padding:0 calc(var(--ec-tm-lineMarkerLabelPadInl) + var(--ec-tm-lineMarkerAccentWd)) 0 var(--ec-tm-lineMarkerLabelPadInl);color:var(--ec-tm-lineMarkerLabelCol)}.expressive-code .ec-line mark{--tmInlineBgCol:var(--ec-tm-markBg);--tmInlineBrdCol:var(--ec-tm-markBrdCol)}.expressive-code .ec-line ins{--tmInlineBgCol:var(--ec-tm-insBg);--tmInlineBrdCol:var(--ec-tm-insBrdCol)}.expressive-code .ec-line del{--tmInlineBgCol:var(--ec-tm-delBg);--tmInlineBrdCol:var(--ec-tm-delBrdCol)}.expressive-code .ec-line mark,.expressive-code .ec-line ins,.expressive-code .ec-line del{all:unset;display:inline-block;position:relative;--tmBrdL:var(--ec-tm-inlMarkerBrdWd);--tmBrdR:var(--ec-tm-inlMarkerBrdWd);--tmRadL:var(--ec-tm-inlMarkerBrdRad);--tmRadR:var(--ec-tm-inlMarkerBrdRad);margin-inline:0.025rem;padding-inline:var(--ec-tm-inlMarkerPad);border-radius:var(--tmRadL) var(--tmRadR) var(--tmRadR) var(--tmRadL);background:var(--tmInlineBgCol);background-clip:padding-box}.expressive-code .ec-line mark.open-start,.expressive-code .ec-line ins.open-start,.expressive-code .ec-line del.open-start{margin-inline-start:0;padding-inline-start:0;--tmBrdL:0px;--tmRadL:0}.expressive-code .ec-line mark.open-end,.expressive-code .ec-line ins.open-end,.expressive-code .ec-line del.open-end{margin-inline-end:0;padding-inline-end:0;--tmBrdR:0px;--tmRadR:0}.expressive-code .ec-line mark::before,.expressive-code .ec-line ins::before,.expressive-code .ec-line del::before{content:&apos;&apos;;position:absolute;pointer-events:none;display:inline-block;inset:0;border-radius:var(--tmRadL) var(--tmRadR) var(--tmRadR) var(--tmRadL);border:var(--ec-tm-inlMarkerBrdWd) solid var(--tmInlineBrdCol);border-inline-width:var(--tmBrdL) var(--tmBrdR)}.expressive-code .frame{all:unset;position:relative;display:block;--header-border-radius:calc(var(--ec-brdRad) + var(--ec-brdWd));--tab-border-radius:calc(var(--ec-frm-edTabBrdRad) + var(--ec-brdWd));--button-spacing:0.4rem;--code-background:var(--ec-frm-edBg);border-radius:var(--header-border-radius);box-shadow:var(--ec-frm-frameBoxShdCssVal)}.expressive-code .frame .header{display:none;z-index:1;position:relative;border-radius:var(--header-border-radius) var(--header-border-radius) 0 0}.expressive-code .frame.has-title pre,.expressive-code .frame.has-title code,.expressive-code .frame.is-terminal pre,.expressive-code .frame.is-terminal code{border-top:none;border-top-left-radius:0;border-top-right-radius:0}.expressive-code .frame .title:empty:before{content:&apos;\a0&apos;}.expressive-code .frame.has-title:not(.is-terminal){--button-spacing:calc(1.9rem + 2 * (var(--ec-uiPadBlk) + var(--ec-frm-edActTabIndHt)))}.expressive-code .frame.has-title:not(.is-terminal) .title{position:relative;color:var(--ec-frm-edActTabFg);background:var(--ec-frm-edActTabBg);background-clip:padding-box;margin-block-start:var(--ec-frm-edTabsMargBlkStart);padding:calc(var(--ec-uiPadBlk) + var(--ec-frm-edActTabIndHt)) var(--ec-uiPadInl);border:var(--ec-brdWd) solid var(--ec-frm-edActTabBrdCol);border-radius:var(--tab-border-radius) var(--tab-border-radius) 0 0;border-bottom:none;overflow:hidden}.expressive-code .frame.has-title:not(.is-terminal) .title::after{content:&apos;&apos;;position:absolute;pointer-events:none;inset:0;border-top:var(--ec-frm-edActTabIndHt) solid var(--ec-frm-edActTabIndTopCol);border-bottom:var(--ec-frm-edActTabIndHt) solid var(--ec-frm-edActTabIndBtmCol)}.expressive-code .frame.has-title:not(.is-terminal) .header{display:flex;background:linear-gradient(to top, var(--ec-frm-edTabBarBrdBtmCol) var(--ec-brdWd), transparent var(--ec-brdWd)),linear-gradient(var(--ec-frm-edTabBarBg), var(--ec-frm-edTabBarBg));background-repeat:no-repeat;padding-inline-start:var(--ec-frm-edTabsMargInlStart)}.expressive-code .frame.has-title:not(.is-terminal) .header::before{content:&apos;&apos;;position:absolute;pointer-events:none;inset:0;border:var(--ec-brdWd) solid var(--ec-frm-edTabBarBrdCol);border-radius:inherit;border-bottom:none}.expressive-code .frame.is-terminal{--button-spacing:calc(1.9rem + var(--ec-brdWd) + 2 * var(--ec-uiPadBlk));--code-background:var(--ec-frm-trmBg)}.expressive-code .frame.is-terminal .header{display:flex;align-items:center;justify-content:center;padding-block:var(--ec-uiPadBlk);padding-block-end:calc(var(--ec-uiPadBlk) + var(--ec-brdWd));position:relative;font-weight:500;letter-spacing:0.025ch;color:var(--ec-frm-trmTtbFg);background:var(--ec-frm-trmTtbBg);border:var(--ec-brdWd) solid var(--ec-brdCol);border-bottom:none}.expressive-code .frame.is-terminal .header::before{content:&apos;&apos;;position:absolute;pointer-events:none;left:var(--ec-uiPadInl);width:2.1rem;height:0.56rem;line-height:0;background-color:var(--ec-frm-trmTtbDotsFg);opacity:var(--ec-frm-trmTtbDotsOpa);-webkit-mask-image:var(--ec-frm-trmIcon);-webkit-mask-repeat:no-repeat;mask-image:var(--ec-frm-trmIcon);mask-repeat:no-repeat}.expressive-code .frame.is-terminal .header::after{content:&apos;&apos;;position:absolute;pointer-events:none;inset:0;border-bottom:var(--ec-brdWd) solid var(--ec-frm-trmTtbBrdBtmCol)}.expressive-code .frame pre{background:var(--code-background)}.expressive-code .copy{display:flex;gap:0.25rem;flex-direction:row;position:absolute;inset-block-start:calc(var(--ec-brdWd) + var(--button-spacing));inset-inline-end:calc(var(--ec-brdWd) + var(--ec-uiPadInl) / 2)}@media (scripting: none){.expressive-code .copy{display:none}}.expressive-code .copy{direction:ltr;unicode-bidi:isolate}.expressive-code .copy button{position:relative;align-self:flex-end;margin:0;padding:0;border:none;border-radius:0.2rem;z-index:1;cursor:pointer;transition-property:opacity, background, border-color;transition-duration:0.2s;transition-timing-function:cubic-bezier(0.25, 0.46, 0.45, 0.94);width:2.5rem;height:2.5rem;background:var(--code-background);opacity:0.75}.expressive-code .copy button div{position:absolute;inset:0;border-radius:inherit;background:var(--ec-frm-inlBtnBg);opacity:var(--ec-frm-inlBtnBgIdleOpa);transition-property:inherit;transition-duration:inherit;transition-timing-function:inherit}.expressive-code .copy button::before{content:&apos;&apos;;position:absolute;pointer-events:none;inset:0;border-radius:inherit;border:var(--ec-brdWd) solid var(--ec-frm-inlBtnBrd);opacity:var(--ec-frm-inlBtnBrdOpa)}.expressive-code .copy button::after{content:&apos;&apos;;position:absolute;pointer-events:none;inset:0;background-color:var(--ec-frm-inlBtnFg);-webkit-mask-image:var(--ec-frm-copyIcon);-webkit-mask-repeat:no-repeat;mask-image:var(--ec-frm-copyIcon);mask-repeat:no-repeat;margin:0.475rem;line-height:0}.expressive-code .copy button:hover,.expressive-code .copy button:focus:focus-visible{opacity:1}.expressive-code .copy button:hover div,.expressive-code .copy button:focus:focus-visible div{opacity:var(--ec-frm-inlBtnBgHoverOrFocusOpa)}.expressive-code .copy button:active{opacity:1}.expressive-code .copy button:active div{opacity:var(--ec-frm-inlBtnBgActOpa)}.expressive-code .copy .feedback{--tooltip-arrow-size:0.35rem;--tooltip-bg:var(--ec-frm-tooltipSuccessBg);color:var(--ec-frm-tooltipSuccessFg);pointer-events:none;user-select:none;-webkit-user-select:none;position:relative;align-self:center;background-color:var(--tooltip-bg);z-index:99;padding:0.125rem 0.75rem;border-radius:0.2rem;margin-inline-end:var(--tooltip-arrow-size);opacity:0;transition-property:opacity, transform;transition-duration:0.2s;transition-timing-function:ease-in-out;transform:translate3d(0, 0.25rem, 0)}.expressive-code .copy .feedback::after{content:&apos;&apos;;position:absolute;pointer-events:none;top:calc(50% - var(--tooltip-arrow-size));inset-inline-end:calc(-2 * (var(--tooltip-arrow-size) - 0.5px));border:var(--tooltip-arrow-size) solid transparent;border-inline-start-color:var(--tooltip-bg)}.expressive-code .copy .feedback.show{opacity:1;transform:translate3d(0, 0, 0)}@media (hover: hover){.expressive-code{}.expressive-code .copy button{opacity:0;width:2rem;height:2rem}.expressive-code .frame:hover .copy button:not(:hover),.expressive-code .frame:focus-within :focus-visible ~ .copy button:not(:hover),.expressive-code .frame .copy .feedback.show ~ button:not(:hover){opacity:0.75}}.expressive-code :nth-child(1 of .ec-line) .code{padding-inline-end:calc(2rem + var(--ec-codePadInl))}:root{--ec-brdRad:0.75rem;--ec-brdWd:1.5px;--ec-brdCol:var(--code-line);--ec-codeFontFml:var(--font-code);--ec-codeFontSize:0.875rem;--ec-codeFontWg:400;--ec-codeLineHt:1.75;--ec-codePadBlk:1rem;--ec-codePadInl:1.125rem;--ec-codeBg:var(--code-bg);--ec-codeFg:#e6edf3;--ec-codeSelBg:#264f78;--ec-gtrFg:#6e7681;--ec-gtrBrdCol:#6e768133;--ec-gtrBrdWd:1.5px;--ec-gtrHlFg:#e6edf3;--ec-uiFontFml:var(--font-mono);--ec-uiFontSize:0.75rem;--ec-uiFontWg:400;--ec-uiLineHt:1.65;--ec-uiPadBlk:0.25rem;--ec-uiPadInl:1rem;--ec-uiSelBg:#6e768166;--ec-uiSelFg:#e6edf3;--ec-focusBrd:#1f6feb;--ec-sbThumbCol:#8b949e33;--ec-sbThumbHoverCol:#8b949e3d;--ec-tm-lineMarkerAccentMarg:0rem;--ec-tm-lineMarkerAccentWd:0.15rem;--ec-tm-lineMarkerLabelPadInl:0.2rem;--ec-tm-lineMarkerLabelCol:white;--ec-tm-lineDiffIndMargLeft:0.3rem;--ec-tm-inlMarkerBrdWd:1.5px;--ec-tm-inlMarkerBrdRad:0.2rem;--ec-tm-inlMarkerPad:0.15rem;--ec-tm-insDiffIndContent:&apos;+&apos;;--ec-tm-delDiffIndContent:&apos;-&apos;;--ec-tm-markBg:#264a8980;--ec-tm-markBrdCol:#5570b3d0;--ec-tm-insBg:#26561c80;--ec-tm-insBrdCol:#4e7e41d0;--ec-tm-insDiffIndCol:#7eb070d0;--ec-tm-delBg:#81322b80;--ec-tm-delBrdCol:#ae594fd0;--ec-tm-delDiffIndCol:#e68a7ed0;--ec-frm-shdCol:#0000005b;--ec-frm-frameBoxShdCssVal:none;--ec-frm-edActTabBg:var(--code-bg);--ec-frm-edActTabFg:var(--code-muted);--ec-frm-edActTabBrdCol:transparent;--ec-frm-edActTabIndHt:1.5px;--ec-frm-edActTabIndTopCol:transparent;--ec-frm-edActTabIndBtmCol:#0d1117;--ec-frm-edTabsMargInlStart:0;--ec-frm-edTabsMargBlkStart:0;--ec-frm-edTabBrdRad:0.75rem;--ec-frm-edTabBarBg:var(--code-bg);--ec-frm-edTabBarBrdCol:var(--code-line);--ec-frm-edTabBarBrdBtmCol:var(--code-line);--ec-frm-edBg:var(--code-bg);--ec-frm-trmTtbFg:var(--code-muted);--ec-frm-trmTtbDotsFg:var(--code-muted);--ec-frm-trmTtbDotsOpa:0.15;--ec-frm-trmTtbBg:var(--code-bg);--ec-frm-trmTtbBrdBtmCol:var(--code-line);--ec-frm-trmBg:var(--code-bg);--ec-frm-inlBtnBg:var(--code-ink);--ec-frm-inlBtnBgIdleOpa:0;--ec-frm-inlBtnBgHoverOrFocusOpa:0.2;--ec-frm-inlBtnBgActOpa:0.3;--ec-frm-inlBtnFg:var(--code-ink);--ec-frm-inlBtnBrd:var(--code-line);--ec-frm-inlBtnBrdOpa:0.4;--ec-frm-tooltipSuccessBg:var(--color-emerald);--ec-frm-tooltipSuccessFg:var(--color-bg);--ec-frm-copyIcon:url(&quot;data:image/svg+xml,%3Csvg%20xmlns%3D&apos;http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg&apos;%20viewBox%3D&apos;0%200%2024%2024&apos;%20fill%3D&apos;none&apos;%20stroke%3D&apos;black&apos;%20stroke-width%3D&apos;1.75&apos;%3E%3Cpath%20d%3D&apos;M3%2019a2%202%200%200%201-1-2V2a2%202%200%200%201%201-1h13a2%202%200%200%201%202%201&apos;%2F%3E%3Crect%20x%3D&apos;6&apos;%20y%3D&apos;5&apos;%20width%3D&apos;16&apos;%20height%3D&apos;18&apos;%20rx%3D&apos;1.5&apos;%20ry%3D&apos;1.5&apos;%2F%3E%3C%2Fsvg%3E&quot;);--ec-frm-trmIcon:url(&quot;data:image/svg+xml,%3Csvg%20xmlns%3D&apos;http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg&apos;%20viewBox%3D&apos;0%200%2060%2016&apos;%20preserveAspectRatio%3D&apos;xMidYMid%20meet&apos;%3E%3Ccircle%20cx%3D&apos;8&apos;%20cy%3D&apos;8&apos;%20r%3D&apos;8&apos;%2F%3E%3Ccircle%20cx%3D&apos;30&apos;%20cy%3D&apos;8&apos;%20r%3D&apos;8&apos;%2F%3E%3Ccircle%20cx%3D&apos;52&apos;%20cy%3D&apos;8&apos;%20r%3D&apos;8&apos;%2F%3E%3C%2Fsvg%3E&quot;)}.expressive-code .ec-line :where(span[style^=&apos;--&apos;]:not([class])){color:var(--0, inherit);background-color:var(--0bg, transparent);font-style:var(--0fs, inherit);font-weight:var(--0fw, inherit);text-decoration:var(--0td, inherit)}&lt;/style&gt;&lt;script type=&quot;module&quot; src=&quot;/_astro/ec.0vx5m.js&quot;&gt;&lt;/script&gt;&lt;figure class=&quot;frame has-title&quot;&gt;&lt;figcaption class=&quot;header&quot;&gt;&lt;span class=&quot;title&quot;&gt;JavaScript&lt;/span&gt;&lt;/figcaption&gt;&lt;pre data-language=&quot;javascript&quot;&gt;&lt;code&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span style=&quot;--0:#8B949E&quot;&gt;// db-pool-config.js&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span style=&quot;--0:#8B949E&quot;&gt;// Production-ready PostgreSQL connection pool setup using &apos;pg&apos; module&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;const&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; { &lt;/span&gt;&lt;span style=&quot;--0:#79C0FF&quot;&gt;Pool&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; } &lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;=&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; &lt;/span&gt;&lt;span style=&quot;--0:#D2A8FF&quot;&gt;require&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;(&lt;/span&gt;&lt;span style=&quot;--0:#A5D6FF&quot;&gt;&apos;pg&apos;&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;);&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;
&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;const&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; &lt;/span&gt;&lt;span style=&quot;--0:#79C0FF&quot;&gt;pool&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; &lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;=&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; &lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;new&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; &lt;/span&gt;&lt;span style=&quot;--0:#D2A8FF&quot;&gt;Pool&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;({&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span class=&quot;indent&quot;&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;  &lt;/span&gt;&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;host: process.env.&lt;/span&gt;&lt;span style=&quot;--0:#79C0FF&quot;&gt;DB_HOST&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; &lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;||&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; &lt;/span&gt;&lt;span style=&quot;--0:#A5D6FF&quot;&gt;&apos;db-primary.foodfast.internal&apos;&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;,&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span class=&quot;indent&quot;&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;  &lt;/span&gt;&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;port: &lt;/span&gt;&lt;span style=&quot;--0:#D2A8FF&quot;&gt;parseInt&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;(process.env.&lt;/span&gt;&lt;span style=&quot;--0:#79C0FF&quot;&gt;DB_PORT&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; &lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;||&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; &lt;/span&gt;&lt;span style=&quot;--0:#A5D6FF&quot;&gt;&apos;5432&apos;&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;, &lt;/span&gt;&lt;span style=&quot;--0:#79C0FF&quot;&gt;10&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;),&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span class=&quot;indent&quot;&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;  &lt;/span&gt;&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;database: process.env.&lt;/span&gt;&lt;span style=&quot;--0:#79C0FF&quot;&gt;DB_NAME&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; &lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;||&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; &lt;/span&gt;&lt;span style=&quot;--0:#A5D6FF&quot;&gt;&apos;foodfast_production&apos;&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;,&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span class=&quot;indent&quot;&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;  &lt;/span&gt;&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;user: process.env.&lt;/span&gt;&lt;span style=&quot;--0:#79C0FF&quot;&gt;DB_USER&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; &lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;||&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; &lt;/span&gt;&lt;span style=&quot;--0:#A5D6FF&quot;&gt;&apos;admin_user&apos;&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;,&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span class=&quot;indent&quot;&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;  &lt;/span&gt;&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;password: process.env.&lt;/span&gt;&lt;span style=&quot;--0:#79C0FF&quot;&gt;DB_PASSWORD&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;,&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span class=&quot;indent&quot;&gt;  &lt;/span&gt;&lt;span style=&quot;--0:#8B949E&quot;&gt;// Limit the maximum number of clients in the pool to prevent memory exhaustion&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span class=&quot;indent&quot;&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;  &lt;/span&gt;&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;max: &lt;/span&gt;&lt;span style=&quot;--0:#79C0FF&quot;&gt;25&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;,&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span class=&quot;indent&quot;&gt;  &lt;/span&gt;&lt;span style=&quot;--0:#8B949E&quot;&gt;// Close idle clients after 30 seconds of inactivity&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span class=&quot;indent&quot;&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;  &lt;/span&gt;&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;idleTimeoutMillis: &lt;/span&gt;&lt;span style=&quot;--0:#79C0FF&quot;&gt;30000&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;,&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span class=&quot;indent&quot;&gt;  &lt;/span&gt;&lt;span style=&quot;--0:#8B949E&quot;&gt;// Return an error after 2 seconds if connection could not be established&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span class=&quot;indent&quot;&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;  &lt;/span&gt;&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;connectionTimeoutMillis: &lt;/span&gt;&lt;span style=&quot;--0:#79C0FF&quot;&gt;2000&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;,&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;});&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;
&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;pool.&lt;/span&gt;&lt;span style=&quot;--0:#D2A8FF&quot;&gt;on&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;(&lt;/span&gt;&lt;span style=&quot;--0:#A5D6FF&quot;&gt;&apos;error&apos;&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;, (&lt;/span&gt;&lt;span style=&quot;--0:#FFA657&quot;&gt;err&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;, &lt;/span&gt;&lt;span style=&quot;--0:#FFA657&quot;&gt;client&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;) &lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;=&gt;&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; {&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span class=&quot;indent&quot;&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;  &lt;/span&gt;&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;console.&lt;/span&gt;&lt;span style=&quot;--0:#D2A8FF&quot;&gt;error&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;(&lt;/span&gt;&lt;span style=&quot;--0:#A5D6FF&quot;&gt;&apos;Unexpected error on idle database client in FoodFast cluster&apos;&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;, err);&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span class=&quot;indent&quot;&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;  &lt;/span&gt;&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;process.&lt;/span&gt;&lt;span style=&quot;--0:#D2A8FF&quot;&gt;exit&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;(&lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;-&lt;/span&gt;&lt;span style=&quot;--0:#79C0FF&quot;&gt;1&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;);&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;});&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;
&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span style=&quot;--0:#79C0FF&quot;&gt;module&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;.&lt;/span&gt;&lt;span style=&quot;--0:#79C0FF&quot;&gt;exports&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; &lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;=&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; {&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span class=&quot;indent&quot;&gt;  &lt;/span&gt;&lt;span style=&quot;--0:#D2A8FF&quot;&gt;query&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;: (&lt;/span&gt;&lt;span style=&quot;--0:#FFA657&quot;&gt;text&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;, &lt;/span&gt;&lt;span style=&quot;--0:#FFA657&quot;&gt;params&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;) &lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;=&gt;&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; pool.&lt;/span&gt;&lt;span style=&quot;--0:#D2A8FF&quot;&gt;query&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;(text, params),&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span class=&quot;indent&quot;&gt;  &lt;/span&gt;&lt;span style=&quot;--0:#D2A8FF&quot;&gt;getPool&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;: () &lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;=&gt;&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; pool,&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;};&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;/code&gt;&lt;/pre&gt;&lt;div class=&quot;copy&quot;&gt;&lt;div aria-live=&quot;polite&quot;&gt;&lt;/div&gt;&lt;button title=&quot;Copy to clipboard&quot; data-copied=&quot;Copied!&quot; data-code=&quot;// db-pool-config.js// Production-ready PostgreSQL connection pool setup using &amp;#x27;pg&amp;#x27; moduleconst { Pool } = require(&amp;#x27;pg&amp;#x27;);const pool = new Pool({  host: process.env.DB_HOST || &amp;#x27;db-primary.foodfast.internal&amp;#x27;,  port: parseInt(process.env.DB_PORT || &amp;#x27;5432&amp;#x27;, 10),  database: process.env.DB_NAME || &amp;#x27;foodfast_production&amp;#x27;,  user: process.env.DB_USER || &amp;#x27;admin_user&amp;#x27;,  password: process.env.DB_PASSWORD,  // Limit the maximum number of clients in the pool to prevent memory exhaustion  max: 25,  // Close idle clients after 30 seconds of inactivity  idleTimeoutMillis: 30000,  // Return an error after 2 seconds if connection could not be established  connectionTimeoutMillis: 2000,});pool.on(&amp;#x27;error&amp;#x27;, (err, client) =&gt; {  console.error(&amp;#x27;Unexpected error on idle database client in FoodFast cluster&amp;#x27;, err);  process.exit(-1);});module.exports = {  query: (text, params) =&gt; pool.query(text, params),  getPool: () =&gt; pool,};&quot;&gt;&lt;div&gt;&lt;/div&gt;&lt;/button&gt;&lt;/div&gt;&lt;/figure&gt;&lt;/div&gt;
&lt;div class=&quot;callout&quot; role=&quot;note&quot; data-type=&quot;note&quot;&gt;
&lt;p class=&quot;callout-title&quot;&gt;Connection Pooling Efficiency&lt;/p&gt;
&lt;p&gt;Opening a new database connection for every incoming request is an expensive operation because it requires a fresh TCP handshake and authentication step each time. Using a connection pool keeps a set of reusable connections open in memory, which significantly reduces query latency.&lt;/p&gt;
&lt;/div&gt;
&lt;hr&gt;
&lt;h2 id=&quot;case-study-2-foodfast-flash-sale-crisis-and-1-million-users-horizontal-scaling-load-balancing&quot;&gt;Case Study 2: FoodFast Flash Sale Crisis and 1 Million Users (Horizontal Scaling &amp;#x26; Load Balancing)&lt;/h2&gt;
&lt;p&gt;As FoodFast&apos;s active user count hits 100,000, your marketing team announces a &quot;Midnight Flash Sale&quot; to drive further business growth. At exactly 12:00 AM, partner restaurants will offer a 50% discount on popular menu items. At 11:59 PM, 100,000 users log into the platform simultaneously, and at the stroke of midnight, thousands of order requests flood the API at once. Within seconds, your powerful 16-core web server crashes from an Out of Memory (OOM) error. The entire platform goes dark, and frustrated users immediately begin posting negative reviews across social media.&lt;/p&gt;
&lt;p&gt;This failure proves that vertical scaling has strict physical and financial limits. You cannot simply install unlimited RAM or CPUs into a single server box, and relying on one machine introduces a Single Point of Failure (SPOF) into your architecture. The only sustainable way out of this crisis is to implement Horizontal Scaling. Instead of relying on one expensive super-server, we deploy 10 standard commodity servers running in parallel across our network. However, this introduces a new routing challenge: how do our clients&apos; mobile apps and web browsers know which specific server IP to send their traffic to?&lt;/p&gt;
&lt;p&gt;To solve this routing problem, we place a Load Balancing Layer directly in front of our application server cluster using tools like Nginx or HAProxy. This load balancer handles Layer 4 (Transport Layer) or Layer 7 (Application Layer) routing. We configure Nginx to use the Least Connections algorithm, which inspects the cluster and routes incoming requests to whichever server currently has the fewest active workloads. However, running across multiple servers requires us to make our application tier completely Stateless. Previously, user login sessions were stored in the local memory of our single server-a pattern known as sticky sessions. Now that requests can land on any server in the cluster, we move our session management out of local memory and into a centralized Redis session store, while adopting stateless JSON Web Tokens (JWT) on the client side.&lt;/p&gt;
&lt;div class=&quot;expressive-code&quot;&gt;&lt;figure class=&quot;frame has-title&quot;&gt;&lt;figcaption class=&quot;header&quot;&gt;&lt;span class=&quot;title&quot;&gt;Nginx&lt;/span&gt;&lt;/figcaption&gt;&lt;pre data-language=&quot;nginx&quot;&gt;&lt;code&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span style=&quot;--0:#8B949E&quot;&gt;# nginx-load-balancer.conf&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span style=&quot;--0:#8B949E&quot;&gt;# Layer 7 Load Balancing configuration for FoodFast backend cluster&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;upstream&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; &lt;/span&gt;&lt;span style=&quot;--0:#FFA657&quot;&gt;foodfast_backend_cluster &lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;{&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span class=&quot;indent&quot;&gt;    &lt;/span&gt;&lt;span style=&quot;--0:#8B949E&quot;&gt;# Routelessly distribute load to the server with the least active connections&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span class=&quot;indent&quot;&gt;    &lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;least_conn&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;;&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;
&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span class=&quot;indent&quot;&gt;    &lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;server&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; app-node-01.foodfast.internal:3000 &lt;/span&gt;&lt;span style=&quot;--0:#FFA657&quot;&gt;max_fails&lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;=&lt;/span&gt;&lt;span style=&quot;--0:#79C0FF&quot;&gt;3&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; fail_timeout=10s;&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span class=&quot;indent&quot;&gt;    &lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;server&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; app-node-02.foodfast.internal:3000 &lt;/span&gt;&lt;span style=&quot;--0:#FFA657&quot;&gt;max_fails&lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;=&lt;/span&gt;&lt;span style=&quot;--0:#79C0FF&quot;&gt;3&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; fail_timeout=10s;&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span class=&quot;indent&quot;&gt;    &lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;server&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; app-node-03.foodfast.internal:3000 &lt;/span&gt;&lt;span style=&quot;--0:#FFA657&quot;&gt;max_fails&lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;=&lt;/span&gt;&lt;span style=&quot;--0:#79C0FF&quot;&gt;3&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; fail_timeout=10s;&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span class=&quot;indent&quot;&gt;    &lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;server&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; app-node-04.foodfast.internal:3000 &lt;/span&gt;&lt;span style=&quot;--0:#FFA657&quot;&gt;max_fails&lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;=&lt;/span&gt;&lt;span style=&quot;--0:#79C0FF&quot;&gt;3&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; fail_timeout=10s;&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span class=&quot;indent&quot;&gt;    &lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;server&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; app-node-05.foodfast.internal:3000 &lt;/span&gt;&lt;span style=&quot;--0:#FFA657&quot;&gt;max_fails&lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;=&lt;/span&gt;&lt;span style=&quot;--0:#79C0FF&quot;&gt;3&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; fail_timeout=10s;&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;
&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span class=&quot;indent&quot;&gt;    &lt;/span&gt;&lt;span style=&quot;--0:#8B949E&quot;&gt;# Maintain open keepalive connections between Nginx and backend servers&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span class=&quot;indent&quot;&gt;   &lt;span style=&quot;--0:#FF7B72&quot;&gt; &lt;/span&gt;&lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;keepalive &lt;/span&gt;&lt;span style=&quot;--0:#79C0FF&quot;&gt;64&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;;&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;}&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;
&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;server&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; {&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span class=&quot;indent&quot;&gt;   &lt;span style=&quot;--0:#FF7B72&quot;&gt; &lt;/span&gt;&lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;listen &lt;/span&gt;&lt;span style=&quot;--0:#79C0FF&quot;&gt;80&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;;&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span class=&quot;indent&quot;&gt;   &lt;span style=&quot;--0:#FF7B72&quot;&gt; &lt;/span&gt;&lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;server_name &lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;api.foodfast.com;&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;
&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span class=&quot;indent&quot;&gt;    &lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;location&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; &lt;/span&gt;&lt;span style=&quot;--0:#FFA657&quot;&gt;/ &lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;{&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span class=&quot;indent&quot;&gt;       &lt;span style=&quot;--0:#FF7B72&quot;&gt; &lt;/span&gt;&lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;proxy_pass &lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;http://foodfast_backend_cluster;&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span class=&quot;indent&quot;&gt;       &lt;span style=&quot;--0:#FF7B72&quot;&gt; &lt;/span&gt;&lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;proxy_http_version &lt;/span&gt;&lt;span style=&quot;--0:#79C0FF&quot;&gt;1.1&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;;&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span class=&quot;indent&quot;&gt;       &lt;span style=&quot;--0:#FF7B72&quot;&gt; &lt;/span&gt;&lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;proxy_set_header &lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;Connection &lt;/span&gt;&lt;span style=&quot;--0:#A5D6FF&quot;&gt;&quot;&quot;&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;;&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span class=&quot;indent&quot;&gt;       &lt;span style=&quot;--0:#FF7B72&quot;&gt; &lt;/span&gt;&lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;proxy_set_header &lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;X-Real-IP $remote_addr;&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span class=&quot;indent&quot;&gt;       &lt;span style=&quot;--0:#FF7B72&quot;&gt; &lt;/span&gt;&lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;proxy_set_header &lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;X-Forwarded-For $proxy_add_x_forwarded_for;&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span class=&quot;indent&quot;&gt;       &lt;span style=&quot;--0:#FF7B72&quot;&gt; &lt;/span&gt;&lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;proxy_set_header &lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;Host $http_host;&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;
&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span class=&quot;indent&quot;&gt;        &lt;/span&gt;&lt;span style=&quot;--0:#8B949E&quot;&gt;# Strict timeout configurations to prevent hanging requests during spikes&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span class=&quot;indent&quot;&gt;       &lt;span style=&quot;--0:#FF7B72&quot;&gt; &lt;/span&gt;&lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;proxy_connect_timeout &lt;/span&gt;&lt;span style=&quot;--0:#79C0FF&quot;&gt;3s&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;;&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span class=&quot;indent&quot;&gt;       &lt;span style=&quot;--0:#FF7B72&quot;&gt; &lt;/span&gt;&lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;proxy_read_timeout &lt;/span&gt;&lt;span style=&quot;--0:#79C0FF&quot;&gt;7s&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;;&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span class=&quot;indent&quot;&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;    &lt;/span&gt;&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;}&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;}&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;/code&gt;&lt;/pre&gt;&lt;div class=&quot;copy&quot;&gt;&lt;div aria-live=&quot;polite&quot;&gt;&lt;/div&gt;&lt;button title=&quot;Copy to clipboard&quot; data-copied=&quot;Copied!&quot; data-code=&quot;# nginx-load-balancer.conf# Layer 7 Load Balancing configuration for FoodFast backend clusterupstream foodfast_backend_cluster {    # Routelessly distribute load to the server with the least active connections    least_conn;    server app-node-01.foodfast.internal:3000 max_fails=3 fail_timeout=10s;    server app-node-02.foodfast.internal:3000 max_fails=3 fail_timeout=10s;    server app-node-03.foodfast.internal:3000 max_fails=3 fail_timeout=10s;    server app-node-04.foodfast.internal:3000 max_fails=3 fail_timeout=10s;    server app-node-05.foodfast.internal:3000 max_fails=3 fail_timeout=10s;    # Maintain open keepalive connections between Nginx and backend servers    keepalive 64;}server {    listen 80;    server_name api.foodfast.com;    location / {        proxy_pass http://foodfast_backend_cluster;        proxy_http_version 1.1;        proxy_set_header Connection &amp;#x22;&amp;#x22;;        proxy_set_header X-Real-IP $remote_addr;        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;        proxy_set_header Host $http_host;        # Strict timeout configurations to prevent hanging requests during spikes        proxy_connect_timeout 3s;        proxy_read_timeout 7s;    }}&quot;&gt;&lt;div&gt;&lt;/div&gt;&lt;/button&gt;&lt;/div&gt;&lt;/figure&gt;&lt;/div&gt;
&lt;figure&gt;&lt;img src=&quot;https://raw.githubusercontent.com/rafeuddaraj/rafes-blog-assets/refs/heads/ultimate-system-design-handbook-case-study-global-scale/assets/foodfast-monolith-to-horizontal.svg&quot; alt=&quot;Monolith to Horizontal Scaling Evolution&quot; loading=&quot;lazy&quot; decoding=&quot;async&quot; width=&quot;1000&quot; height=&quot;580&quot;&gt;&lt;figcaption&gt;Monolith to Horizontal Scaling Evolution&lt;/figcaption&gt;&lt;/figure&gt;
&lt;div class=&quot;callout&quot; role=&quot;note&quot; data-type=&quot;note&quot;&gt;
&lt;p class=&quot;callout-title&quot;&gt;Stateless Architecture Requirement&lt;/p&gt;
&lt;p&gt;When using a load balancer, never store user session data, temporary file uploads, or local state inside the memory of your application servers. If your servers are not strictly stateless, users will be logged out randomly or lose their data whenever the load balancer routes their next request to a different server node.&lt;/p&gt;
&lt;/div&gt;
&lt;hr&gt;
&lt;h2 id=&quot;case-study-3-when-the-database-becomes-the-bottleneck-global-expansion-replication-sharding-nosql&quot;&gt;Case Study 3: When the Database Becomes the Bottleneck &amp;#x26; Global Expansion (Replication, Sharding &amp;#x26; NoSQL)&lt;/h2&gt;
&lt;p&gt;With horizontal scaling and load balancing in place, FoodFast&apos;s web server cluster can easily handle hundreds of thousands of requests per second. Furthermore, your business has expanded beyond a single city; you now operate nationwide and in several neighboring countries, pushing your total user base past 1 million. Right at this stage of global expansion, a new severe bottleneck surfaces. While your 10 application servers process HTTP requests independently, they all hammer the exact same relational database to read and write data.&lt;/p&gt;
&lt;p&gt;This heavy traffic load causes severe database read and write contention. Your database connection pool is frequently exhausted, and complex transaction queries begin throwing deadlock errors. When we analyze the database slow query logs, we discover that restaurant search requests are performing full table scans. Searching through a table of 100,000 restaurants to find open locations in a specific neighborhood is pegging the database CPU at 100%. Our first remediation step is to apply B-Tree Indexing to the most frequently searched database columns. This simple indexing step reduces our search query time complexity from &lt;span class=&quot;katex&quot;&gt;&lt;span class=&quot;katex-html&quot; aria-hidden=&quot;true&quot;&gt;&lt;span class=&quot;base&quot;&gt;&lt;span class=&quot;strut&quot; style=&quot;height:1em;vertical-align:-0.25em;&quot;&gt;&lt;/span&gt;&lt;span class=&quot;mord mathnormal&quot; style=&quot;margin-right:0.0278em;&quot;&gt;O&lt;/span&gt;&lt;span class=&quot;mopen&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mord mathnormal&quot;&gt;n&lt;/span&gt;&lt;span class=&quot;mclose&quot;&gt;)&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/span&gt; down to &lt;span class=&quot;katex&quot;&gt;&lt;span class=&quot;katex-html&quot; aria-hidden=&quot;true&quot;&gt;&lt;span class=&quot;base&quot;&gt;&lt;span class=&quot;strut&quot; style=&quot;height:1em;vertical-align:-0.25em;&quot;&gt;&lt;/span&gt;&lt;span class=&quot;mord mathnormal&quot; style=&quot;margin-right:0.0278em;&quot;&gt;O&lt;/span&gt;&lt;span class=&quot;mopen&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mop&quot;&gt;lo&lt;span style=&quot;margin-right:0.0139em;&quot;&gt;g&lt;/span&gt;&lt;/span&gt;&lt;span class=&quot;mspace&quot; style=&quot;margin-right:0.1667em;&quot;&gt;&lt;/span&gt;&lt;span class=&quot;mord mathnormal&quot;&gt;n&lt;/span&gt;&lt;span class=&quot;mclose&quot;&gt;)&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;, dropping execution times from 500 milliseconds down to just 5 milliseconds.&lt;/p&gt;
&lt;p&gt;However, indexing only optimizes read speeds. Every time a user places a new order (a write operation), the database must update and rebuild its index trees, which adds storage space complexity and slows down write performance. To fix this, we move to a distributed database architecture by implementing Database Replication. We set up a single Leader (write) database paired with 4 Follower (read) databases. Since 90% of our application traffic consists of read operations-such as browsing menus and searching for restaurants-we route all read traffic across our read-replica followers. We reserve the leader database exclusively for write operations like checkout and payment processing, allowing the leader to asynchronously replicate its data changes down to the followers.&lt;/p&gt;
&lt;p&gt;Eventually, our core orders table surpasses tens of millions of rows, making it impossible for a single leader database to hold all that write traffic efficiently. This is when we implement Sharding, or horizontal partitioning. We choose the user&apos;s geographic location or city ID as our Sharding Key, splitting our monolithic database into smaller, independent regional databases. For example, all users in Dhaka are routed to Shard-A, while users in Chittagong are routed to Shard-B. At the same time, we realize that a relational SQL database is not the best tool for every data type. While we must maintain strict ACID (Atomicity, Consistency, Isolation, Durability) compliance for orders and payments using PostgreSQL, we migrate our high-volume, unstructured data-such as real-time GPS delivery driver tracking and customer support chat logs-over to NoSQL databases like MongoDB and Cassandra. Our design choices here are heavily guided by the CAP Theorem (Consistency, Availability, Partition Tolerance); we prioritize strict consistency for our billing systems while prioritizing high availability for our live location tracking feeds.&lt;/p&gt;
&lt;figure&gt;&lt;img src=&quot;https://raw.githubusercontent.com/rafeuddaraj/rafes-blog-assets/refs/heads/ultimate-system-design-handbook-case-study-global-scale/assets/database-sharding-replication.svg&quot; alt=&quot;Distributed Database Replication and Sharding&quot; loading=&quot;lazy&quot; decoding=&quot;async&quot; width=&quot;1000&quot; height=&quot;520&quot;&gt;&lt;figcaption&gt;Distributed Database Replication and Sharding&lt;/figcaption&gt;&lt;/figure&gt;
&lt;div class=&quot;callout&quot; role=&quot;note&quot; data-type=&quot;warning&quot;&gt;
&lt;p class=&quot;callout-title&quot;&gt;Database Sharding Complexity&lt;/p&gt;
&lt;p&gt;Think carefully before implementing database sharding. Once you shard a database across multiple physical machines, running cross-shard join queries or maintaining multi-table transactions becomes extremely complex. Always exhaust your indexing, caching, and read-replication options before partitioning your primary database.&lt;/p&gt;
&lt;/div&gt;
&lt;hr&gt;
&lt;h2 id=&quot;case-study-4-boosting-performance-to-rocket-speed-caching-strategies-edge-computing&quot;&gt;Case Study 4: Boosting Performance to Rocket Speed (Caching Strategies &amp;#x26; Edge Computing)&lt;/h2&gt;
&lt;p&gt;FoodFast&apos;s database layer is now distributed and horizontally scaled. Your servers are stable, and orders process without crashing the platform. However, when reviewing your application analytics reports, you notice that the mobile app still takes roughly 2.5 seconds to load the home screen. In today&apos;s fast-paced internet ecosystem, a 2.5-second load time is slow enough to cause significant user drop-off as customers switch to faster competitor apps. When we trace the network request waterfall, we see that every time a user opens the app, our application servers query the database from scratch to fetch restaurant lists and popular menu items. Reading this data from physical disk storage and dealing with network round-trip delays is wasting valuable milliseconds.&lt;/p&gt;
&lt;p&gt;The most effective engineering tool for dropping latency from milliseconds down to microseconds is In-Memory Caching. We integrate in-memory data stores like Redis or Memcached directly into our architecture. Any data that is read frequently but rarely updated-such as restaurant menus, item prices, and store categories-is cached directly in system RAM. We implement the Cache-Aside pattern for our read-heavy endpoints. When a client request arrives, the application first checks the Redis cache (a cache hit). If the data is found, it is returned immediately without touching the primary database. If the data is missing (a cache miss), the application queries the PostgreSQL database, returns the payload to the user, and writes a copy of that data into Redis to serve subsequent requests.&lt;/p&gt;
&lt;p&gt;Because RAM is an expensive hardware resource with limited storage capacity, we cannot keep billions of food items cached in memory indefinitely. To manage this footprint, we configure proper Cache Eviction Policies. We set our Redis cluster to use the Least Recently Used (LRU) algorithm. When memory reaches its capacity limit, the system automatically purges data keys that have not been accessed recently, freeing up RAM for active, hot data. Furthermore, to maintain data consistency across our platform, we assign a logical Time To Live (TTL) expiration value to every cache key. This ensures that when a restaurant manager updates an item&apos;s price, users do not see stale pricing data lingering in the cache.&lt;/p&gt;
&lt;p&gt;Additionally, our platform hosts thousands of high-resolution food images and promotional videos uploaded daily. When a user scrolls through the app, loading these heavy static media files directly from our primary origin servers consumes massive network bandwidth and slows down rendering time. To solve this delivery bottleneck, we integrate a Content Delivery Network (CDN) such as Cloudflare or AWS CloudFront. The CDN caches copies of our media files across globally distributed edge servers located close to our end users. Now, when a customer opens the app, food images load directly from the nearest edge location rather than traveling across the world to our origin data center. This drastically reduces Round Trip Time (RTT), making the application feel instantaneous.&lt;/p&gt;
&lt;div class=&quot;expressive-code&quot;&gt;&lt;figure class=&quot;frame has-title&quot;&gt;&lt;figcaption class=&quot;header&quot;&gt;&lt;span class=&quot;title&quot;&gt;TypeScript&lt;/span&gt;&lt;/figcaption&gt;&lt;pre data-language=&quot;typescript&quot;&gt;&lt;code&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span style=&quot;--0:#8B949E&quot;&gt;// redis-cache-aside.ts&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span style=&quot;--0:#8B949E&quot;&gt;// Production implementation of the Cache-Aside pattern using Redis and Node.js&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;import&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; { createClient } &lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;from&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; &lt;/span&gt;&lt;span style=&quot;--0:#A5D6FF&quot;&gt;&apos;redis&apos;&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;;&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;import&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; { getPool } &lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;from&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; &lt;/span&gt;&lt;span style=&quot;--0:#A5D6FF&quot;&gt;&apos;./db-pool-config&apos;&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;;&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;
&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;const&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; &lt;/span&gt;&lt;span style=&quot;--0:#79C0FF&quot;&gt;redisClient&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; &lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;=&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; &lt;/span&gt;&lt;span style=&quot;--0:#D2A8FF&quot;&gt;createClient&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;({ url: process.env.&lt;/span&gt;&lt;span style=&quot;--0:#79C0FF&quot;&gt;REDIS_URL&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; });&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;redisClient.&lt;/span&gt;&lt;span style=&quot;--0:#D2A8FF&quot;&gt;connect&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;();&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;
&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;export&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; &lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;async&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; &lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;function&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; &lt;/span&gt;&lt;span style=&quot;--0:#D2A8FF&quot;&gt;getRestaurantMenu&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;(&lt;/span&gt;&lt;span style=&quot;--0:#FFA657&quot;&gt;restaurantId&lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;:&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; &lt;/span&gt;&lt;span style=&quot;--0:#79C0FF&quot;&gt;string&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;)&lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;:&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; &lt;/span&gt;&lt;span style=&quot;--0:#FFA657&quot;&gt;Promise&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;&amp;#x3C;&lt;/span&gt;&lt;span style=&quot;--0:#79C0FF&quot;&gt;any&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;&gt; {&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span class=&quot;indent&quot;&gt;  &lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;const&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; &lt;/span&gt;&lt;span style=&quot;--0:#79C0FF&quot;&gt;cacheKey&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; &lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;=&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; &lt;/span&gt;&lt;span style=&quot;--0:#A5D6FF&quot;&gt;`foodfast:menu:${&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;restaurantId&lt;/span&gt;&lt;span style=&quot;--0:#A5D6FF&quot;&gt;}`&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;;&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;
&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span class=&quot;indent&quot;&gt;  &lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;try&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; {&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span class=&quot;indent&quot;&gt;    &lt;/span&gt;&lt;span style=&quot;--0:#8B949E&quot;&gt;// Step 1: Check if the menu exists in the Redis in-memory cache&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span class=&quot;indent&quot;&gt;    &lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;const&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; &lt;/span&gt;&lt;span style=&quot;--0:#79C0FF&quot;&gt;cachedData&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; &lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;=&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; &lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;await&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; redisClient.&lt;/span&gt;&lt;span style=&quot;--0:#D2A8FF&quot;&gt;get&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;(cacheKey);&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span class=&quot;indent&quot;&gt;    &lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;if&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; (cachedData) {&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span class=&quot;indent&quot;&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;      &lt;/span&gt;&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;console.&lt;/span&gt;&lt;span style=&quot;--0:#D2A8FF&quot;&gt;info&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;(&lt;/span&gt;&lt;span style=&quot;--0:#A5D6FF&quot;&gt;`[Cache Hit] Serving menu from Redis for restaurant: ${&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;restaurantId&lt;/span&gt;&lt;span style=&quot;--0:#A5D6FF&quot;&gt;}`&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;);&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span class=&quot;indent&quot;&gt;      &lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;return&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; &lt;/span&gt;&lt;span style=&quot;--0:#79C0FF&quot;&gt;JSON&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;.&lt;/span&gt;&lt;span style=&quot;--0:#D2A8FF&quot;&gt;parse&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;(cachedData);&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span class=&quot;indent&quot;&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;    &lt;/span&gt;&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;}&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;
&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span class=&quot;indent&quot;&gt;    &lt;/span&gt;&lt;span style=&quot;--0:#8B949E&quot;&gt;// Step 2: Cache Miss - Query the primary PostgreSQL database&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span class=&quot;indent&quot;&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;    &lt;/span&gt;&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;console.&lt;/span&gt;&lt;span style=&quot;--0:#D2A8FF&quot;&gt;warn&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;(&lt;/span&gt;&lt;span style=&quot;--0:#A5D6FF&quot;&gt;`[Cache Miss] Fetching menu from DB for restaurant: ${&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;restaurantId&lt;/span&gt;&lt;span style=&quot;--0:#A5D6FF&quot;&gt;}`&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;);&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span class=&quot;indent&quot;&gt;    &lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;const&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; &lt;/span&gt;&lt;span style=&quot;--0:#79C0FF&quot;&gt;dbPool&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; &lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;=&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; &lt;/span&gt;&lt;span style=&quot;--0:#D2A8FF&quot;&gt;getPool&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;();&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span class=&quot;indent&quot;&gt;    &lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;const&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; &lt;/span&gt;&lt;span style=&quot;--0:#79C0FF&quot;&gt;queryText&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; &lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;=&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; &lt;/span&gt;&lt;span style=&quot;--0:#A5D6FF&quot;&gt;`&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span class=&quot;indent&quot;&gt;&lt;span style=&quot;--0:#A5D6FF&quot;&gt;      &lt;/span&gt;&lt;/span&gt;&lt;span style=&quot;--0:#A5D6FF&quot;&gt;SELECT id, name, description, price, category, is_available&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span class=&quot;indent&quot;&gt;&lt;span style=&quot;--0:#A5D6FF&quot;&gt;      &lt;/span&gt;&lt;/span&gt;&lt;span style=&quot;--0:#A5D6FF&quot;&gt;FROM menu_items&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span class=&quot;indent&quot;&gt;&lt;span style=&quot;--0:#A5D6FF&quot;&gt;      &lt;/span&gt;&lt;/span&gt;&lt;span style=&quot;--0:#A5D6FF&quot;&gt;WHERE restaurant_id = $1 AND is_deleted = false&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span class=&quot;indent&quot;&gt;&lt;span style=&quot;--0:#A5D6FF&quot;&gt;    &lt;/span&gt;&lt;/span&gt;&lt;span style=&quot;--0:#A5D6FF&quot;&gt;`&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;;&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span class=&quot;indent&quot;&gt;    &lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;const&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; &lt;/span&gt;&lt;span style=&quot;--0:#79C0FF&quot;&gt;result&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; &lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;=&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; &lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;await&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; dbPool.&lt;/span&gt;&lt;span style=&quot;--0:#D2A8FF&quot;&gt;query&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;(queryText, [restaurantId]);&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;
&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span class=&quot;indent&quot;&gt;    &lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;if&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; (result.rows.&lt;/span&gt;&lt;span style=&quot;--0:#79C0FF&quot;&gt;length&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; &lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;===&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; &lt;/span&gt;&lt;span style=&quot;--0:#79C0FF&quot;&gt;0&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;) {&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span class=&quot;indent&quot;&gt;      &lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;return&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; &lt;/span&gt;&lt;span style=&quot;--0:#79C0FF&quot;&gt;null&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;;&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span class=&quot;indent&quot;&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;    &lt;/span&gt;&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;}&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;
&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span class=&quot;indent&quot;&gt;    &lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;const&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; &lt;/span&gt;&lt;span style=&quot;--0:#79C0FF&quot;&gt;menuData&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; &lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;=&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; result.rows;&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;
&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span class=&quot;indent&quot;&gt;    &lt;/span&gt;&lt;span style=&quot;--0:#8B949E&quot;&gt;// Step 3: Write data to Redis Cache with a TTL of 3600 seconds (1 hour)&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span class=&quot;indent&quot;&gt;    &lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;await&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; redisClient.&lt;/span&gt;&lt;span style=&quot;--0:#D2A8FF&quot;&gt;setEx&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;(cacheKey, &lt;/span&gt;&lt;span style=&quot;--0:#79C0FF&quot;&gt;3600&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;, &lt;/span&gt;&lt;span style=&quot;--0:#79C0FF&quot;&gt;JSON&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;.&lt;/span&gt;&lt;span style=&quot;--0:#D2A8FF&quot;&gt;stringify&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;(menuData));&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;
&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span class=&quot;indent&quot;&gt;    &lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;return&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; menuData;&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span class=&quot;indent&quot;&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;  &lt;/span&gt;&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;} &lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;catch&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; (error) {&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span class=&quot;indent&quot;&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;    &lt;/span&gt;&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;console.&lt;/span&gt;&lt;span style=&quot;--0:#D2A8FF&quot;&gt;error&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;(&lt;/span&gt;&lt;span style=&quot;--0:#A5D6FF&quot;&gt;&apos;Error in getRestaurantMenu execution:&apos;&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;, error);&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span class=&quot;indent&quot;&gt;    &lt;/span&gt;&lt;span style=&quot;--0:#8B949E&quot;&gt;// Fallback: If Redis fails, gracefully degrade and fetch from DB directly&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span class=&quot;indent&quot;&gt;    &lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;const&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; &lt;/span&gt;&lt;span style=&quot;--0:#79C0FF&quot;&gt;dbPool&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; &lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;=&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; &lt;/span&gt;&lt;span style=&quot;--0:#D2A8FF&quot;&gt;getPool&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;();&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span class=&quot;indent&quot;&gt;    &lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;const&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; &lt;/span&gt;&lt;span style=&quot;--0:#79C0FF&quot;&gt;fallbackResult&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; &lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;=&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; &lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;await&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; dbPool.&lt;/span&gt;&lt;span style=&quot;--0:#D2A8FF&quot;&gt;query&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;(&lt;/span&gt;&lt;span style=&quot;--0:#A5D6FF&quot;&gt;&apos;SELECT * FROM menu_items WHERE restaurant_id = $1&apos;&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;, [restaurantId]);&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span class=&quot;indent&quot;&gt;    &lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;return&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; fallbackResult.rows;&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span class=&quot;indent&quot;&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;  &lt;/span&gt;&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;}&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;}&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;/code&gt;&lt;/pre&gt;&lt;div class=&quot;copy&quot;&gt;&lt;div aria-live=&quot;polite&quot;&gt;&lt;/div&gt;&lt;button title=&quot;Copy to clipboard&quot; data-copied=&quot;Copied!&quot; data-code=&quot;// redis-cache-aside.ts// Production implementation of the Cache-Aside pattern using Redis and Node.jsimport { createClient } from &amp;#x27;redis&amp;#x27;;import { getPool } from &amp;#x27;./db-pool-config&amp;#x27;;const redisClient = createClient({ url: process.env.REDIS_URL });redisClient.connect();export async function getRestaurantMenu(restaurantId: string): Promise&lt;any&gt; {  const cacheKey = &amp;#x60;foodfast:menu:${restaurantId}&amp;#x60;;  try {    // Step 1: Check if the menu exists in the Redis in-memory cache    const cachedData = await redisClient.get(cacheKey);    if (cachedData) {      console.info(&amp;#x60;[Cache Hit] Serving menu from Redis for restaurant: ${restaurantId}&amp;#x60;);      return JSON.parse(cachedData);    }    // Step 2: Cache Miss - Query the primary PostgreSQL database    console.warn(&amp;#x60;[Cache Miss] Fetching menu from DB for restaurant: ${restaurantId}&amp;#x60;);    const dbPool = getPool();    const queryText = &amp;#x60;      SELECT id, name, description, price, category, is_available      FROM menu_items      WHERE restaurant_id = $1 AND is_deleted = false    &amp;#x60;;    const result = await dbPool.query(queryText, [restaurantId]);    if (result.rows.length === 0) {      return null;    }    const menuData = result.rows;    // Step 3: Write data to Redis Cache with a TTL of 3600 seconds (1 hour)    await redisClient.setEx(cacheKey, 3600, JSON.stringify(menuData));    return menuData;  } catch (error) {    console.error(&amp;#x27;Error in getRestaurantMenu execution:&amp;#x27;, error);    // Fallback: If Redis fails, gracefully degrade and fetch from DB directly    const dbPool = getPool();    const fallbackResult = await dbPool.query(&amp;#x27;SELECT * FROM menu_items WHERE restaurant_id = $1&amp;#x27;, [restaurantId]);    return fallbackResult.rows;  }}&quot;&gt;&lt;div&gt;&lt;/div&gt;&lt;/button&gt;&lt;/div&gt;&lt;/figure&gt;&lt;/div&gt;
&lt;div class=&quot;callout&quot; role=&quot;note&quot; data-type=&quot;tip&quot;&gt;
&lt;p class=&quot;callout-title&quot;&gt;Cache Stampede Prevention&lt;/p&gt;
&lt;p&gt;When a popular cache key expires (its TTL drops to zero), thousands of concurrent requests can hit the primary database at the exact same millisecond-a failure mode known as a cache stampede. To prevent this, implement mutex locks or distributed locking mechanisms so that only a single background thread queries the database and repopulates the cache while other requests wait briefly for the updated payload.&lt;/p&gt;
&lt;/div&gt;
&lt;hr&gt;
&lt;h2 id=&quot;case-study-5-the-monolith-breakdown-and-50-developers-microservices-event-driven-flow&quot;&gt;Case Study 5: The Monolith Breakdown and 50 Developers (Microservices &amp;#x26; Event-Driven Flow)&lt;/h2&gt;
&lt;p&gt;FoodFast has now evolved into a major enterprise technology enterprise. Your engineering department has grown to over 50 software developers, QA engineers, and DevOps specialists working concurrently. Despite this growth in headcount, you notice that releasing new features to production takes much longer than it used to. The root cause is your legacy monolithic codebase. Every piece of business logic-user authentication, restaurant onboarding, shopping cart management, payment processing, delivery rider matching, and push notifications-is tightly trapped inside a single, massive Git repository.&lt;/p&gt;
&lt;p&gt;This monolithic architecture creates severe tight coupling across your engineering teams. When a junior developer attempts to modify an email template inside the notification module, a minor syntax error causes the entire payment processing pipeline to crash in production. With 50 engineers pushing code to the same repository daily, merge conflicts and broken builds become routine. Fixing a small bug requires compiling, testing, and deploying the entire monolith, which takes several hours per release cycle. Furthermore, when our payment system needs more CPU during peak hours, we cannot scale that specific function alone; we are forced to scale the entire monolithic server footprint, resulting in massive hardware resource waste.&lt;/p&gt;
&lt;p&gt;To escape this maintenance nightmare, we migrate our entire platform to a Microservices Architecture. Following Domain-Driven Design (DDD) principles, we break our monolith down into smaller, independent services aligned with specific business capabilities. We create a dedicated Auth Service, Restaurant Service, Order Service, Payment Service, Rider Matching Service, and Notification Service. Each microservice is assigned its own independent database and CI/CD deployment pipeline. Now, the billing engineering team can deploy updates to the payment service 10 times a day without coordinating with or risking stability for the rest of the company.&lt;/p&gt;
&lt;p&gt;To manage communication between our client applications and these numerous backend services, we deploy an API Gateway as a single entry point. Our mobile apps no longer need to track the internal IP addresses or URLs of dozens of individual microservices. The API Gateway receives all incoming client traffic, handles SSL termination and user authentication, and routes the requests to the appropriate downstream service. For inter-service communication, we adopt two distinct architectural patterns. When a service requires an immediate response-such as checking if a user is authenticated during checkout-we use synchronous communication via REST or gRPC protocols. The gRPC protocol uses Protocol Buffers to transmit data in a compact binary format, running up to 10 times faster than standard JSON over HTTP.&lt;/p&gt;
&lt;p&gt;For operations where an immediate client response is unnecessary, we implement asynchronous communication. For example, when a customer successfully places a food order, the Order Service does not make synchronous HTTP calls to the Notification Service or the Analytics Service and wait for them to respond. Instead, the Order Service publishes an &lt;code&gt;OrderCreatedEvent&lt;/code&gt; message to a distributed message broker or event bus, such as Apache Kafka or RabbitMQ. Independent consumer services-including Payment, Notification, and Analytics-subscribe to that Kafka topic, ingest the message, and execute their respective background tasks (such as generating invoices, sending SMS alerts, and dispatching delivery riders) independently. This Event-Driven Architecture keeps our system loosely coupled, highly responsive, and effortlessly scalable.&lt;/p&gt;
&lt;figure&gt;&lt;img src=&quot;https://raw.githubusercontent.com/rafeuddaraj/rafes-blog-assets/refs/heads/ultimate-system-design-handbook-case-study-global-scale/assets/microservices-event-driven-flow.svg&quot; alt=&quot;Microservices Architecture and Event-Driven Kafka Flow&quot; loading=&quot;lazy&quot; decoding=&quot;async&quot; width=&quot;1000&quot; height=&quot;520&quot;&gt;&lt;figcaption&gt;Microservices Architecture and Event-Driven Kafka Flow&lt;/figcaption&gt;&lt;/figure&gt;
&lt;hr&gt;
&lt;h2 id=&quot;case-study-6-building-an-bulletproof-system-for-disaster-recovery-fault-tolerance-rate-limiting-observability&quot;&gt;Case Study 6: Building an Bulletproof System for Disaster Recovery (Fault Tolerance, Rate Limiting &amp;#x26; Observability)&lt;/h2&gt;
&lt;p&gt;In a distributed microservices ecosystem, one absolute law holds true: anything can fail at any time. On a busy Friday night during peak dinner hours, our third-party banking payment gateway partner suffered an internal system outage. Their servers began taking over 30 seconds to respond to payment authorization requests. Our FoodFast Payment Service kept waiting for those responses, which quickly exhausted its internal thread pools and open outbound connection limits. Because our Order Service made synchronous calls to the Payment Service, it also ran out of available threads and crashed. Within minutes, this cascading failure brought down our entire microservices ecosystem like a falling stack of dominoes.&lt;/p&gt;
&lt;p&gt;To prevent this catastrophic failure mode from happening again, we engineer strict Fault Tolerance into our architecture. We implement the Circuit Breaker Pattern across all inter-service network calls. Just as an electrical circuit breaker trips during a power surge to prevent your house from catching fire, a software circuit breaker monitors network failures to protect your system. Using patterns established by libraries like Resilience4j or Hystrix, we configure our circuit breakers to trip into an &quot;Open&quot; state if a downstream service fails or times out on 50% of its requests within a 10-second window. While the circuit is open, our application stops sending requests to the failing service entirely and immediately returns a graceful fallback response (for example: &quot;Online card processing is temporarily unavailable; your order has been switched to Cash on Delivery&quot;). This protects our primary thread pools from blocking and keeps the rest of the platform online.&lt;/p&gt;
&lt;p&gt;Simultaneously, we protect our infrastructure against malicious actors, web scrapers, and Denial of Service (DDoS) attacks by enforcing Rate Limiting. We implement the Token Bucket or Leaky Bucket algorithm at the API Gateway layer, establishing strict traffic rules that limit individual IP addresses or user accounts to a maximum of 20 requests per second. If a script or scraper exceeds this limit-such as a competitor attempting to scrape our entire menu catalog-the API Gateway immediately blocks the traffic and returns an HTTP &lt;code&gt;429 Too Many Requests&lt;/code&gt; status code, shielding our backend cluster from synthetic load spikes.&lt;/p&gt;
&lt;p&gt;Finally, managing 50 microservices running across thousands of containers requires complete internal visibility, so we build a comprehensive Observability platform. We structure this observability strategy around the three core pillars: Logging, Metrics, and Tracing. We aggregate application logs from every container and stream them into a centralized ELK Stack (Elasticsearch, Logstash, Kibana) for real-time querying. To track system health, we use Prometheus to scrape hardware metrics (CPU, memory, disk usage) and application metrics (request latency, error rates), visualizing them on live Grafana dashboards. To trace requests across our distributed network, we deploy Jaeger or Zipkin for Distributed Tracing. When a user complains about a slow checkout, we can inspect a single trace ID and immediately identify which specific database query inside which microservice is causing the latency spike.&lt;/p&gt;
&lt;div class=&quot;expressive-code&quot;&gt;&lt;figure class=&quot;frame has-title&quot;&gt;&lt;figcaption class=&quot;header&quot;&gt;&lt;span class=&quot;title&quot;&gt;TypeScript&lt;/span&gt;&lt;/figcaption&gt;&lt;pre data-language=&quot;typescript&quot;&gt;&lt;code&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span style=&quot;--0:#8B949E&quot;&gt;// circuit-breaker-pattern.ts&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span style=&quot;--0:#8B949E&quot;&gt;// Production-ready implementation of the Circuit Breaker pattern using the Opossum library&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;import&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; CircuitBreaker &lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;from&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; &lt;/span&gt;&lt;span style=&quot;--0:#A5D6FF&quot;&gt;&apos;opossum&apos;&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;;&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;import&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; axios &lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;from&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; &lt;/span&gt;&lt;span style=&quot;--0:#A5D6FF&quot;&gt;&apos;axios&apos;&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;;&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;
&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span style=&quot;--0:#8B949E&quot;&gt;// The potentially unreliable external service call (e.g., Bank Payment Gateway)&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;async&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; &lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;function&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; &lt;/span&gt;&lt;span style=&quot;--0:#D2A8FF&quot;&gt;callExternalPaymentGateway&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;(&lt;/span&gt;&lt;span style=&quot;--0:#FFA657&quot;&gt;payload&lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;:&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; &lt;/span&gt;&lt;span style=&quot;--0:#79C0FF&quot;&gt;any&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;)&lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;:&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; &lt;/span&gt;&lt;span style=&quot;--0:#FFA657&quot;&gt;Promise&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;&amp;#x3C;&lt;/span&gt;&lt;span style=&quot;--0:#79C0FF&quot;&gt;any&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;&gt; {&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span class=&quot;indent&quot;&gt;  &lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;const&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; &lt;/span&gt;&lt;span style=&quot;--0:#79C0FF&quot;&gt;response&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; &lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;=&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; &lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;await&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; axios.&lt;/span&gt;&lt;span style=&quot;--0:#D2A8FF&quot;&gt;post&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;(&lt;/span&gt;&lt;span style=&quot;--0:#A5D6FF&quot;&gt;&apos;https://bank-gateway.external.com/api/v1/charge&apos;&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;, payload, {&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span class=&quot;indent&quot;&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;    &lt;/span&gt;&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;timeout: &lt;/span&gt;&lt;span style=&quot;--0:#79C0FF&quot;&gt;3000&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;, &lt;/span&gt;&lt;span style=&quot;--0:#8B949E&quot;&gt;// Strict 3-second timeout to prevent thread blocking&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span class=&quot;indent&quot;&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;  &lt;/span&gt;&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;});&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span class=&quot;indent&quot;&gt;  &lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;return&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; response.data;&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;}&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;
&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span style=&quot;--0:#8B949E&quot;&gt;// Circuit Breaker configuration options for the FoodFast payment service&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;const&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; &lt;/span&gt;&lt;span style=&quot;--0:#79C0FF&quot;&gt;breakerOptions&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; &lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;=&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; {&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span class=&quot;indent&quot;&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;  &lt;/span&gt;&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;timeout: &lt;/span&gt;&lt;span style=&quot;--0:#79C0FF&quot;&gt;3500&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;, &lt;/span&gt;&lt;span style=&quot;--0:#8B949E&quot;&gt;// If function execution takes longer than 3.5s, trigger a failure&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span class=&quot;indent&quot;&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;  &lt;/span&gt;&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;errorThresholdPercentage: &lt;/span&gt;&lt;span style=&quot;--0:#79C0FF&quot;&gt;50&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;, &lt;/span&gt;&lt;span style=&quot;--0:#8B949E&quot;&gt;// When 50% of requests fail, trip the circuit to OPEN&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span class=&quot;indent&quot;&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;  &lt;/span&gt;&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;resetTimeout: &lt;/span&gt;&lt;span style=&quot;--0:#79C0FF&quot;&gt;30000&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;, &lt;/span&gt;&lt;span style=&quot;--0:#8B949E&quot;&gt;// After 30 seconds, transition to HALF-OPEN state to test service health&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;};&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;
&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;const&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; &lt;/span&gt;&lt;span style=&quot;--0:#79C0FF&quot;&gt;paymentCircuitBreaker&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; &lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;=&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; &lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;new&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; &lt;/span&gt;&lt;span style=&quot;--0:#D2A8FF&quot;&gt;CircuitBreaker&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;(callExternalPaymentGateway, breakerOptions);&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;
&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span style=&quot;--0:#8B949E&quot;&gt;// Fallback logic executed immediately when Circuit is OPEN or service fails&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;paymentCircuitBreaker.&lt;/span&gt;&lt;span style=&quot;--0:#D2A8FF&quot;&gt;fallback&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;((&lt;/span&gt;&lt;span style=&quot;--0:#FFA657&quot;&gt;payload&lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;:&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; &lt;/span&gt;&lt;span style=&quot;--0:#79C0FF&quot;&gt;any&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;, &lt;/span&gt;&lt;span style=&quot;--0:#FFA657&quot;&gt;error&lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;:&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; &lt;/span&gt;&lt;span style=&quot;--0:#79C0FF&quot;&gt;any&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;) &lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;=&gt;&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; {&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span class=&quot;indent&quot;&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;  &lt;/span&gt;&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;console.&lt;/span&gt;&lt;span style=&quot;--0:#D2A8FF&quot;&gt;warn&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;(&lt;/span&gt;&lt;span style=&quot;--0:#A5D6FF&quot;&gt;`[Circuit Breaker OPEN] Payment gateway failed for order ${&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;payload&lt;/span&gt;&lt;span style=&quot;--0:#A5D6FF&quot;&gt;.&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;orderId&lt;/span&gt;&lt;span style=&quot;--0:#A5D6FF&quot;&gt;}. Executing fallback.`&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;);&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span class=&quot;indent&quot;&gt;  &lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;return&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; {&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span class=&quot;indent&quot;&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;    &lt;/span&gt;&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;status: &lt;/span&gt;&lt;span style=&quot;--0:#A5D6FF&quot;&gt;&apos;ACCEPTED_FALLBACK&apos;&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;,&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span class=&quot;indent&quot;&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;    &lt;/span&gt;&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;paymentMethod: &lt;/span&gt;&lt;span style=&quot;--0:#A5D6FF&quot;&gt;&apos;CASH_ON_DELIVERY&apos;&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;,&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span class=&quot;indent&quot;&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;    &lt;/span&gt;&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;message: &lt;/span&gt;&lt;span style=&quot;--0:#A5D6FF&quot;&gt;&apos;Online payment is temporarily unavailable. Order converted to Cash on Delivery.&apos;&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;,&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span class=&quot;indent&quot;&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;    &lt;/span&gt;&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;originalError: error.message,&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span class=&quot;indent&quot;&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;  &lt;/span&gt;&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;};&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;});&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;
&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;paymentCircuitBreaker.&lt;/span&gt;&lt;span style=&quot;--0:#D2A8FF&quot;&gt;on&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;(&lt;/span&gt;&lt;span style=&quot;--0:#A5D6FF&quot;&gt;&apos;open&apos;&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;, () &lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;=&gt;&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; console.&lt;/span&gt;&lt;span style=&quot;--0:#D2A8FF&quot;&gt;error&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;(&lt;/span&gt;&lt;span style=&quot;--0:#A5D6FF&quot;&gt;&apos;CRITICAL ALERT: Payment Circuit Breaker TRIPPED to OPEN!&apos;&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;));&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;paymentCircuitBreaker.&lt;/span&gt;&lt;span style=&quot;--0:#D2A8FF&quot;&gt;on&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;(&lt;/span&gt;&lt;span style=&quot;--0:#A5D6FF&quot;&gt;&apos;halfOpen&apos;&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;, () &lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;=&gt;&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; console.&lt;/span&gt;&lt;span style=&quot;--0:#D2A8FF&quot;&gt;info&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;(&lt;/span&gt;&lt;span style=&quot;--0:#A5D6FF&quot;&gt;&apos;Payment Circuit Breaker is HALF-OPEN. Testing gateway health...&apos;&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;));&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;paymentCircuitBreaker.&lt;/span&gt;&lt;span style=&quot;--0:#D2A8FF&quot;&gt;on&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;(&lt;/span&gt;&lt;span style=&quot;--0:#A5D6FF&quot;&gt;&apos;close&apos;&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;, () &lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;=&gt;&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; console.&lt;/span&gt;&lt;span style=&quot;--0:#D2A8FF&quot;&gt;info&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;(&lt;/span&gt;&lt;span style=&quot;--0:#A5D6FF&quot;&gt;&apos;Payment Circuit Breaker CLOSED. Gateway operating normally.&apos;&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;));&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;
&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;export&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; &lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;async&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; &lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;function&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; &lt;/span&gt;&lt;span style=&quot;--0:#D2A8FF&quot;&gt;processOrderPayment&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;(&lt;/span&gt;&lt;span style=&quot;--0:#FFA657&quot;&gt;payload&lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;:&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; &lt;/span&gt;&lt;span style=&quot;--0:#79C0FF&quot;&gt;any&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;)&lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;:&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; &lt;/span&gt;&lt;span style=&quot;--0:#FFA657&quot;&gt;Promise&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;&amp;#x3C;&lt;/span&gt;&lt;span style=&quot;--0:#79C0FF&quot;&gt;any&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;&gt; {&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span class=&quot;indent&quot;&gt;  &lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;return&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; &lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;await&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; paymentCircuitBreaker.&lt;/span&gt;&lt;span style=&quot;--0:#D2A8FF&quot;&gt;fire&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;(payload);&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;}&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;/code&gt;&lt;/pre&gt;&lt;div class=&quot;copy&quot;&gt;&lt;div aria-live=&quot;polite&quot;&gt;&lt;/div&gt;&lt;button title=&quot;Copy to clipboard&quot; data-copied=&quot;Copied!&quot; data-code=&quot;// circuit-breaker-pattern.ts// Production-ready implementation of the Circuit Breaker pattern using the Opossum libraryimport CircuitBreaker from &amp;#x27;opossum&amp;#x27;;import axios from &amp;#x27;axios&amp;#x27;;// The potentially unreliable external service call (e.g., Bank Payment Gateway)async function callExternalPaymentGateway(payload: any): Promise&lt;any&gt; {  const response = await axios.post(&amp;#x27;https://bank-gateway.external.com/api/v1/charge&amp;#x27;, payload, {    timeout: 3000, // Strict 3-second timeout to prevent thread blocking  });  return response.data;}// Circuit Breaker configuration options for the FoodFast payment serviceconst breakerOptions = {  timeout: 3500, // If function execution takes longer than 3.5s, trigger a failure  errorThresholdPercentage: 50, // When 50% of requests fail, trip the circuit to OPEN  resetTimeout: 30000, // After 30 seconds, transition to HALF-OPEN state to test service health};const paymentCircuitBreaker = new CircuitBreaker(callExternalPaymentGateway, breakerOptions);// Fallback logic executed immediately when Circuit is OPEN or service failspaymentCircuitBreaker.fallback((payload: any, error: any) =&gt; {  console.warn(&amp;#x60;[Circuit Breaker OPEN] Payment gateway failed for order ${payload.orderId}. Executing fallback.&amp;#x60;);  return {    status: &amp;#x27;ACCEPTED_FALLBACK&amp;#x27;,    paymentMethod: &amp;#x27;CASH_ON_DELIVERY&amp;#x27;,    message: &amp;#x27;Online payment is temporarily unavailable. Order converted to Cash on Delivery.&amp;#x27;,    originalError: error.message,  };});paymentCircuitBreaker.on(&amp;#x27;open&amp;#x27;, () =&gt; console.error(&amp;#x27;CRITICAL ALERT: Payment Circuit Breaker TRIPPED to OPEN!&amp;#x27;));paymentCircuitBreaker.on(&amp;#x27;halfOpen&amp;#x27;, () =&gt; console.info(&amp;#x27;Payment Circuit Breaker is HALF-OPEN. Testing gateway health...&amp;#x27;));paymentCircuitBreaker.on(&amp;#x27;close&amp;#x27;, () =&gt; console.info(&amp;#x27;Payment Circuit Breaker CLOSED. Gateway operating normally.&amp;#x27;));export async function processOrderPayment(payload: any): Promise&lt;any&gt; {  return await paymentCircuitBreaker.fire(payload);}&quot;&gt;&lt;div&gt;&lt;/div&gt;&lt;/button&gt;&lt;/div&gt;&lt;/figure&gt;&lt;/div&gt;
&lt;div class=&quot;callout&quot; role=&quot;note&quot; data-type=&quot;warning&quot;&gt;
&lt;p class=&quot;callout-title&quot;&gt;Distributed Tracing Overhead&lt;/p&gt;
&lt;p&gt;Never enable 100% request sampling for distributed tracing in a high-traffic production environment. Capturing a trace for every single HTTP request consumes massive network bandwidth and quickly fills up storage clusters. Instead, configure sample rates between 1% and 5%, which provides more than enough statistical data to monitor system performance and catch latency bottlenecks.&lt;/p&gt;
&lt;/div&gt;
&lt;hr&gt;
&lt;h2 id=&quot;case-study-7-end-to-end-blueprints-of-global-tech-giants-url-shortener-news-feed-video-streaming&quot;&gt;Case Study 7: End-to-End Blueprints of Global Tech Giants (URL Shortener, News Feed &amp;#x26; Video Streaming)&lt;/h2&gt;
&lt;p&gt;Having explored the individual engineering layers of a scalable architecture through the FoodFast journey, we will now synthesize these concepts by analyzing how global tech companies design their core production systems. Below, we break down three real-world architectural blueprints from scratch.&lt;/p&gt;
&lt;h3 id=&quot;case-study-7a-url-shortener-design-bitly-or-tinyurl-style&quot;&gt;Case Study 7A: URL Shortener Design (Bitly or TinyURL Style)&lt;/h3&gt;
&lt;p&gt;The primary responsibility of a URL shortening service is to take a long web URL, generate a compact unique short link, and reliably redirect users back to the original long URL whenever they click the short link.&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;Trade-Off and Ratio Analysis:&lt;/strong&gt; In a URL shortening platform, the volume of users clicking short links is vastly higher than the volume of users creating new links. We design the system assuming a 10:1 read-to-write ratio. If the platform generates 100 new short links per second, it must handle 1,000 redirect requests per second. Therefore, our architectural focus centers on optimizing read performance and achieving low redirect latency.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Unique ID Generation and Encoding:&lt;/strong&gt; To generate a compact short link, we need to create a 7-character unique key. We use Base62 encoding, which utilizes alphanumeric characters (a-z, A-Z, 0-9). A 7-character Base62 string provides &lt;span class=&quot;katex&quot;&gt;&lt;span class=&quot;katex-html&quot; aria-hidden=&quot;true&quot;&gt;&lt;span class=&quot;base&quot;&gt;&lt;span class=&quot;strut&quot; style=&quot;height:0.8141em;&quot;&gt;&lt;/span&gt;&lt;span class=&quot;mord&quot;&gt;6&lt;/span&gt;&lt;span class=&quot;mord&quot;&gt;&lt;span class=&quot;mord&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;msupsub&quot;&gt;&lt;span class=&quot;vlist-t&quot;&gt;&lt;span class=&quot;vlist-r&quot;&gt;&lt;span class=&quot;vlist&quot; style=&quot;height:0.8141em;&quot;&gt;&lt;span style=&quot;top:-3.063em;margin-right:0.05em;&quot;&gt;&lt;span class=&quot;pstrut&quot; style=&quot;height:2.7em;&quot;&gt;&lt;/span&gt;&lt;span class=&quot;sizing reset-size6 size3 mtight&quot;&gt;&lt;span class=&quot;mord mtight&quot;&gt;7&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;, or roughly 3.5 trillion unique combinations-enough to support system growth for decades without running out of keys. Rather than relying on slow database auto-increment locks, we deploy a Distributed Sequence Generator like Twitter Snowflake or a dedicated Key Generation Service (KGS). The KGS pre-generates blocks of unique keys and holds them in memory, allowing application servers to grab new short keys instantly without database write latency.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Data Layer and Caching Strategy:&lt;/strong&gt; We store the mappings between short keys and original long URLs inside a horizontally sharded NoSQL database such as DynamoDB or Apache Cassandra, as this data model requires no complex relational table joins. To drive redirect latency down to near-zero milliseconds, we deploy a massive Redis caching cluster in front of the database. When a user clicks a short link, the application checks Redis, grabs the original long URL from memory, and immediately returns an HTTP &lt;code&gt;301 Permanent Redirect&lt;/code&gt; or &lt;code&gt;302 Temporary Redirect&lt;/code&gt; status code to send the browser to its destination.&lt;/li&gt;
&lt;/ul&gt;
&lt;h3 id=&quot;case-study-7b-news-feed-system-design-facebook-or-twitter-style&quot;&gt;Case Study 7B: News Feed System Design (Facebook or Twitter Style)&lt;/h3&gt;
&lt;p&gt;The core engineering challenge of a social media news feed is generating a real-time, chronologically sorted timeline of posts from hundreds of friends and followed accounts for millions of concurrent users.&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;Fan-Out Architecture (Write vs. Read Push/Pull Models):&lt;/strong&gt; When a user publishes a new post, the process of delivering that post to the timelines of all their followers is called Fan-Out. There are two primary architectural strategies here. The first is Fan-Out on Write (the Push Model). When a standard user publishes a post, a background service grabs their follower list and pushes the post ID directly into the in-memory timeline caches (Redis lists) of every individual follower. The main advantage here is that when a follower opens the app, their timeline is already pre-computed in RAM, loading instantly without database queries.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;The Celebrity Problem and Hybrid Solutions:&lt;/strong&gt; However, the push model breaks down when encountering the &quot;Celebrity Problem.&quot; Imagine a famous user with 50 million followers publishes a new post. Pushing that single post into 50 million individual timeline caches simultaneously creates a massive write storm that can overwhelm servers and crash the caching tier. To prevent this, platforms use Fan-Out on Read (the Pull Model) for accounts with large follower counts. When a celebrity publishes a post, it is simply saved to their personal timeline database table without pushing to followers. When an average user opens their app, the Feed Generation Service merges their pre-computed push timeline from Redis with an on-the-fly pull query fetching recent posts from the celebrities they follow. This hybrid push/pull model is the standard pattern used in production by platforms like Facebook and Twitter.&lt;/li&gt;
&lt;/ul&gt;
&lt;h3 id=&quot;case-study-7c-video-streaming-platform-design-youtube-or-netflix-style&quot;&gt;Case Study 7C: Video Streaming Platform Design (YouTube or Netflix Style)&lt;/h3&gt;
&lt;p&gt;Building a video streaming platform requires handling massive file uploads, optimizing network bandwidth utilization, and delivering smooth video playback across variable internet connection speeds without buffering.&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;Video Ingestion and Distributed Transcoding:&lt;/strong&gt; When a content creator uploads a raw 4K video file, serving that huge file directly to end users on mobile devices is impractical. The uploaded video lands in an object storage bucket (such as AWS S3 or Google Cloud Storage), which immediately fires an event into an Apache Kafka message queue. A fleet of background Transcoding Workers consumes this job from the queue and uses tools like FFmpeg to convert the raw video into multiple standard display resolutions, including 1080p, 720p, 480p, and 360p.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Chunking and Adaptive Bitrate Streaming (ABR):&lt;/strong&gt; During the transcoding process, each video resolution is sliced into short, 2- to 4-second file segments called chunks (saved as &lt;code&gt;.ts&lt;/code&gt; or &lt;code&gt;.m4s&lt;/code&gt; files), and a master playlist or manifest file (&lt;code&gt;.m3u8&lt;/code&gt; or &lt;code&gt;.mpd&lt;/code&gt;) is generated to map them together. This segmented delivery approach is known as Adaptive Bitrate Streaming (running over HLS or DASH protocols).&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;CDN Edge Delivery and the Client Player:&lt;/strong&gt; We distribute these transcoded video chunks and manifest files out to global Content Delivery Network (CDN) edge servers. When a user presses play, their video player downloads the manifest file and assesses their current network connection speed. If the user has a fast fiber connection, the player fetches high-definition 1080p chunks from the nearest CDN edge node. If their Wi-Fi signal drops or their cellular network degrades, the client player smoothly drops down to fetching 360p chunks on the fly, keeping the video playing continuously without freezing or buffering.&lt;/li&gt;
&lt;/ul&gt;
&lt;figure&gt;&lt;img src=&quot;https://raw.githubusercontent.com/rafeuddaraj/rafes-blog-assets/refs/heads/ultimate-system-design-handbook-case-study-global-scale/assets/video-streaming-transcoding-pipeline.svg&quot; alt=&quot;YouTube and Netflix Video Streaming Transcoding Pipeline&quot; loading=&quot;lazy&quot; decoding=&quot;async&quot; width=&quot;1000&quot; height=&quot;500&quot;&gt;&lt;figcaption&gt;YouTube and Netflix Video Streaming Transcoding Pipeline&lt;/figcaption&gt;&lt;/figure&gt;
&lt;hr&gt;
&lt;h2 id=&quot;developer-checklist-and-production-guidelines&quot;&gt;Developer Checklist and Production Guidelines&lt;/h2&gt;
&lt;p&gt;Successful system design is about choosing the right architectural trade-off at the right time. Whenever you design a new platform or refactor a legacy system, review this production-ready engineering checklist. Walking through these points will help you catch critical architectural flaws before they turn into production outages.&lt;/p&gt;
&lt;ul class=&quot;contains-task-list&quot;&gt;
&lt;li class=&quot;task-list-item&quot;&gt;&lt;input type=&quot;checkbox&quot; disabled aria-label=&quot;Scalability and Statelessness: Are your web servers and API tiers configured as completely stateless applications? If a &quot;&gt; &lt;strong&gt;Scalability and Statelessness:&lt;/strong&gt; Are your web servers and API tiers configured as completely stateless applications? If a running server node is abruptly terminated, will client sessions and pending requests fail gracefully without losing data?&lt;/li&gt;
&lt;li class=&quot;task-list-item&quot;&gt;&lt;input type=&quot;checkbox&quot; disabled aria-label=&quot;Caching and Expiration Policies: Is your caching tier configured with an appropriate eviction policy like LRU or LFU? Ha&quot;&gt; &lt;strong&gt;Caching and Expiration Policies:&lt;/strong&gt; Is your caching tier configured with an appropriate eviction policy like LRU or LFU? Have you assigned a logical Time To Live (TTL) value to every cache key to prevent memory leaks and eliminate stale data?&lt;/li&gt;
&lt;li class=&quot;task-list-item&quot;&gt;&lt;input type=&quot;checkbox&quot; disabled aria-label=&quot;Database and Query Indexing: Have you applied B-Tree indexes to the database columns used most frequently in search WHER&quot;&gt; &lt;strong&gt;Database and Query Indexing:&lt;/strong&gt; Have you applied B-Tree indexes to the database columns used most frequently in search WHERE clauses and JOIN conditions? Have you run &lt;code&gt;EXPLAIN ANALYZE&lt;/code&gt; on your slow queries to verify that they are using index scans instead of full table scans?&lt;/li&gt;
&lt;li class=&quot;task-list-item&quot;&gt;&lt;input type=&quot;checkbox&quot; disabled aria-label=&quot;Synchronous vs. Asynchronous Processing: Are background workloads that do not require an immediate user response (such a&quot;&gt; &lt;strong&gt;Synchronous vs. Asynchronous Processing:&lt;/strong&gt; Are background workloads that do not require an immediate user response (such as sending confirmation emails, generating PDF reports, or logging analytics) pushed to an asynchronous message queue like Kafka or RabbitMQ?&lt;/li&gt;
&lt;li class=&quot;task-list-item&quot;&gt;&lt;input type=&quot;checkbox&quot; disabled aria-label=&quot;Fault Tolerance and Circuit Breakers: Have you implemented strict network timeout rules and the Circuit Breaker pattern &quot;&gt; &lt;strong&gt;Fault Tolerance and Circuit Breakers:&lt;/strong&gt; Have you implemented strict network timeout rules and the Circuit Breaker pattern on all outbound REST and gRPC calls to third-party APIs and internal microservices to prevent cascading system failures?&lt;/li&gt;
&lt;li class=&quot;task-list-item&quot;&gt;&lt;input type=&quot;checkbox&quot; disabled aria-label=&quot;Rate Limiting and Security: Is your API Gateway configured with Token Bucket or Leaky Bucket rate limiting rules to prot&quot;&gt; &lt;strong&gt;Rate Limiting and Security:&lt;/strong&gt; Is your API Gateway configured with Token Bucket or Leaky Bucket rate limiting rules to protect your backend cluster against brute-force attacks, aggressive web scrapers, and DDoS traffic spikes?&lt;/li&gt;
&lt;li class=&quot;task-list-item&quot;&gt;&lt;input type=&quot;checkbox&quot; disabled aria-label=&quot;Single Points of Failure (SPOF): Have you eliminated every Single Point of Failure across your infrastructure by deployi&quot;&gt; &lt;strong&gt;Single Points of Failure (SPOF):&lt;/strong&gt; Have you eliminated every Single Point of Failure across your infrastructure by deploying redundant standby nodes for your load balancers, database masters, and caching clusters?&lt;/li&gt;
&lt;li class=&quot;task-list-item&quot;&gt;&lt;input type=&quot;checkbox&quot; disabled aria-label=&quot;Observability and Alerting: Do you have Prometheus and Grafana dashboards actively scraping CPU, memory, latency, and er&quot;&gt; &lt;strong&gt;Observability and Alerting:&lt;/strong&gt; Do you have Prometheus and Grafana dashboards actively scraping CPU, memory, latency, and error rate metrics from your production containers? Are automated PagerDuty or Slack alerts configured to notify your on-call engineering team the moment an error rate threshold is breached?&lt;/li&gt;
&lt;/ul&gt;</content:encoded><category>System Design</category><category>System Design</category><category>Software Architecture</category><category>Microservices</category><category>Scalability</category><category>Database Sharding</category><category>Caching Strategies</category><category>Load Balancing</category><category>Fault Tolerance</category><category>Kafka</category><category>High Availability</category></item><item><title>Google Did the Research, OpenAI Captured the Value: An Under-the-Hood Look at Generative AI Architecture</title><link>https://www.rafeuddaraj.me/blog/generative-ai-under-the-hood-google-vs-openai-deep-dive/</link><guid isPermaLink="true">https://www.rafeuddaraj.me/blog/generative-ai-under-the-hood-google-vs-openai-deep-dive/</guid><description>A comprehensive engineering deep dive into how Google&apos;s 2017 Transformer architecture powers modern generative AI, why Google missed the first-mover advantage, and how OpenAI captured the market.</description><pubDate>Sat, 04 Jul 2026 19:34:25 GMT</pubDate><content:encoded>&lt;p&gt;There is a common misconception among everyday technology users and even many junior software engineers that today&apos;s generative AI and large language model revolution belongs entirely to OpenAI. When we interact with powerful models like ChatGPT, Claude, or Gemini, it feels as though this entire technology was born inside OpenAI&apos;s private laboratories. But if you look under the hood at the actual engineering architecture, you will find a very different story. The true backbone of this entire revolution lies within a historic 2017 research paper published by Google.&lt;/p&gt;
&lt;p&gt;In this engineering deep dive, we will analyze how a breakthrough architecture invented by Google completely changed the technology landscape. We will examine why Google failed to capture the first-mover advantage itself, and how OpenAI used that open-source technology to pull off one of the biggest value captures in tech history. At the end of this article, you will find reference links to all the original research papers and technical documentation so you can explore the math and mechanics yourself.&lt;/p&gt;
&lt;h2 id=&quot;the-historic-turning-point-in-tech&quot;&gt;The Historic Turning Point in Tech&lt;/h2&gt;
&lt;p&gt;In mid-2017, a team of eight scientists from Google Brain and Google Research published a paper titled &lt;a href=&quot;https://arxiv.org/abs/1706.03762&quot; rel=&quot;noopener noreferrer&quot;&gt;Attention Is All You Need&lt;/a&gt;. While the paper created a huge buzz in academic circles at the time, very few people in the broader software industry realized the massive earthquake it was about to trigger.&lt;/p&gt;
&lt;p&gt;This research paper introduced the world to the Transformer architecture for the very first time. If you use ChatGPT today, that final letter &quot;T&quot; actually stands for Transformer, as in Generative Pre-trained Transformer. This means the core engine powering your complex code debugging and natural language conversations was built entirely inside Google&apos;s labs. Instead of locking away this breakthrough invention for internal use only, Google decided to open-source it for the global developer community. That exact decision kicked off one of the most significant strategic shifts in software history.&lt;/p&gt;
&lt;h2 id=&quot;a-foundational-mental-model-and-analogy&quot;&gt;A Foundational Mental Model and Analogy&lt;/h2&gt;
&lt;p&gt;Before we get into the technical architecture, let us break down the entire situation using a real-world analogy. Imagine a world-famous, top-tier restaurant chain (Google) that spends years in its R&amp;#x26;D kitchen developing an extraordinary new recipe for biryani (the Transformer architecture). This recipe is so advanced that it allows chefs to prepare delicious food for millions of people at a fraction of the usual cost and cooking time.&lt;/p&gt;
&lt;p&gt;However, the restaurant chain hesitates to put this new dish on its official menu. The executives worry that launching something so new and disruptive might hurt the quality and sales of their existing, highly profitable menu items. Instead of commercializing the recipe, they publish it in an open cookbook for anyone in the culinary world to read and use.&lt;/p&gt;
&lt;p&gt;Right around that time, a small but ambitious catering startup (OpenAI) gets hold of the public cookbook. They realize that while the recipe itself is brilliant, the real magic happens when you scale it up using a massive industrial kitchen (supercomputing power) and tons of raw ingredients (big data). The startup quickly builds the necessary infrastructure, cooks up the biryani, and serves it directly to hungry customers (the ChatGPT launch). The customers are amazed by the quality and naturally assume the startup invented the recipe from scratch. In reality, the recipe belonged to Google, but OpenAI captured the market by executing at scale at the exact right time.&lt;/p&gt;
&lt;h2 id=&quot;under-the-hood-architecture-what-made-the-transformer-special&quot;&gt;Under-the-Hood Architecture: What Made the Transformer Special?&lt;/h2&gt;
&lt;p&gt;Why was Google&apos;s discovery such a major scientific breakthrough? To understand this, we need to look at how artificial intelligence models processed natural language before the Transformer came along. Prior to 2017, natural language processing relied heavily on Recurrent Neural Networks (RNNs) and Long Short-Term Memory (LSTM) architectures.&lt;/p&gt;
&lt;p&gt;The biggest limitation of those older RNN models was sequential processing. If you fed a twenty-word sentence into the model, the recurrent network had to process the data word by word, moving strictly from the first word to the last. This step-by-step mechanism created two major engineering bottlenecks that prevented large-scale training.&lt;/p&gt;
&lt;p&gt;First, the process was incredibly slow. Because each token depended on the processing completion of the previous token, you could not take full advantage of the parallel processing power of modern GPUs. The time complexity and memory bottlenecks were severe. Second, whenever a sentence grew too long, the model tended to forget the reference or context of earlier words. In machine learning, this issue is known as the vanishing gradient problem.&lt;/p&gt;
&lt;figure&gt;&lt;img src=&quot;https://raw.githubusercontent.com/rafeuddaraj/rafes-blog-assets/refs/heads/generative-ai-under-the-hood-google-vs-openai-deep-dive/assets/transformer-architecture-workflow.svg&quot; alt=&quot;Sequential RNN Processing vs Parallel Transformer Self-Attention Workflow&quot; loading=&quot;lazy&quot; decoding=&quot;async&quot; width=&quot;800&quot; height=&quot;450&quot;&gt;&lt;figcaption&gt;Sequential RNN Processing vs Parallel Transformer Self-Attention Workflow&lt;/figcaption&gt;&lt;/figure&gt;
&lt;p&gt;Google scientists solved this exact problem by introducing the self-attention mechanism. Instead of processing words one after another like a recurrent network, the Transformer architecture loads all the words in a sentence into memory at the exact same time through parallel processing. The self-attention mechanism mathematically calculates an attention weight between every single word and every other word in the sequence.&lt;/p&gt;
&lt;p&gt;For example, take the sentence: &quot;The server crashed because it was overloaded.&quot; An old recurrent network struggled to figure out whether the word &quot;it&quot; referred to the server or the crash. But Google&apos;s self-attention mechanism maps these relationships instantly within a high-dimensional vector space. As a result, processing speeds skyrocketed, making it incredibly easy to scale these models across massive GPU and TPU clusters. You can read more about this breakthrough in the official &lt;a href=&quot;https://research.google/blog/transformer-a-novel-neural-network-architecture-for-language-understanding&quot; rel=&quot;noopener noreferrer&quot;&gt;Google Research Blog Post&lt;/a&gt;.&lt;/p&gt;
&lt;h2 id=&quot;step-by-step-execution-trace-and-code-mechanism&quot;&gt;Step-by-Step Execution Trace and Code Mechanism&lt;/h2&gt;
&lt;p&gt;When you type a prompt into ChatGPT or Gemini, how does the data actually flow under the hood? Let us trace the execution pipeline and memory layout across five distinct steps to see how the engine generates a response:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;Step 1 - Tokenization:&lt;/strong&gt; Your input text is first broken down into smaller pieces called tokens. Each token is then mapped to a specific numerical ID that the computer can understand and manipulate.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Step 2 - Embedding and Positional Encoding:&lt;/strong&gt; Since the Transformer architecture processes all words in parallel, it needs a way to remember word order. Google scientists solved this using positional encoding. A mathematical signature representing the word&apos;s position in the sentence is added to each token&apos;s embedding vector, creating a rich, high-dimensional representation.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Step 3 - Multi-Head Self-Attention:&lt;/strong&gt; This is Google&apos;s core architectural innovation. For each token, the model creates three distinct vectors: Query (Q), Key (K), and Value (V). Using matrix multiplication on these vectors, the model calculates how much focus, or attention, each token should pay to every other token. Multiple attention heads work in parallel to capture different aspects of the text, such as syntax, grammar, and long-term context.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Step 4 - Feed-Forward Network and Normalization:&lt;/strong&gt; The data flows out of the attention blocks and passes through a feed-forward neural network and layer normalization at each stage. This step refines the data representations and stabilizes the learning process.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Step 5 - Output Generation (Softmax):&lt;/strong&gt; Finally, the model calculates a probability distribution across every single token in its entire vocabulary. It predicts and selects the most likely next token to continue the sentence. This entire execution cycle loops thousands of times per millisecond to stream the final answer onto your screen.&lt;/li&gt;
&lt;/ul&gt;
&lt;h2 id=&quot;googles-mistake-or-extreme-caution&quot;&gt;Google&apos;s Mistake or Extreme Caution?&lt;/h2&gt;
&lt;p&gt;Now brings us to the biggest question: Why didn&apos;t Google release a commercial product like ChatGPT first, especially since they invented the underlying technology? Was this an engineering failure on their part? Not at all. It was primarily a conflict of corporate culture and business models.&lt;/p&gt;
&lt;p&gt;The first factor was reputation risk and the fear of hallucinations. As a multi-billion-dollar public company, Google holds a massive amount of global trust. One well-known limitation of large language models is hallucination, where the AI presents completely false information with absolute confidence. Google leadership worried that releasing an imperfect chatbot that provided incorrect or biased answers would severely damage the credibility of their flagship search engine.&lt;/p&gt;
&lt;p&gt;The second and most critical factor was the Innovator&apos;s Dilemma and business model cannibalization. Google makes the vast majority of its revenue from its search engine and advertising network. When you search for something on Google, you see links to different websites alongside sponsored advertisements. If Google released an AI interface that gave users direct, instant answers, people would stop clicking on website links and ad banners. Google hesitated to push a technology that could actively cannibalize its multi-billion-dollar advertising empire.&lt;/p&gt;
&lt;h2 id=&quot;openais-entry-and-masterstroke&quot;&gt;OpenAI&apos;s Entry and Masterstroke&lt;/h2&gt;
&lt;p&gt;While Google sat in analysis meetings debating model safety and revenue impact, OpenAI stepped onto the field. They recognized the true commercial potential of Google&apos;s open-source Transformer architecture. OpenAI believed firmly in a simple principle known as scaling laws. They hypothesized that if you exponentially increased the parameter count and training data of a Transformer model, advanced reasoning and logical capabilities would emerge automatically.&lt;/p&gt;
&lt;p&gt;They methodically released the &lt;a href=&quot;https://cdn.openai.com/research-covers/language-unsupervised/language_understanding_paper.pdf&quot; rel=&quot;noopener noreferrer&quot;&gt;GPT-1 Technical Paper (2018)&lt;/a&gt; with 117 million parameters, followed by GPT-2 with 1.5 billion parameters, and the historic &lt;a href=&quot;https://arxiv.org/abs/2005.14165&quot; rel=&quot;noopener noreferrer&quot;&gt;GPT-3 Technical Paper (2020)&lt;/a&gt; with 175 billion parameters. However, OpenAI&apos;s true masterstroke was not just training large models. Their smartest move was product delivery and user interface design.&lt;/p&gt;
&lt;p&gt;When they released ChatGPT in November 2022, they did not offer a complex API or a developer-only terminal console. Instead, they launched a simple, familiar chat interface that anyone could use immediately. Everyday users could converse with the AI without needing any programming knowledge. That single UX decision caught Silicon Valley completely off guard and secured OpenAI an unbeatable first-mover advantage.&lt;/p&gt;
&lt;div class=&quot;callout&quot; role=&quot;note&quot; data-type=&quot;note&quot;&gt;
&lt;p class=&quot;callout-title&quot;&gt;Important&lt;/p&gt;
&lt;p&gt;UI/UX and Accessibility Advantage: No matter how powerful your underlying engineering architecture is, a technology will struggle to achieve mass adoption if it lacks a simple, intuitive user interface. The clean simplicity of the ChatGPT interface was one of the biggest catalysts for its exponential growth.&lt;/p&gt;
&lt;/div&gt;
&lt;h2 id=&quot;was-it-theft-or-just-how-open-source-works&quot;&gt;Was It Theft, or Just How Open-Source Works?&lt;/h2&gt;
&lt;p&gt;Many casual tech observers ask a fair question: If OpenAI built a multi-billion-dollar business using technology invented by Google, is that legally considered theft? From a strictly legal standpoint, the answer is no.&lt;/p&gt;
&lt;p&gt;The code and architectural blueprints that Google published alongside their &quot;Attention Is All You Need&quot; paper were released under an open-source license. The fundamental principle of open-source software is that anyone is free to use, modify, and build commercial products on top of the technology. OpenAI operated entirely within normal legal and open-source boundaries.&lt;/p&gt;
&lt;p&gt;From a business and strategy perspective, however, industry experts often call this one of the greatest idea hijacks or value capture failures in technology history. Google&apos;s scientific teams spent years and millions of dollars on research and development, yet a relatively small startup walked away with the market leadership and commercial rewards.&lt;/p&gt;
&lt;p&gt;To make matters worse for Google, the event triggered a massive brain drain. All eight scientists who authored the original Transformer paper ended up leaving Google within a few years of ChatGPT&apos;s release. Frustrated by corporate bureaucracy and slow product timelines, they departed to launch their own successful artificial intelligence startups. For example, &lt;a href=&quot;https://en.wikipedia.org/wiki/Ashish_Vaswani&quot; rel=&quot;noopener noreferrer&quot;&gt;Ashish Vaswani&lt;/a&gt; and &lt;a href=&quot;https://share.google/XklSybxSwldbKWK0q&quot; rel=&quot;noopener noreferrer&quot;&gt;Niki Parmar&lt;/a&gt; founded &lt;a href=&quot;https://www.essential.ai/&quot; rel=&quot;noopener noreferrer&quot;&gt;Essential AI&lt;/a&gt;, &lt;a href=&quot;https://en.wikipedia.org/wiki/Aidan_Gomez&quot; rel=&quot;noopener noreferrer&quot;&gt;Aidan Gomez&lt;/a&gt; founded the highly valued AI company &lt;a href=&quot;https://cohere.com/&quot; rel=&quot;noopener noreferrer&quot;&gt;Cohere&lt;/a&gt;, and &lt;a href=&quot;https://en.wikipedia.org/wiki/Noam_Shazeer&quot; rel=&quot;noopener noreferrer&quot;&gt;Noam Shazeer&lt;/a&gt; founded &lt;a href=&quot;https://character.ai/&quot; rel=&quot;noopener noreferrer&quot;&gt;Character.ai&lt;/a&gt;, a startup that Google eventually brought back into its ecosystem through a multi-billion-dollar deal.&lt;/p&gt;
&lt;h2 id=&quot;googles-panic-mode-and-the-current-ai-war&quot;&gt;Google&apos;s Panic Mode and the Current AI War&lt;/h2&gt;
&lt;p&gt;Within just a few weeks of launching, ChatGPT broke historical records by reaching one million, and then one hundred million active users faster than any software product in history. This unprecedented growth triggered internal panic at Google headquarters. Google CEO Sundar Pichai issued a company-wide &quot;Code Red,&quot; calling in company founders Larry Page and Sergey Brin from retirement to help steer their AI strategy.&lt;/p&gt;
&lt;p&gt;Realizing they had fallen behind in the race, Google rushed to release their first AI chatbot, named Bard, in early 2023. Because the launch was rushed, Bard gave a factually incorrect answer about the James Webb Space Telescope during its official demo event. That single public error caused Google&apos;s stock price to plummet, wiping out over one hundred billion dollars in market value in a single day.&lt;/p&gt;
&lt;figure&gt;&lt;img src=&quot;https://raw.githubusercontent.com/rafeuddaraj/rafes-blog-assets/refs/heads/generative-ai-under-the-hood-google-vs-openai-deep-dive/assets/ai-market-timeline-clash.svg&quot; alt=&quot;Generative AI Market Evolution and Timeline Clash&quot; loading=&quot;lazy&quot; decoding=&quot;async&quot; width=&quot;900&quot; height=&quot;390&quot;&gt;&lt;figcaption&gt;Generative AI Market Evolution and Timeline Clash&lt;/figcaption&gt;&lt;/figure&gt;
&lt;p&gt;Following that rough start, Google restructured its entire artificial intelligence division. They merged their scattered AI research teams, Google Brain and DeepMind, into a single powerhouse called Google DeepMind. They retired the Bard brand completely and introduced the &lt;a href=&quot;https://arxiv.org/abs/2312.11805&quot; rel=&quot;noopener noreferrer&quot;&gt;Gemini Technical Architecture&lt;/a&gt;.&lt;/p&gt;
&lt;p&gt;Today, Google&apos;s Gemini models compete directly against OpenAI&apos;s GPT-4 and Omni architectures. Google holds a massive long-term advantage thanks to its vast data ecosystem, which includes YouTube, Search, and Android, as well as its custom Tensor Processing Unit (TPU) hardware infrastructure. They are actively using these proprietary assets to win back the market share they lost.&lt;/p&gt;
&lt;div class=&quot;callout&quot; role=&quot;note&quot; data-type=&quot;warning&quot;&gt;
&lt;p class=&quot;callout-title&quot;&gt;Warning&lt;/p&gt;
&lt;p&gt;Analysis Paralysis and Market Timing: Waiting around for absolute perfection and zero risk in a production system can cost you your first-mover advantage entirely. In software engineering, deploying a functional product quickly to establish a real-world user feedback loop is almost always more effective than chasing static perfection in a lab.&lt;/p&gt;
&lt;/div&gt;
&lt;h2 id=&quot;final-thoughts-and-production-decision-rules&quot;&gt;Final Thoughts and Production Decision Rules&lt;/h2&gt;
&lt;p&gt;The story of Google doing the foundational research while OpenAI captured the commercial victory offers critical lessons for software engineers, system architects, and technology leaders. Having a brilliant idea or theoretical breakthrough does not guarantee success by itself. The real advantage comes from scaling that architecture at the right time and wrapping it in an accessible, user-friendly product.&lt;/p&gt;
&lt;p&gt;As a software architect or developer, you can apply three core production decision rules from this deep dive to your daily engineering projects and system designs:&lt;/p&gt;
&lt;ol&gt;
&lt;li&gt;&lt;strong&gt;Ensure Ecosystem Readiness:&lt;/strong&gt; If you plan to open-source a core library or architectural innovation, make sure your team is prepared to build commercial products and ecosystems on top of it first. Otherwise, someone else will step in and capture the commercial value of your invention.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Balance Ideation with Execution:&lt;/strong&gt; Never fall into the trap of over-engineering or waiting endlessly for perfection. Deploy a Minimum Viable Product (MVP) or a basic, functional version to production as soon as possible. Real-world usage data is the best guide you have for making accurate architectural improvements over time.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Prioritize Accessibility and User Experience:&lt;/strong&gt; It does not matter how clean your backend code is or how fast your database queries run; if end-users cannot consume that value through a simple interface, the system will fail. Always strive to hide complex, under-the-hood engineering behind a clean, intuitive, and frictionless user interface.&lt;/li&gt;
&lt;/ol&gt;
&lt;hr&gt;
&lt;h2 id=&quot;references-and-further-reading&quot;&gt;References and Further Reading&lt;/h2&gt;
&lt;p&gt;If you want to explore the mathematical concepts and technical specifications of the Transformer architecture in greater detail, check out these official whitepapers and documentation links:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;a href=&quot;https://arxiv.org/abs/1706.03762&quot; rel=&quot;noopener noreferrer&quot;&gt;Attention Is All You Need (arXiv:1706.03762)&lt;/a&gt;: The original historic 2017 research paper published by Google that first introduced the Transformer architecture and the self-attention mechanism to the world.&lt;/li&gt;
&lt;li&gt;&lt;a href=&quot;https://research.google/blog/transformer-a-novel-neural-network-architecture-for-language-understanding&quot; rel=&quot;noopener noreferrer&quot;&gt;Google Research Blog: Transformer A Novel Neural Network Architecture&lt;/a&gt;: The official Google Brain blog post explaining the mechanics of the Transformer architecture and the benefits of parallel processing in clear, accessible terms.&lt;/li&gt;
&lt;li&gt;&lt;a href=&quot;https://cdn.openai.com/research-covers/language-unsupervised/language_understanding_paper.pdf&quot; rel=&quot;noopener noreferrer&quot;&gt;Improving Language Understanding by Generative Pre-Training (GPT-1 Paper)&lt;/a&gt;: OpenAI&apos;s foundational paper demonstrating how to apply Google&apos;s Transformer architecture for generative pre-training and downstream fine-tuning.&lt;/li&gt;
&lt;li&gt;&lt;a href=&quot;https://arxiv.org/abs/2005.14165&quot; rel=&quot;noopener noreferrer&quot;&gt;Language Models are Few-Shot Learners (GPT-3 Paper - arXiv:2005.14165)&lt;/a&gt;: The comprehensive 175-billion parameter model paper from OpenAI that proved how scaling laws drive emergent capabilities in generative AI.&lt;/li&gt;
&lt;li&gt;&lt;a href=&quot;https://arxiv.org/abs/2312.11805&quot; rel=&quot;noopener noreferrer&quot;&gt;Gemini: A Family of Highly Capable Multimodal Models (arXiv:2312.11805)&lt;/a&gt;: The official technical report detailing Google&apos;s modern Gemini architecture, released as part of their competitive comeback against OpenAI.&lt;/li&gt;
&lt;li&gt;&lt;a href=&quot;https://jalammar.github.io/illustrated-transformer/&quot; rel=&quot;noopener noreferrer&quot;&gt;The Illustrated Transformer by Jay Alammar&lt;/a&gt;: One of the most popular engineering blog posts in the software community for visually understanding data flow, matrix multiplication, and multi-head attention mechanics under the hood.&lt;/li&gt;
&lt;/ul&gt;</content:encoded><category>Artificial Intelligence</category><category>Deep Dive</category><category>Under the hood</category><category>Architecture</category><category>Generative AI</category><category>Transformer</category><category>System Design</category><category>OpenAI</category><category>Google</category><category>References</category></item><item><title>The Complete Engineering Handbook: Data Structures and Algorithms for Production Scalability</title><link>https://www.rafeuddaraj.me/blog/the-complete-engineering-handbook-data-structures-and-algorithms-for-production-scalability/</link><guid isPermaLink="true">https://www.rafeuddaraj.me/blog/the-complete-engineering-handbook-data-structures-and-algorithms-for-production-scalability/</guid><description>A practical engineering guide explaining real-world production bottlenecks, memory layouts, Big-O notation, and system architecture to help developers build scalable software.</description><pubDate>Sun, 28 Jun 2026 10:01:14 GMT</pubDate><content:encoded>&lt;h2 id=&quot;core-philosophy-why-are-we-here&quot;&gt;Core Philosophy (Why Are We Here?)&lt;/h2&gt;
&lt;p&gt;You just finished building a fantastic web application. In your local development environment, everything runs at top speed for ten users. Every request processes in milliseconds, and database queries return answers without any delay. But the day you deploy your application to a production server and traffic suddenly spikes to a hundred thousand concurrent requests, disaster strikes. Your server memory and CPU usage hit one hundred percent, API response times stretch into seconds, and eventually, the entire system crashes. Have you ever wondered why code that works perfectly on your local machine breaks down so miserably under real production loads?&lt;/p&gt;
&lt;p&gt;There is a widespread misconception in the software engineering industry. Many developers believe that knowing the syntax of a programming language, such as writing loops or conditional statements, is the foundation of software engineering. But in real production environments, simply knowing how to write code is not enough to build scalable systems. When your code executes, you need a deep understanding of how the computer stores data in memory and how the processor handles that information. Without this foundational mechanical knowledge, request bottlenecks are inevitable. It does not matter how powerful your cloud servers or hardware configurations are; inefficient code architecture will destroy your system performance.&lt;/p&gt;
&lt;p&gt;What exactly is a data structure? In simple terms, it is the art of organizing and storing data efficiently inside computer memory. To understand this concept, let us look at a real-world analogy. Imagine a disorganized workshop where thousands of tools are scattered randomly across the floor. If you need to find a specific screwdriver in that mess, you will easily waste thirty minutes searching for it. Now, picture a well-organized, smart toolbox where every single tool has a dedicated, custom-fitted slot. With that toolbox, you could grab the exact tool you need in just a few seconds without even looking. A data structure is that smart toolbox for your computer memory, arranging data so that your system can find and process it instantly when needed.&lt;/p&gt;
&lt;p&gt;On the other hand, an algorithm is a step-by-step set of logical instructions or a recipe for working with that organized data. You might own the best toolbox in the world, but if you do not know the exact steps required to repair an engine using those tools, you will not get any work done. In the exact same way, simply organizing your data is not enough. You must also choose the fastest logical path to search through, retrieve, or modify that information. The real secret to building high-performing, scalable systems and APIs is the exact combination of the right data structure with an optimized algorithm. Without this powerful pairing, no modern software architecture can truly be production ready.&lt;/p&gt;
&lt;hr&gt;
&lt;h2 id=&quot;performance-measurement-standards-big-o-notation-and-trade-offs&quot;&gt;Performance Measurement Standards (Big-O Notation and Trade-offs)&lt;/h2&gt;
&lt;p&gt;When we write code or logic as software engineers, measuring how fast that code executes is critical. However, if you try to measure the speed of your code using seconds or milliseconds, you are making a major engineering mistake. Time measurements depend entirely on the processing power of the underlying hardware. A piece of code might run in ten milliseconds on your brand new, high-end laptop, but that exact same code could take a full second to execute on an older device owned by your user. Because of this discrepancy, we need a universal measurement scale that does not rely on hardware specifications or processor speeds. We need a metric that shows how code performance changes as the size of the input data grows.&lt;/p&gt;
&lt;p&gt;This universal standard is known as Big-O Notation. It tells us how rapidly the required time or memory will increase as the input data grows in size. In this context, we must evaluate two main concepts: time complexity and space complexity. Time complexity measures how many logical operations or steps the code needs to complete its task. Space complexity measures how much additional memory your code consumes while it runs. Maintaining a clean balance between these two metrics is essential in production architecture. We often have to trade extra memory consumption to gain faster processing speeds, or accept slightly longer processing times to conserve valuable system memory.&lt;/p&gt;
&lt;p&gt;Several primary forms of Big-O Notation influence our daily engineering decisions. Here is a simple breakdown of how they work:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;O(1) - Constant Time:&lt;/strong&gt; This represents peak performance. Whether your system contains ten records or ten million records, this logic will always take the exact same amount of time to execute. For example, grabbing a value directly from an array using its index number does not depend on the size of the dataset.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;O(n) - Linear Time:&lt;/strong&gt; In this scenario, as the input data multiplies, the execution time multiplies at the exact same rate. If you write a loop to search from the beginning to the end of an array for a specific value, searching through ten million items might require up to ten million iterations.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;O(log n) - Logarithmic Time:&lt;/strong&gt; This is a highly efficient and fast performance pattern. With this approach, the search area or dataset is cut in half at every single step. Even if the data size doubles, the algorithm only requires one additional step to complete its work. This makes it ideal for working with large databases and sorted lists.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;O(n^2) - Quadratic Time:&lt;/strong&gt; This is the silent killer of production systems. When you write nested loops in your code, meaning one loop runs inside another loop, the processing time grows geometrically as the data increases. If you have one thousand items, your loop will run one million times, which can instantly freeze your server.&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;&lt;img src=&quot;https://raw.githubusercontent.com/rafeuddaraj/rafes-blog-assets/refs/heads/the-complete-engineering-handbook-data-structures-and-algorithms-for-production-scalability/assets/big-o-performance-curves.svg&quot; alt=&quot;Big-O Notation Complexity Chart - Comparing O(1) Constant, O(log n) Logarithmic, O(n) Linear, and O(n²) Quadratic Time Performance Curves&quot; loading=&quot;lazy&quot; decoding=&quot;async&quot; width=&quot;800&quot; height=&quot;500&quot;&gt;
Take a look at the diagram above. It clearly shows how performance changes across different Big-O complexities as the input data grows. In production environments, our primary goal is to keep code within constant time or logarithmic time whenever possible, and strictly avoid quadratic time or worse logic at all costs.&lt;/p&gt;
&lt;hr&gt;
&lt;h2 id=&quot;memory-layout-and-linear-data-structures-the-foundation&quot;&gt;Memory Layout and Linear Data Structures (The Foundation)&lt;/h2&gt;
&lt;p&gt;To truly understand data structures, we first need to look at how computer memory actually works. When you create a variable or store data in your code, the operating system places it in a specific location inside your system memory. You can picture memory as a long, continuous row of billions of tiny boxes. Each box holds one byte of data and has its own unique memory address, much like every house on a street has a unique house number. When the processor wants to read or write data, it communicates directly using that memory address.&lt;/p&gt;
&lt;p&gt;Based on this memory layout, the most fundamental data structure we use is the array. An array is simply a collection of continuous, sequential memory blocks. When you declare an array in your code, the system allocates a continuous strip of memory boxes right next to each other. To picture this, think of booking movie theater tickets with your friends. If you want to sit together and book five seats, the ticketing clerk assigns you five consecutive seats in the exact same row. An array occupies memory in that exact same continuous manner.&lt;/p&gt;
&lt;p&gt;Reading data from an array using an index happens in constant time. Because the data items sit right next to each other in memory, the computer uses a simple mathematical formula to calculate the exact memory address of any index instantly. The formula is: &lt;span class=&quot;katex&quot;&gt;&lt;span class=&quot;katex-html&quot; aria-hidden=&quot;true&quot;&gt;&lt;span class=&quot;base&quot;&gt;&lt;span class=&quot;strut&quot; style=&quot;height:0.8889em;vertical-align:-0.1944em;&quot;&gt;&lt;/span&gt;&lt;span class=&quot;mord text&quot;&gt;&lt;span class=&quot;mord&quot;&gt;Target Address&lt;/span&gt;&lt;/span&gt;&lt;span class=&quot;mspace&quot; style=&quot;margin-right:0.2778em;&quot;&gt;&lt;/span&gt;&lt;span class=&quot;mrel&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mspace&quot; style=&quot;margin-right:0.2778em;&quot;&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class=&quot;base&quot;&gt;&lt;span class=&quot;strut&quot; style=&quot;height:0.7778em;vertical-align:-0.0833em;&quot;&gt;&lt;/span&gt;&lt;span class=&quot;mord text&quot;&gt;&lt;span class=&quot;mord&quot;&gt;Base Address&lt;/span&gt;&lt;/span&gt;&lt;span class=&quot;mspace&quot; style=&quot;margin-right:0.2222em;&quot;&gt;&lt;/span&gt;&lt;span class=&quot;mbin&quot;&gt;+&lt;/span&gt;&lt;span class=&quot;mspace&quot; style=&quot;margin-right:0.2222em;&quot;&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class=&quot;base&quot;&gt;&lt;span class=&quot;strut&quot; style=&quot;height:1em;vertical-align:-0.25em;&quot;&gt;&lt;/span&gt;&lt;span class=&quot;mopen&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mord text&quot;&gt;&lt;span class=&quot;mord&quot;&gt;Index&lt;/span&gt;&lt;/span&gt;&lt;span class=&quot;mspace&quot; style=&quot;margin-right:0.2222em;&quot;&gt;&lt;/span&gt;&lt;span class=&quot;mbin&quot;&gt;×&lt;/span&gt;&lt;span class=&quot;mspace&quot; style=&quot;margin-right:0.2222em;&quot;&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class=&quot;base&quot;&gt;&lt;span class=&quot;strut&quot; style=&quot;height:1em;vertical-align:-0.25em;&quot;&gt;&lt;/span&gt;&lt;span class=&quot;mord text&quot;&gt;&lt;span class=&quot;mord&quot;&gt;Size of Element&lt;/span&gt;&lt;/span&gt;&lt;span class=&quot;mclose&quot;&gt;)&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;. However, the major weakness of an array comes into play when you try to insert or delete data from the middle of the sequence. If you want to drop a new item into the middle of an array, you must shift every subsequent item one position to the right to clear space. In an array of ten million items, this shifting process is extremely slow and results in linear time complexity.&lt;/p&gt;
&lt;p&gt;To overcome this physical limitation, we use the linked list. In a linked list, data items do not need to sit in continuous, sequential memory blocks like they do in an array. A data block, called a node, can sit anywhere in memory where empty space is available. Every single node contains two things: the actual data value, and a pointer that stores the memory address of the next node in the sequence. To visualize this architecture, think of a classic treasure hunt game. When you find your first clue, it gives you the location of the second clue. You travel to that spot to find the second clue, which then directs you to the third location. A linked list operates on this exact same chaining mechanism.&lt;/p&gt;
&lt;p&gt;Deciding whether to use an array or a linked list in production depends entirely on your specific use case. If your system frequently reads data by index number, an array is the best choice. However, if your application constantly inserts and deletes data from the middle of a list and you cannot predict the total data size in advance, a linked list will deliver superior performance. With a linked list, you never have to shift massive amounts of data; you simply update the address stored in the pointers, and the job is done.&lt;/p&gt;
&lt;p&gt;&lt;img src=&quot;https://raw.githubusercontent.com/rafeuddaraj/rafes-blog-assets/refs/heads/the-complete-engineering-handbook-data-structures-and-algorithms-for-production-scalability/assets/memory-layout-comparison.svg&quot; alt=&quot;Array vs Linked List Memory Layout - Contiguous Sequential Blocks vs Scattered Pointer-Based Nodes in RAM&quot; loading=&quot;lazy&quot; decoding=&quot;async&quot; width=&quot;800&quot; height=&quot;450&quot;&gt;
Two other essential concepts in the world of linear data structures are the stack and the queue. A stack operates on a Last-In, First-Out model. A great analogy for a stack is a pile of clean plates sitting on a dining table. When you wash plates and stack them one on top of another, the plate you placed on the very top is always the first one you grab when setting the table for dinner. This architecture is heavily used across software engineering. The back button in your web browser, the call stack during code execution, and the undo and redo features in text editors all rely completely on this stack mechanism.&lt;/p&gt;
&lt;p&gt;In contrast, a queue operates on a First-In, First-Out model. A real-world analogy for a queue is a line of people waiting at a bank cashier or a movie theater ticketing counter. The person who arrives first and stands at the front of the line is the first person to receive service and leave the counter. Queues are an indispensable component in backend and systems architecture. The Node.js event loop, background job processing in microservice architectures, and heavy-duty task queues or message brokers like RabbitMQ and Apache Kafka all scale by relying on this exact first-in, first-out principle.&lt;/p&gt;
&lt;hr&gt;
&lt;figure&gt;&lt;img src=&quot;https://raw.githubusercontent.com/rafeuddaraj/rafes-blog-assets/refs/heads/the-complete-engineering-handbook-data-structures-and-algorithms-for-production-scalability/assets/stack-vs-queue-execution-flow.svg&quot; alt=&quot;Stack LIFO vs Queue FIFO Execution Flow - Call Stack Architecture vs Event Loop Task Queue&quot; loading=&quot;lazy&quot; decoding=&quot;async&quot; width=&quot;800&quot; height=&quot;450&quot;&gt;&lt;figcaption&gt;Stack LIFO vs Queue FIFO Execution Flow - Call Stack Architecture vs Event Loop Task Queue&lt;/figcaption&gt;&lt;/figure&gt;
&lt;h2 id=&quot;fastest-data-lookup-hash-tables-and-maps&quot;&gt;Fastest Data Lookup (Hash Tables and Maps)&lt;/h2&gt;
&lt;p&gt;When we deal with massive datasets in production engineering, our primary objective is finding specific data as quickly as possible. If you need to search through a database of ten million users to find a specific email address or user profile in just a single millisecond, linear arrays and linked lists simply will not work. For this kind of ultra-fast lookup, an engineer&apos;s most powerful weapon is the hash table, also known as a map. A hash table performs the magic of retrieving data from any database or list in constant time, regardless of the dataset size.&lt;/p&gt;
&lt;p&gt;The real power behind this lookup speed is the hash function. A hash function is a specialized mathematical algorithm that takes a string, number, or key as input, runs a specific calculation, and converts that key into an integer that serves as a memory index. For example, when you pass the key &quot;user_1029&quot; into a hash table, the hash function uses a mathematical formula to determine that this user profile sits in memory slot number 42. Later, when you request the data for &quot;user_1029&quot; again, the system does not run a search loop; it simply runs the hash function and pulls the data directly from slot 42.&lt;/p&gt;
&lt;div class=&quot;expressive-code&quot;&gt;&lt;style&gt;.expressive-code{font-family:var(--ec-uiFontFml);font-size:var(--ec-uiFontSize);font-weight:var(--ec-uiFontWg);line-height:var(--ec-uiLineHt);text-size-adjust:none;-webkit-text-size-adjust:none}.expressive-code *:not(:is(svg, svg *)){all:revert;box-sizing:border-box}.expressive-code pre{display:flex;margin:0;padding:0;border:var(--ec-brdWd) solid var(--ec-brdCol);border-radius:calc(var(--ec-brdRad) + var(--ec-brdWd));background:var(--ec-codeBg)}.expressive-code pre:focus-visible{outline:3px solid var(--ec-focusBrd);outline-offset:-3px}.expressive-code pre &gt; code{all:unset;display:block;flex:1 0 100%;padding:var(--ec-codePadBlk) 0;color:var(--ec-codeFg);font-family:var(--ec-codeFontFml);font-size:var(--ec-codeFontSize);font-weight:var(--ec-codeFontWg);line-height:var(--ec-codeLineHt)}.expressive-code pre{overflow-x:auto}.expressive-code pre.wrap .ec-line .code{white-space:pre-wrap;overflow-wrap:break-word;min-width:min(20ch, var(--ecMaxLine, 20ch))}.expressive-code pre.wrap .ec-line .code span.indent{white-space:pre}.expressive-code pre::-webkit-scrollbar,.expressive-code pre::-webkit-scrollbar-track{background-color:inherit;border-radius:calc(var(--ec-brdRad) + var(--ec-brdWd));border-top-left-radius:0;border-top-right-radius:0}.expressive-code pre::-webkit-scrollbar-thumb{background-color:var(--ec-sbThumbCol);border:4px solid transparent;background-clip:content-box;border-radius:10px}.expressive-code pre::-webkit-scrollbar-thumb:hover{background-color:var(--ec-sbThumbHoverCol)}.expressive-code pre::-webkit-scrollbar-corner{background:transparent}.expressive-code .ec-line{direction:ltr;unicode-bidi:isolate;display:grid;grid-template-areas:&apos;gutter code&apos;;grid-template-columns:auto 1fr;position:relative}.expressive-code .ec-line .gutter{grid-area:gutter;color:var(--ec-gtrFg)}.expressive-code .ec-line .gutter &gt; *{pointer-events:none;user-select:none;-webkit-user-select:none}.expressive-code .ec-line .gutter ~ .code{--ecLineBrdCol:var(--ec-gtrBrdCol)}.expressive-code .ec-line.highlight .gutter{color:var(--ec-gtrHlFg)}.expressive-code .ec-line .code{grid-area:code;position:relative;box-sizing:content-box;padding-inline-start:calc(var(--ecIndent, 0ch) + var(--ec-codePadInl) - var(--ecGtrBrdWd));padding-inline-end:var(--ec-codePadInl);text-indent:calc(var(--ecIndent, 0ch) * -1)}.expressive-code .ec-line .code::before,.expressive-code .ec-line .code::after,.expressive-code .ec-line .code :where(*){text-indent:0}.expressive-code .ec-line .code{--ecGtrBrdWd:var(--ec-gtrBrdWd);border-inline-start:var(--ecGtrBrdWd) solid var(--ecLineBrdCol, transparent)}.expressive-code .sr-only{position:absolute;width:1px;height:1px;padding:0;margin:-1px;overflow:hidden;clip:rect(0, 0, 0, 0);white-space:nowrap;border-width:0}.expressive-code .ec-line.mark{--tmLineBgCol:var(--ec-tm-markBg)}.expressive-code .ec-line.mark .code{--ecLineBrdCol:var(--ec-tm-markBrdCol)}.expressive-code .ec-line.ins{--tmLineBgCol:var(--ec-tm-insBg);--tmLabel:var(--ec-tm-insDiffIndContent)}.expressive-code .ec-line.ins .code{--ecLineBrdCol:var(--ec-tm-insBrdCol)}.expressive-code .ec-line.ins .code::before{color:var(--ec-tm-insDiffIndCol)}.expressive-code .ec-line.del{--tmLineBgCol:var(--ec-tm-delBg);--tmLabel:var(--ec-tm-delDiffIndContent)}.expressive-code .ec-line.del .code{--ecLineBrdCol:var(--ec-tm-delBrdCol)}.expressive-code .ec-line.del .code::before{color:var(--ec-tm-delDiffIndCol)}.expressive-code .ec-line.mark,.expressive-code .ec-line.ins,.expressive-code .ec-line.del{background:var(--tmLineBgCol)}.expressive-code .ec-line.mark .code,.expressive-code .ec-line.ins .code,.expressive-code .ec-line.del .code{--ecGtrBrdWd:var(--ec-tm-lineMarkerAccentWd)}.expressive-code .ec-line.mark .code::before,.expressive-code .ec-line.ins .code::before,.expressive-code .ec-line.del .code::before{display:block;position:absolute;left:0;box-sizing:border-box;content:var(--tmLabel, &apos; &apos;);padding-inline-start:var(--ec-tm-lineDiffIndMargLeft);text-align:center;white-space:pre}.expressive-code .ec-line.mark.tm-label .code::before,.expressive-code .ec-line.ins.tm-label .code::before,.expressive-code .ec-line.del.tm-label .code::before{background:var(--ecLineBrdCol);padding:0 calc(var(--ec-tm-lineMarkerLabelPadInl) + var(--ec-tm-lineMarkerAccentWd)) 0 var(--ec-tm-lineMarkerLabelPadInl);color:var(--ec-tm-lineMarkerLabelCol)}.expressive-code .ec-line mark{--tmInlineBgCol:var(--ec-tm-markBg);--tmInlineBrdCol:var(--ec-tm-markBrdCol)}.expressive-code .ec-line ins{--tmInlineBgCol:var(--ec-tm-insBg);--tmInlineBrdCol:var(--ec-tm-insBrdCol)}.expressive-code .ec-line del{--tmInlineBgCol:var(--ec-tm-delBg);--tmInlineBrdCol:var(--ec-tm-delBrdCol)}.expressive-code .ec-line mark,.expressive-code .ec-line ins,.expressive-code .ec-line del{all:unset;display:inline-block;position:relative;--tmBrdL:var(--ec-tm-inlMarkerBrdWd);--tmBrdR:var(--ec-tm-inlMarkerBrdWd);--tmRadL:var(--ec-tm-inlMarkerBrdRad);--tmRadR:var(--ec-tm-inlMarkerBrdRad);margin-inline:0.025rem;padding-inline:var(--ec-tm-inlMarkerPad);border-radius:var(--tmRadL) var(--tmRadR) var(--tmRadR) var(--tmRadL);background:var(--tmInlineBgCol);background-clip:padding-box}.expressive-code .ec-line mark.open-start,.expressive-code .ec-line ins.open-start,.expressive-code .ec-line del.open-start{margin-inline-start:0;padding-inline-start:0;--tmBrdL:0px;--tmRadL:0}.expressive-code .ec-line mark.open-end,.expressive-code .ec-line ins.open-end,.expressive-code .ec-line del.open-end{margin-inline-end:0;padding-inline-end:0;--tmBrdR:0px;--tmRadR:0}.expressive-code .ec-line mark::before,.expressive-code .ec-line ins::before,.expressive-code .ec-line del::before{content:&apos;&apos;;position:absolute;pointer-events:none;display:inline-block;inset:0;border-radius:var(--tmRadL) var(--tmRadR) var(--tmRadR) var(--tmRadL);border:var(--ec-tm-inlMarkerBrdWd) solid var(--tmInlineBrdCol);border-inline-width:var(--tmBrdL) var(--tmBrdR)}.expressive-code .frame{all:unset;position:relative;display:block;--header-border-radius:calc(var(--ec-brdRad) + var(--ec-brdWd));--tab-border-radius:calc(var(--ec-frm-edTabBrdRad) + var(--ec-brdWd));--button-spacing:0.4rem;--code-background:var(--ec-frm-edBg);border-radius:var(--header-border-radius);box-shadow:var(--ec-frm-frameBoxShdCssVal)}.expressive-code .frame .header{display:none;z-index:1;position:relative;border-radius:var(--header-border-radius) var(--header-border-radius) 0 0}.expressive-code .frame.has-title pre,.expressive-code .frame.has-title code,.expressive-code .frame.is-terminal pre,.expressive-code .frame.is-terminal code{border-top:none;border-top-left-radius:0;border-top-right-radius:0}.expressive-code .frame .title:empty:before{content:&apos;\a0&apos;}.expressive-code .frame.has-title:not(.is-terminal){--button-spacing:calc(1.9rem + 2 * (var(--ec-uiPadBlk) + var(--ec-frm-edActTabIndHt)))}.expressive-code .frame.has-title:not(.is-terminal) .title{position:relative;color:var(--ec-frm-edActTabFg);background:var(--ec-frm-edActTabBg);background-clip:padding-box;margin-block-start:var(--ec-frm-edTabsMargBlkStart);padding:calc(var(--ec-uiPadBlk) + var(--ec-frm-edActTabIndHt)) var(--ec-uiPadInl);border:var(--ec-brdWd) solid var(--ec-frm-edActTabBrdCol);border-radius:var(--tab-border-radius) var(--tab-border-radius) 0 0;border-bottom:none;overflow:hidden}.expressive-code .frame.has-title:not(.is-terminal) .title::after{content:&apos;&apos;;position:absolute;pointer-events:none;inset:0;border-top:var(--ec-frm-edActTabIndHt) solid var(--ec-frm-edActTabIndTopCol);border-bottom:var(--ec-frm-edActTabIndHt) solid var(--ec-frm-edActTabIndBtmCol)}.expressive-code .frame.has-title:not(.is-terminal) .header{display:flex;background:linear-gradient(to top, var(--ec-frm-edTabBarBrdBtmCol) var(--ec-brdWd), transparent var(--ec-brdWd)),linear-gradient(var(--ec-frm-edTabBarBg), var(--ec-frm-edTabBarBg));background-repeat:no-repeat;padding-inline-start:var(--ec-frm-edTabsMargInlStart)}.expressive-code .frame.has-title:not(.is-terminal) .header::before{content:&apos;&apos;;position:absolute;pointer-events:none;inset:0;border:var(--ec-brdWd) solid var(--ec-frm-edTabBarBrdCol);border-radius:inherit;border-bottom:none}.expressive-code .frame.is-terminal{--button-spacing:calc(1.9rem + var(--ec-brdWd) + 2 * var(--ec-uiPadBlk));--code-background:var(--ec-frm-trmBg)}.expressive-code .frame.is-terminal .header{display:flex;align-items:center;justify-content:center;padding-block:var(--ec-uiPadBlk);padding-block-end:calc(var(--ec-uiPadBlk) + var(--ec-brdWd));position:relative;font-weight:500;letter-spacing:0.025ch;color:var(--ec-frm-trmTtbFg);background:var(--ec-frm-trmTtbBg);border:var(--ec-brdWd) solid var(--ec-brdCol);border-bottom:none}.expressive-code .frame.is-terminal .header::before{content:&apos;&apos;;position:absolute;pointer-events:none;left:var(--ec-uiPadInl);width:2.1rem;height:0.56rem;line-height:0;background-color:var(--ec-frm-trmTtbDotsFg);opacity:var(--ec-frm-trmTtbDotsOpa);-webkit-mask-image:var(--ec-frm-trmIcon);-webkit-mask-repeat:no-repeat;mask-image:var(--ec-frm-trmIcon);mask-repeat:no-repeat}.expressive-code .frame.is-terminal .header::after{content:&apos;&apos;;position:absolute;pointer-events:none;inset:0;border-bottom:var(--ec-brdWd) solid var(--ec-frm-trmTtbBrdBtmCol)}.expressive-code .frame pre{background:var(--code-background)}.expressive-code .copy{display:flex;gap:0.25rem;flex-direction:row;position:absolute;inset-block-start:calc(var(--ec-brdWd) + var(--button-spacing));inset-inline-end:calc(var(--ec-brdWd) + var(--ec-uiPadInl) / 2)}@media (scripting: none){.expressive-code .copy{display:none}}.expressive-code .copy{direction:ltr;unicode-bidi:isolate}.expressive-code .copy button{position:relative;align-self:flex-end;margin:0;padding:0;border:none;border-radius:0.2rem;z-index:1;cursor:pointer;transition-property:opacity, background, border-color;transition-duration:0.2s;transition-timing-function:cubic-bezier(0.25, 0.46, 0.45, 0.94);width:2.5rem;height:2.5rem;background:var(--code-background);opacity:0.75}.expressive-code .copy button div{position:absolute;inset:0;border-radius:inherit;background:var(--ec-frm-inlBtnBg);opacity:var(--ec-frm-inlBtnBgIdleOpa);transition-property:inherit;transition-duration:inherit;transition-timing-function:inherit}.expressive-code .copy button::before{content:&apos;&apos;;position:absolute;pointer-events:none;inset:0;border-radius:inherit;border:var(--ec-brdWd) solid var(--ec-frm-inlBtnBrd);opacity:var(--ec-frm-inlBtnBrdOpa)}.expressive-code .copy button::after{content:&apos;&apos;;position:absolute;pointer-events:none;inset:0;background-color:var(--ec-frm-inlBtnFg);-webkit-mask-image:var(--ec-frm-copyIcon);-webkit-mask-repeat:no-repeat;mask-image:var(--ec-frm-copyIcon);mask-repeat:no-repeat;margin:0.475rem;line-height:0}.expressive-code .copy button:hover,.expressive-code .copy button:focus:focus-visible{opacity:1}.expressive-code .copy button:hover div,.expressive-code .copy button:focus:focus-visible div{opacity:var(--ec-frm-inlBtnBgHoverOrFocusOpa)}.expressive-code .copy button:active{opacity:1}.expressive-code .copy button:active div{opacity:var(--ec-frm-inlBtnBgActOpa)}.expressive-code .copy .feedback{--tooltip-arrow-size:0.35rem;--tooltip-bg:var(--ec-frm-tooltipSuccessBg);color:var(--ec-frm-tooltipSuccessFg);pointer-events:none;user-select:none;-webkit-user-select:none;position:relative;align-self:center;background-color:var(--tooltip-bg);z-index:99;padding:0.125rem 0.75rem;border-radius:0.2rem;margin-inline-end:var(--tooltip-arrow-size);opacity:0;transition-property:opacity, transform;transition-duration:0.2s;transition-timing-function:ease-in-out;transform:translate3d(0, 0.25rem, 0)}.expressive-code .copy .feedback::after{content:&apos;&apos;;position:absolute;pointer-events:none;top:calc(50% - var(--tooltip-arrow-size));inset-inline-end:calc(-2 * (var(--tooltip-arrow-size) - 0.5px));border:var(--tooltip-arrow-size) solid transparent;border-inline-start-color:var(--tooltip-bg)}.expressive-code .copy .feedback.show{opacity:1;transform:translate3d(0, 0, 0)}@media (hover: hover){.expressive-code{}.expressive-code .copy button{opacity:0;width:2rem;height:2rem}.expressive-code .frame:hover .copy button:not(:hover),.expressive-code .frame:focus-within :focus-visible ~ .copy button:not(:hover),.expressive-code .frame .copy .feedback.show ~ button:not(:hover){opacity:0.75}}.expressive-code :nth-child(1 of .ec-line) .code{padding-inline-end:calc(2rem + var(--ec-codePadInl))}:root{--ec-brdRad:0.75rem;--ec-brdWd:1.5px;--ec-brdCol:var(--code-line);--ec-codeFontFml:var(--font-code);--ec-codeFontSize:0.875rem;--ec-codeFontWg:400;--ec-codeLineHt:1.75;--ec-codePadBlk:1rem;--ec-codePadInl:1.125rem;--ec-codeBg:var(--code-bg);--ec-codeFg:#e6edf3;--ec-codeSelBg:#264f78;--ec-gtrFg:#6e7681;--ec-gtrBrdCol:#6e768133;--ec-gtrBrdWd:1.5px;--ec-gtrHlFg:#e6edf3;--ec-uiFontFml:var(--font-mono);--ec-uiFontSize:0.75rem;--ec-uiFontWg:400;--ec-uiLineHt:1.65;--ec-uiPadBlk:0.25rem;--ec-uiPadInl:1rem;--ec-uiSelBg:#6e768166;--ec-uiSelFg:#e6edf3;--ec-focusBrd:#1f6feb;--ec-sbThumbCol:#8b949e33;--ec-sbThumbHoverCol:#8b949e3d;--ec-tm-lineMarkerAccentMarg:0rem;--ec-tm-lineMarkerAccentWd:0.15rem;--ec-tm-lineMarkerLabelPadInl:0.2rem;--ec-tm-lineMarkerLabelCol:white;--ec-tm-lineDiffIndMargLeft:0.3rem;--ec-tm-inlMarkerBrdWd:1.5px;--ec-tm-inlMarkerBrdRad:0.2rem;--ec-tm-inlMarkerPad:0.15rem;--ec-tm-insDiffIndContent:&apos;+&apos;;--ec-tm-delDiffIndContent:&apos;-&apos;;--ec-tm-markBg:#264a8980;--ec-tm-markBrdCol:#5570b3d0;--ec-tm-insBg:#26561c80;--ec-tm-insBrdCol:#4e7e41d0;--ec-tm-insDiffIndCol:#7eb070d0;--ec-tm-delBg:#81322b80;--ec-tm-delBrdCol:#ae594fd0;--ec-tm-delDiffIndCol:#e68a7ed0;--ec-frm-shdCol:#0000005b;--ec-frm-frameBoxShdCssVal:none;--ec-frm-edActTabBg:var(--code-bg);--ec-frm-edActTabFg:var(--code-muted);--ec-frm-edActTabBrdCol:transparent;--ec-frm-edActTabIndHt:1.5px;--ec-frm-edActTabIndTopCol:transparent;--ec-frm-edActTabIndBtmCol:#0d1117;--ec-frm-edTabsMargInlStart:0;--ec-frm-edTabsMargBlkStart:0;--ec-frm-edTabBrdRad:0.75rem;--ec-frm-edTabBarBg:var(--code-bg);--ec-frm-edTabBarBrdCol:var(--code-line);--ec-frm-edTabBarBrdBtmCol:var(--code-line);--ec-frm-edBg:var(--code-bg);--ec-frm-trmTtbFg:var(--code-muted);--ec-frm-trmTtbDotsFg:var(--code-muted);--ec-frm-trmTtbDotsOpa:0.15;--ec-frm-trmTtbBg:var(--code-bg);--ec-frm-trmTtbBrdBtmCol:var(--code-line);--ec-frm-trmBg:var(--code-bg);--ec-frm-inlBtnBg:var(--code-ink);--ec-frm-inlBtnBgIdleOpa:0;--ec-frm-inlBtnBgHoverOrFocusOpa:0.2;--ec-frm-inlBtnBgActOpa:0.3;--ec-frm-inlBtnFg:var(--code-ink);--ec-frm-inlBtnBrd:var(--code-line);--ec-frm-inlBtnBrdOpa:0.4;--ec-frm-tooltipSuccessBg:var(--color-emerald);--ec-frm-tooltipSuccessFg:var(--color-bg);--ec-frm-copyIcon:url(&quot;data:image/svg+xml,%3Csvg%20xmlns%3D&apos;http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg&apos;%20viewBox%3D&apos;0%200%2024%2024&apos;%20fill%3D&apos;none&apos;%20stroke%3D&apos;black&apos;%20stroke-width%3D&apos;1.75&apos;%3E%3Cpath%20d%3D&apos;M3%2019a2%202%200%200%201-1-2V2a2%202%200%200%201%201-1h13a2%202%200%200%201%202%201&apos;%2F%3E%3Crect%20x%3D&apos;6&apos;%20y%3D&apos;5&apos;%20width%3D&apos;16&apos;%20height%3D&apos;18&apos;%20rx%3D&apos;1.5&apos;%20ry%3D&apos;1.5&apos;%2F%3E%3C%2Fsvg%3E&quot;);--ec-frm-trmIcon:url(&quot;data:image/svg+xml,%3Csvg%20xmlns%3D&apos;http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg&apos;%20viewBox%3D&apos;0%200%2060%2016&apos;%20preserveAspectRatio%3D&apos;xMidYMid%20meet&apos;%3E%3Ccircle%20cx%3D&apos;8&apos;%20cy%3D&apos;8&apos;%20r%3D&apos;8&apos;%2F%3E%3Ccircle%20cx%3D&apos;30&apos;%20cy%3D&apos;8&apos;%20r%3D&apos;8&apos;%2F%3E%3Ccircle%20cx%3D&apos;52&apos;%20cy%3D&apos;8&apos;%20r%3D&apos;8&apos;%2F%3E%3C%2Fsvg%3E&quot;)}.expressive-code .ec-line :where(span[style^=&apos;--&apos;]:not([class])){color:var(--0, inherit);background-color:var(--0bg, transparent);font-style:var(--0fs, inherit);font-weight:var(--0fw, inherit);text-decoration:var(--0td, inherit)}&lt;/style&gt;&lt;script type=&quot;module&quot; src=&quot;/_astro/ec.0vx5m.js&quot;&gt;&lt;/script&gt;&lt;figure class=&quot;frame has-title&quot;&gt;&lt;figcaption class=&quot;header&quot;&gt;&lt;span class=&quot;title&quot;&gt;TypeScript&lt;/span&gt;&lt;/figcaption&gt;&lt;pre data-language=&quot;typescript&quot;&gt;&lt;code&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span style=&quot;--0:#8B949E&quot;&gt;// An example of a simple hash function that converts a string key into an array index&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;function&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; &lt;/span&gt;&lt;span style=&quot;--0:#D2A8FF&quot;&gt;simpleHash&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;(&lt;/span&gt;&lt;span style=&quot;--0:#FFA657&quot;&gt;key&lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;:&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; &lt;/span&gt;&lt;span style=&quot;--0:#79C0FF&quot;&gt;string&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;, &lt;/span&gt;&lt;span style=&quot;--0:#FFA657&quot;&gt;arraySize&lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;:&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; &lt;/span&gt;&lt;span style=&quot;--0:#79C0FF&quot;&gt;number&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;)&lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;:&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; &lt;/span&gt;&lt;span style=&quot;--0:#79C0FF&quot;&gt;number&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; {&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span class=&quot;indent&quot;&gt;    &lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;let&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; hash &lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;=&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; &lt;/span&gt;&lt;span style=&quot;--0:#79C0FF&quot;&gt;0&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;;&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span class=&quot;indent&quot;&gt;    &lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;for&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; (&lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;let&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; i &lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;=&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; &lt;/span&gt;&lt;span style=&quot;--0:#79C0FF&quot;&gt;0&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;; i &lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;&amp;#x3C;&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; key.&lt;/span&gt;&lt;span style=&quot;--0:#79C0FF&quot;&gt;length&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;; i&lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;++&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;) {&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span class=&quot;indent&quot;&gt;        &lt;/span&gt;&lt;span style=&quot;--0:#8B949E&quot;&gt;// Performing mathematical calculations using the ASCII code of each character&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span class=&quot;indent&quot;&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;        &lt;/span&gt;&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;hash &lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;=&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; (hash &lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;+&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; key.&lt;/span&gt;&lt;span style=&quot;--0:#D2A8FF&quot;&gt;charCodeAt&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;(i) &lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;*&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; &lt;/span&gt;&lt;span style=&quot;--0:#79C0FF&quot;&gt;31&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;) &lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;%&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; arraySize;&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span class=&quot;indent&quot;&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;    &lt;/span&gt;&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;}&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span class=&quot;indent&quot;&gt;    &lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;return&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; hash;&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;}&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;
&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;const&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; &lt;/span&gt;&lt;span style=&quot;--0:#79C0FF&quot;&gt;tableSize&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; &lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;=&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; &lt;/span&gt;&lt;span style=&quot;--0:#79C0FF&quot;&gt;100&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;;&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;const&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; &lt;/span&gt;&lt;span style=&quot;--0:#79C0FF&quot;&gt;index&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; &lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;=&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; &lt;/span&gt;&lt;span style=&quot;--0:#D2A8FF&quot;&gt;simpleHash&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;(&lt;/span&gt;&lt;span style=&quot;--0:#A5D6FF&quot;&gt;&quot;user_profile_dhaka&quot;&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;, tableSize);&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;console.&lt;/span&gt;&lt;span style=&quot;--0:#D2A8FF&quot;&gt;log&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;(&lt;/span&gt;&lt;span style=&quot;--0:#A5D6FF&quot;&gt;`Data will be stored at index: ${&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;index&lt;/span&gt;&lt;span style=&quot;--0:#A5D6FF&quot;&gt;}`&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;);&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;/code&gt;&lt;/pre&gt;&lt;div class=&quot;copy&quot;&gt;&lt;div aria-live=&quot;polite&quot;&gt;&lt;/div&gt;&lt;button title=&quot;Copy to clipboard&quot; data-copied=&quot;Copied!&quot; data-code=&quot;// An example of a simple hash function that converts a string key into an array indexfunction simpleHash(key: string, arraySize: number): number {    let hash = 0;    for (let i = 0; i &lt; key.length; i++) {        // Performing mathematical calculations using the ASCII code of each character        hash = (hash + key.charCodeAt(i) * 31) % arraySize;    }    return hash;}const tableSize = 100;const index = simpleHash(&amp;#x22;user_profile_dhaka&amp;#x22;, tableSize);console.log(&amp;#x60;Data will be stored at index: ${index}&amp;#x60;);&quot;&gt;&lt;div&gt;&lt;/div&gt;&lt;/button&gt;&lt;/div&gt;&lt;/figure&gt;&lt;/div&gt;
&lt;p&gt;However, this brilliant system introduces a major engineering challenge known as a hash collision. Because our system memory and array slots are finite, but the potential number of input keys is infinite, two completely different keys will occasionally generate the exact same memory index. For example, if running the hash calculation on the words &quot;dhaka&quot; and &quot;sylhet&quot; both result in slot number 15, a hash collision occurs. If your system architecture does not handle these collisions with clean logic, you risk system crashes or permanent data loss.&lt;/p&gt;
&lt;p&gt;In software architecture, engineers rely on two highly popular and effective techniques to resolve hash collisions:&lt;/p&gt;
&lt;ol&gt;
&lt;li&gt;&lt;strong&gt;Chaining:&lt;/strong&gt; In this approach, instead of storing a single data value directly inside each memory slot of the hash table, the slot holds the head of a linked list. Whenever a collision occurs and multiple keys map to the exact same index, the system simply attaches the new data as a new node in that slot&apos;s linked list. During a lookup, the hash function locates the correct index first, and then the system runs a brief loop through that tiny linked list to find the exact target data.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Open Addressing:&lt;/strong&gt; This method avoids using linked lists entirely. When the system tries to place new data into a memory slot and discovers that the slot is already occupied, it automatically begins searching for the very next empty slot. To find an open space, it uses techniques like linear probing, which checks slots sequentially one by one, or quadratic probing, which uses mathematical jumps to find empty slots. The new data is then placed into the first empty slot the system discovers.&lt;/li&gt;
&lt;/ol&gt;
&lt;hr&gt;
&lt;h2 id=&quot;non-linear-structures-the-real-power-of-scaling&quot;&gt;Non-Linear Structures (The Real Power of Scaling)&lt;/h2&gt;
&lt;p&gt;So far, every data structure we have discussed, including arrays, linked lists, stacks, and queues, falls under the category of linear data structures. In a linear structure, data items sit in a straight, sequential line. However, many complex real-world problems and massive datasets cannot be modeled efficiently in a simple straight line. When our systems require hierarchical relationships where data elements sit beneath other data elements, we must step into the world of non-linear data structures. The two most important and powerful pillars of this world are trees and graphs.&lt;/p&gt;
&lt;p&gt;Trees, and specifically binary search trees, provide an architecture that organizes data in a clear hierarchy. A great analogy for a tree is a corporate organizational chart or a family tree. In a corporate organogram, the Chief Executive Officer sits at the top, directing several vice presidents, who supervise managers, who guide the engineering teams below them. A tree data structure operates in this exact hierarchical format, where the top element is called the root node, and the branching elements below it are called child nodes.&lt;/p&gt;
&lt;p&gt;Why do modern relational databases and operating system file systems rely on trees instead of simple arrays? The primary reason is incredible search speed. A binary search tree follows a strict rule: any node placed in the left branch must contain a smaller value, and any node placed in the right branch must contain a larger value. When you search for a specific item, you can determine with absolute certainty at every step whether your target lies to the left or to the right. This simple logic cuts the remaining search space in half with every step, giving us logarithmic time complexity.&lt;/p&gt;
&lt;p&gt;&lt;img src=&quot;https://raw.githubusercontent.com/rafeuddaraj/rafes-blog-assets/refs/heads/the-complete-engineering-handbook-data-structures-and-algorithms-for-production-scalability/assets/bst-vs-linear-search.svg&quot; alt=&quot;Binary Search Tree O(log n) vs Linear Search O(n) - Search Performance Comparison for Production Databases&quot; loading=&quot;lazy&quot; decoding=&quot;async&quot; width=&quot;800&quot; height=&quot;450&quot;&gt;
In an array of ten million records, a linear search might require ten million loop iterations to find an item located at the very end. In contrast, using a balanced binary search tree, finding any piece of data among those same ten million records requires at most twenty-four to thirty steps. In a production environment, this massive performance difference dictates whether your API responds in milliseconds or crashes from request timeouts.&lt;/p&gt;
&lt;p&gt;When we move beyond trees to tackle even more complex, real-world networking logic, we need the graph data structure. A tree is actually just a specialized version of a graph that has a defined root and contains no closed loops or cycles. A graph has no such limitations. A graph consists of two main components: nodes, also called vertices, which represent objects or locations, and edges, which represent the relationship or connection paths between those nodes.&lt;/p&gt;
&lt;p&gt;Graphs appear everywhere in real-world software engineering. For example, social media friend networks on platforms like Facebook or LinkedIn are massive graphs. Every user is a node, and a friendship connection between two users represents an edge. When the system calculates mutual friends or suggests connections, graph traversal algorithms run in the backend. Similarly, ride-sharing applications and mapping platforms like Google Maps or Uber store entire city road networks in memory as graphs. Street intersections act as nodes, and the roads connecting them act as edges. To calculate the shortest and fastest route between two locations, these systems use specialized graph algorithms like Dijkstra or A-star. Even internet data routing protocols rely entirely on graph architectures to move data packets across the globe efficiently.&lt;/p&gt;
&lt;hr&gt;
&lt;h2 id=&quot;core-algorithmic-techniques-and-paradigms&quot;&gt;Core Algorithmic Techniques and Paradigms&lt;/h2&gt;
&lt;p&gt;Once we have organized our data cleanly in memory, our next step is executing various operations and logical tasks on that data. To do this effectively, we need to master a core set of algorithmic techniques and problem-solving paradigms. In daily software engineering, the two most common computational tasks we face are searching and sorting.&lt;/p&gt;
&lt;p&gt;We have already seen that linear search is a slow approach where a loop checks items one by one, resulting in linear time complexity. However, if your dataset is already sorted in ascending order, you can use binary search. This powerful algorithm compares your target value with the middle item of the dataset and eliminates half of the remaining items in a single bound. This allows you to find any data point in logarithmic time.&lt;/p&gt;
&lt;p&gt;Now let us examine sorting. Keeping data sorted is essential in production systems because binary search and ultra-fast database queries are impossible without sorted data. While simple sorting algorithms work fine for small lists, sorting millions of database records requires advanced algorithms. The two most widely used production sorting algorithms are QuickSort and MergeSort.&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;QuickSort:&lt;/strong&gt; This is a divide-and-conquer algorithm. It selects a specific item from the dataset to act as a pivot, and then shifts all smaller values to the left of the pivot and all larger values to the right. It then recursively sorts the left and right sections using the same method. Its average time complexity is O(n log n), and it uses very little additional memory space. However, if the data is already sorted in reverse order and the algorithm chooses a poor pivot, its worst-case performance can drop to quadratic time.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;MergeSort:&lt;/strong&gt; This algorithm also relies on the divide-and-conquer paradigm. It continually cuts the entire dataset in half until each smaller subsection contains only a single item. It then merges those individual items back together in sequential order to produce a fully sorted list. Its biggest advantage is reliability: regardless of how messy the initial data is, MergeSort is guaranteed to complete its work in O(n log n) time. The trade-off is space complexity; merging the lists requires allocating additional memory space equal to O(n).&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;How should we think when facing a new or complex engineering problem? In software architecture, we generally rely on three major problem-solving paradigms:&lt;/p&gt;
&lt;ol&gt;
&lt;li&gt;&lt;strong&gt;Brute Force:&lt;/strong&gt; This is the most straightforward problem-solving approach, without any clever optimizations. Using brute force, your code checks every single possible solution or path one by one until it finds the correct answer. While this approach is easy to code and guaranteed to find the right answer, it is extremely slow in production systems, often resulting in time complexities of O(n^2) or even exponential time, O(2^n).&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Greedy Algorithm:&lt;/strong&gt; With this mindset, the algorithm makes whatever decision looks best and most profitable at the exact current moment, without considering future consequences or the big picture. It chooses a locally optimal step at each stage with the hope of reaching a globally optimal solution. For example, when routing network packets at the lowest cost, choosing the shortest available path at every single router junction follows greedy logic. While this approach executes very quickly, it does not guarantee a one-hundred-percent optimal solution for every type of problem.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Dynamic Programming:&lt;/strong&gt; This is a highly sophisticated and intelligent engineering paradigm. When you can break a massive, complex problem down into many smaller, overlapping subproblems, dynamic programming is the right tool for the job. Its core philosophy is simple: never repeat a calculation you have already completed. The system solves the smaller problems once and stores those answers inside a memory map or array, a technique known as memoization or caching. When the algorithm encounters the exact same calculation later, it bypasses processing and reads the result directly from memory. Because of this caching mechanism, problems that would take brute force thousands of years to solve can be resolved in just a few seconds using dynamic programming.&lt;/li&gt;
&lt;/ol&gt;
&lt;hr&gt;
&lt;h2 id=&quot;production-engineering-and-real-world-use-cases&quot;&gt;Production Engineering and Real-World Use Cases&lt;/h2&gt;
&lt;p&gt;After covering the theoretical foundations, let us see how we apply this knowledge of data structures and algorithms directly to daily production engineering and real-world systems. We will examine two vital production use cases in detail: database indexing and caching architecture.&lt;/p&gt;
&lt;p&gt;First, let us discuss database indexing. When you work with a relational database like MySQL or PostgreSQL storing millions of user records, how does a query like &lt;code&gt;SELECT * FROM users WHERE email = &apos;example@test.com&apos;&lt;/code&gt; return an answer in just a few milliseconds? If you have not created an index on the email column, the database engine must read every single record from the hard disk or solid-state drive into memory one by one to check for a match. This is called a full table scan. If high traffic hits your system while the database performs full table scans across ten million records, your server processor and memory will overload instantly, causing the database to crash.&lt;/p&gt;
&lt;p&gt;To resolve this bottleneck, database engines use specialized balanced tree structures known as B-Trees and B+ Trees. When you create an index on a specific column, the database organizes that data into a B+ Tree and stores it in a dedicated space in memory or on disk. The defining feature of a B+ Tree is that every single node can hold multiple data values and many child pointers, which keeps the overall height of the tree extremely low. As a result, finding a specific record among tens of millions of entries requires the database to execute only three or four disk read operations, guaranteeing logarithmic performance.&lt;/p&gt;
&lt;p&gt;Our second production use case is caching architecture. In any high-traffic, scalable system, we use caching layers like Redis or Memcached to reduce the database load and serve instant responses to users. However, memory space in RAM is extremely limited and expensive. Therefore, we must design a smart caching architecture that retains the most frequently needed data in memory while automatically removing old or unused items when memory fills up. The industry-standard algorithm for this requirement is the Least Recently Used cache, commonly known as an LRU Cache.&lt;/p&gt;
&lt;p&gt;To build a production-grade LRU cache, we need an architecture where two specific operations occur in constant time:&lt;/p&gt;
&lt;ol&gt;
&lt;li&gt;Looking up data using any key.&lt;/li&gt;
&lt;li&gt;Updating memory during data insertion or when removing old items.&lt;/li&gt;
&lt;/ol&gt;
&lt;p&gt;Using only an array or only a linked list cannot achieve this. Instead, software architects combine two distinct structures: a hash map and a doubly linked list. The hash map guarantees constant time data lookups, while the doubly linked list allows us to add or remove nodes from any position in constant time without shifting data.&lt;/p&gt;
&lt;figure&gt;&lt;img src=&quot;https://raw.githubusercontent.com/rafeuddaraj/rafes-blog-assets/refs/heads/the-complete-engineering-handbook-data-structures-and-algorithms-for-production-scalability/assets/lru-cache-architecture.svg&quot; alt=&quot;LRU Cache Architecture - Hash Map and Doubly Linked List Combination for O(1) Lookup and Eviction&quot; loading=&quot;lazy&quot; decoding=&quot;async&quot; width=&quot;800&quot; height=&quot;450&quot;&gt;&lt;figcaption&gt;LRU Cache Architecture - Hash Map and Doubly Linked List Combination for O(1) Lookup and Eviction&lt;/figcaption&gt;&lt;/figure&gt;
&lt;p&gt;Consider the architecture involved here. Each key in the hash map points directly to the memory address of a specific node inside the doubly linked list. Whenever an item is read or written, the system moves that node to the very front of the doubly linked list, marking it as the most recently used item. When the cache hits its maximum capacity, the system targets the node sitting at the very end of the list, marking it as the least recently used item, and removes it from memory in constant time.&lt;/p&gt;
&lt;p&gt;Here is a production-ready, fully type-safe TypeScript implementation that combines a hash map and a doubly linked list to create a functioning LRU cache:&lt;/p&gt;
&lt;div class=&quot;expressive-code&quot;&gt;&lt;figure class=&quot;frame has-title&quot;&gt;&lt;figcaption class=&quot;header&quot;&gt;&lt;span class=&quot;title&quot;&gt;TypeScript&lt;/span&gt;&lt;/figcaption&gt;&lt;pre data-language=&quot;typescript&quot;&gt;&lt;code&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span style=&quot;--0:#8B949E&quot;&gt;// Architecture of each node in the doubly linked list&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;class&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; &lt;/span&gt;&lt;span style=&quot;--0:#FFA657&quot;&gt;CacheNode&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;&amp;#x3C;&lt;/span&gt;&lt;span style=&quot;--0:#FFA657&quot;&gt;K&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;, &lt;/span&gt;&lt;span style=&quot;--0:#FFA657&quot;&gt;V&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;&gt; {&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span class=&quot;indent&quot;&gt;    &lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;public&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; &lt;/span&gt;&lt;span style=&quot;--0:#FFA657&quot;&gt;key&lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;:&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; &lt;/span&gt;&lt;span style=&quot;--0:#FFA657&quot;&gt;K&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;;&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span class=&quot;indent&quot;&gt;    &lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;public&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; &lt;/span&gt;&lt;span style=&quot;--0:#FFA657&quot;&gt;value&lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;:&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; &lt;/span&gt;&lt;span style=&quot;--0:#FFA657&quot;&gt;V&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;;&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span class=&quot;indent&quot;&gt;    &lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;public&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; &lt;/span&gt;&lt;span style=&quot;--0:#FFA657&quot;&gt;prev&lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;:&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; &lt;/span&gt;&lt;span style=&quot;--0:#FFA657&quot;&gt;CacheNode&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;&amp;#x3C;&lt;/span&gt;&lt;span style=&quot;--0:#FFA657&quot;&gt;K&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;, &lt;/span&gt;&lt;span style=&quot;--0:#FFA657&quot;&gt;V&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;&gt; &lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;|&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; &lt;/span&gt;&lt;span style=&quot;--0:#79C0FF&quot;&gt;null&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; &lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;=&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; &lt;/span&gt;&lt;span style=&quot;--0:#79C0FF&quot;&gt;null&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;;&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span class=&quot;indent&quot;&gt;    &lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;public&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; &lt;/span&gt;&lt;span style=&quot;--0:#FFA657&quot;&gt;next&lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;:&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; &lt;/span&gt;&lt;span style=&quot;--0:#FFA657&quot;&gt;CacheNode&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;&amp;#x3C;&lt;/span&gt;&lt;span style=&quot;--0:#FFA657&quot;&gt;K&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;, &lt;/span&gt;&lt;span style=&quot;--0:#FFA657&quot;&gt;V&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;&gt; &lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;|&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; &lt;/span&gt;&lt;span style=&quot;--0:#79C0FF&quot;&gt;null&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; &lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;=&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; &lt;/span&gt;&lt;span style=&quot;--0:#79C0FF&quot;&gt;null&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;;&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;
&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span class=&quot;indent&quot;&gt;    &lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;constructor&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;(&lt;/span&gt;&lt;span style=&quot;--0:#FFA657&quot;&gt;key&lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;:&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; &lt;/span&gt;&lt;span style=&quot;--0:#FFA657&quot;&gt;K&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;, &lt;/span&gt;&lt;span style=&quot;--0:#FFA657&quot;&gt;value&lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;:&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; &lt;/span&gt;&lt;span style=&quot;--0:#FFA657&quot;&gt;V&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;) {&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span class=&quot;indent&quot;&gt;        &lt;/span&gt;&lt;span style=&quot;--0:#79C0FF&quot;&gt;this&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;.key &lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;=&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; key;&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span class=&quot;indent&quot;&gt;        &lt;/span&gt;&lt;span style=&quot;--0:#79C0FF&quot;&gt;this&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;.value &lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;=&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; value;&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span class=&quot;indent&quot;&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;    &lt;/span&gt;&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;}&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;}&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;
&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span style=&quot;--0:#8B949E&quot;&gt;// Complete LRU Cache implementation&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;export&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; &lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;class&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; &lt;/span&gt;&lt;span style=&quot;--0:#FFA657&quot;&gt;LRUCache&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;&amp;#x3C;&lt;/span&gt;&lt;span style=&quot;--0:#FFA657&quot;&gt;K&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;, &lt;/span&gt;&lt;span style=&quot;--0:#FFA657&quot;&gt;V&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;&gt; {&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span class=&quot;indent&quot;&gt;    &lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;private&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; &lt;/span&gt;&lt;span style=&quot;--0:#FFA657&quot;&gt;capacity&lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;:&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; &lt;/span&gt;&lt;span style=&quot;--0:#79C0FF&quot;&gt;number&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;;&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span class=&quot;indent&quot;&gt;    &lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;private&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; &lt;/span&gt;&lt;span style=&quot;--0:#FFA657&quot;&gt;cacheMap&lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;:&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; &lt;/span&gt;&lt;span style=&quot;--0:#FFA657&quot;&gt;Map&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;&amp;#x3C;&lt;/span&gt;&lt;span style=&quot;--0:#FFA657&quot;&gt;K&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;, &lt;/span&gt;&lt;span style=&quot;--0:#FFA657&quot;&gt;CacheNode&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;&amp;#x3C;&lt;/span&gt;&lt;span style=&quot;--0:#FFA657&quot;&gt;K&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;, &lt;/span&gt;&lt;span style=&quot;--0:#FFA657&quot;&gt;V&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;&gt;&gt;;&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span class=&quot;indent&quot;&gt;    &lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;private&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; &lt;/span&gt;&lt;span style=&quot;--0:#FFA657&quot;&gt;head&lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;:&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; &lt;/span&gt;&lt;span style=&quot;--0:#FFA657&quot;&gt;CacheNode&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;&amp;#x3C;&lt;/span&gt;&lt;span style=&quot;--0:#FFA657&quot;&gt;K&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;, &lt;/span&gt;&lt;span style=&quot;--0:#FFA657&quot;&gt;V&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;&gt;;&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span class=&quot;indent&quot;&gt;    &lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;private&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; &lt;/span&gt;&lt;span style=&quot;--0:#FFA657&quot;&gt;tail&lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;:&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; &lt;/span&gt;&lt;span style=&quot;--0:#FFA657&quot;&gt;CacheNode&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;&amp;#x3C;&lt;/span&gt;&lt;span style=&quot;--0:#FFA657&quot;&gt;K&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;, &lt;/span&gt;&lt;span style=&quot;--0:#FFA657&quot;&gt;V&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;&gt;;&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;
&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span class=&quot;indent&quot;&gt;    &lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;constructor&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;(&lt;/span&gt;&lt;span style=&quot;--0:#FFA657&quot;&gt;capacity&lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;:&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; &lt;/span&gt;&lt;span style=&quot;--0:#79C0FF&quot;&gt;number&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;) {&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span class=&quot;indent&quot;&gt;        &lt;/span&gt;&lt;span style=&quot;--0:#79C0FF&quot;&gt;this&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;.capacity &lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;=&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; capacity;&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span class=&quot;indent&quot;&gt;        &lt;/span&gt;&lt;span style=&quot;--0:#79C0FF&quot;&gt;this&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;.cacheMap &lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;=&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; &lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;new&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; &lt;/span&gt;&lt;span style=&quot;--0:#D2A8FF&quot;&gt;Map&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;();&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;
&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span class=&quot;indent&quot;&gt;        &lt;/span&gt;&lt;span style=&quot;--0:#8B949E&quot;&gt;// Creating dummy head and tail nodes to make edge case handling easier&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span class=&quot;indent&quot;&gt;        &lt;/span&gt;&lt;span style=&quot;--0:#79C0FF&quot;&gt;this&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;.head &lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;=&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; &lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;new&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; &lt;/span&gt;&lt;span style=&quot;--0:#D2A8FF&quot;&gt;CacheNode&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;&amp;#x3C;&lt;/span&gt;&lt;span style=&quot;--0:#FFA657&quot;&gt;K&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;, &lt;/span&gt;&lt;span style=&quot;--0:#FFA657&quot;&gt;V&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;&gt;({} &lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;as&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; &lt;/span&gt;&lt;span style=&quot;--0:#FFA657&quot;&gt;K&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;, {} &lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;as&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; &lt;/span&gt;&lt;span style=&quot;--0:#FFA657&quot;&gt;V&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;);&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span class=&quot;indent&quot;&gt;        &lt;/span&gt;&lt;span style=&quot;--0:#79C0FF&quot;&gt;this&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;.tail &lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;=&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; &lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;new&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; &lt;/span&gt;&lt;span style=&quot;--0:#D2A8FF&quot;&gt;CacheNode&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;&amp;#x3C;&lt;/span&gt;&lt;span style=&quot;--0:#FFA657&quot;&gt;K&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;, &lt;/span&gt;&lt;span style=&quot;--0:#FFA657&quot;&gt;V&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;&gt;({} &lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;as&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; &lt;/span&gt;&lt;span style=&quot;--0:#FFA657&quot;&gt;K&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;, {} &lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;as&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; &lt;/span&gt;&lt;span style=&quot;--0:#FFA657&quot;&gt;V&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;);&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span class=&quot;indent&quot;&gt;        &lt;/span&gt;&lt;span style=&quot;--0:#79C0FF&quot;&gt;this&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;.head.next &lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;=&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; &lt;/span&gt;&lt;span style=&quot;--0:#79C0FF&quot;&gt;this&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;.tail;&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span class=&quot;indent&quot;&gt;        &lt;/span&gt;&lt;span style=&quot;--0:#79C0FF&quot;&gt;this&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;.tail.prev &lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;=&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; &lt;/span&gt;&lt;span style=&quot;--0:#79C0FF&quot;&gt;this&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;.head;&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span class=&quot;indent&quot;&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;    &lt;/span&gt;&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;}&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;
&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span class=&quot;indent&quot;&gt;    &lt;/span&gt;&lt;span style=&quot;--0:#8B949E&quot;&gt;// Constant time logic to disconnect any node from the linked list&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span class=&quot;indent&quot;&gt;    &lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;private&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; &lt;/span&gt;&lt;span style=&quot;--0:#D2A8FF&quot;&gt;removeNode&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;(&lt;/span&gt;&lt;span style=&quot;--0:#FFA657&quot;&gt;node&lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;:&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; &lt;/span&gt;&lt;span style=&quot;--0:#FFA657&quot;&gt;CacheNode&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;&amp;#x3C;&lt;/span&gt;&lt;span style=&quot;--0:#FFA657&quot;&gt;K&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;, &lt;/span&gt;&lt;span style=&quot;--0:#FFA657&quot;&gt;V&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;&gt;)&lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;:&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; &lt;/span&gt;&lt;span style=&quot;--0:#79C0FF&quot;&gt;void&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; {&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span class=&quot;indent&quot;&gt;        &lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;const&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; &lt;/span&gt;&lt;span style=&quot;--0:#79C0FF&quot;&gt;prevNode&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; &lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;=&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; node.prev;&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span class=&quot;indent&quot;&gt;        &lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;const&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; &lt;/span&gt;&lt;span style=&quot;--0:#79C0FF&quot;&gt;nextNode&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; &lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;=&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; node.next;&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;
&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span class=&quot;indent&quot;&gt;        &lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;if&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; (prevNode &lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;&amp;#x26;&amp;#x26;&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; nextNode) {&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span class=&quot;indent&quot;&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;            &lt;/span&gt;&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;prevNode.next &lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;=&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; nextNode;&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span class=&quot;indent&quot;&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;            &lt;/span&gt;&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;nextNode.prev &lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;=&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; prevNode;&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span class=&quot;indent&quot;&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;        &lt;/span&gt;&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;}&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span class=&quot;indent&quot;&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;    &lt;/span&gt;&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;}&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;
&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span class=&quot;indent&quot;&gt;    &lt;/span&gt;&lt;span style=&quot;--0:#8B949E&quot;&gt;// Constant time logic to add any node right after the head&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span class=&quot;indent&quot;&gt;    &lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;private&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; &lt;/span&gt;&lt;span style=&quot;--0:#D2A8FF&quot;&gt;addToHead&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;(&lt;/span&gt;&lt;span style=&quot;--0:#FFA657&quot;&gt;node&lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;:&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; &lt;/span&gt;&lt;span style=&quot;--0:#FFA657&quot;&gt;CacheNode&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;&amp;#x3C;&lt;/span&gt;&lt;span style=&quot;--0:#FFA657&quot;&gt;K&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;, &lt;/span&gt;&lt;span style=&quot;--0:#FFA657&quot;&gt;V&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;&gt;)&lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;:&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; &lt;/span&gt;&lt;span style=&quot;--0:#79C0FF&quot;&gt;void&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; {&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span class=&quot;indent&quot;&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;        &lt;/span&gt;&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;node.prev &lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;=&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; &lt;/span&gt;&lt;span style=&quot;--0:#79C0FF&quot;&gt;this&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;.head;&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span class=&quot;indent&quot;&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;        &lt;/span&gt;&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;node.next &lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;=&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; &lt;/span&gt;&lt;span style=&quot;--0:#79C0FF&quot;&gt;this&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;.head.next;&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;
&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span class=&quot;indent&quot;&gt;        &lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;if&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; (&lt;/span&gt;&lt;span style=&quot;--0:#79C0FF&quot;&gt;this&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;.head.next) {&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span class=&quot;indent&quot;&gt;            &lt;/span&gt;&lt;span style=&quot;--0:#79C0FF&quot;&gt;this&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;.head.next.prev &lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;=&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; node;&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span class=&quot;indent&quot;&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;        &lt;/span&gt;&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;}&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span class=&quot;indent&quot;&gt;        &lt;/span&gt;&lt;span style=&quot;--0:#79C0FF&quot;&gt;this&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;.head.next &lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;=&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; node;&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span class=&quot;indent&quot;&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;    &lt;/span&gt;&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;}&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;
&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span class=&quot;indent&quot;&gt;    &lt;/span&gt;&lt;span style=&quot;--0:#8B949E&quot;&gt;// Constant time read method&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span class=&quot;indent&quot;&gt;    &lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;public&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; &lt;/span&gt;&lt;span style=&quot;--0:#D2A8FF&quot;&gt;get&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;(&lt;/span&gt;&lt;span style=&quot;--0:#FFA657&quot;&gt;key&lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;:&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; &lt;/span&gt;&lt;span style=&quot;--0:#FFA657&quot;&gt;K&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;)&lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;:&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; &lt;/span&gt;&lt;span style=&quot;--0:#FFA657&quot;&gt;V&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; &lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;|&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; &lt;/span&gt;&lt;span style=&quot;--0:#79C0FF&quot;&gt;null&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; {&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span class=&quot;indent&quot;&gt;        &lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;if&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; (&lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;!&lt;/span&gt;&lt;span style=&quot;--0:#79C0FF&quot;&gt;this&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;.cacheMap.&lt;/span&gt;&lt;span style=&quot;--0:#D2A8FF&quot;&gt;has&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;(key)) {&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span class=&quot;indent&quot;&gt;            &lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;return&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; &lt;/span&gt;&lt;span style=&quot;--0:#79C0FF&quot;&gt;null&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;;&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span class=&quot;indent&quot;&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;        &lt;/span&gt;&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;}&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;
&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span class=&quot;indent&quot;&gt;        &lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;const&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; &lt;/span&gt;&lt;span style=&quot;--0:#79C0FF&quot;&gt;node&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; &lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;=&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; &lt;/span&gt;&lt;span style=&quot;--0:#79C0FF&quot;&gt;this&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;.cacheMap.&lt;/span&gt;&lt;span style=&quot;--0:#D2A8FF&quot;&gt;get&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;(key)&lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;!&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;;&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span class=&quot;indent&quot;&gt;        &lt;/span&gt;&lt;span style=&quot;--0:#8B949E&quot;&gt;// Since this data was just accessed, move it to the head&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span class=&quot;indent&quot;&gt;        &lt;/span&gt;&lt;span style=&quot;--0:#79C0FF&quot;&gt;this&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;.&lt;/span&gt;&lt;span style=&quot;--0:#D2A8FF&quot;&gt;removeNode&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;(node);&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span class=&quot;indent&quot;&gt;        &lt;/span&gt;&lt;span style=&quot;--0:#79C0FF&quot;&gt;this&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;.&lt;/span&gt;&lt;span style=&quot;--0:#D2A8FF&quot;&gt;addToHead&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;(node);&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;
&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span class=&quot;indent&quot;&gt;        &lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;return&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; node.value;&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span class=&quot;indent&quot;&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;    &lt;/span&gt;&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;}&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;
&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span class=&quot;indent&quot;&gt;    &lt;/span&gt;&lt;span style=&quot;--0:#8B949E&quot;&gt;// Constant time write method&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span class=&quot;indent&quot;&gt;    &lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;public&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; &lt;/span&gt;&lt;span style=&quot;--0:#D2A8FF&quot;&gt;put&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;(&lt;/span&gt;&lt;span style=&quot;--0:#FFA657&quot;&gt;key&lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;:&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; &lt;/span&gt;&lt;span style=&quot;--0:#FFA657&quot;&gt;K&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;, &lt;/span&gt;&lt;span style=&quot;--0:#FFA657&quot;&gt;value&lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;:&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; &lt;/span&gt;&lt;span style=&quot;--0:#FFA657&quot;&gt;V&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;)&lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;:&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; &lt;/span&gt;&lt;span style=&quot;--0:#79C0FF&quot;&gt;void&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; {&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span class=&quot;indent&quot;&gt;        &lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;if&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; (&lt;/span&gt;&lt;span style=&quot;--0:#79C0FF&quot;&gt;this&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;.cacheMap.&lt;/span&gt;&lt;span style=&quot;--0:#D2A8FF&quot;&gt;has&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;(key)) {&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span class=&quot;indent&quot;&gt;            &lt;/span&gt;&lt;span style=&quot;--0:#8B949E&quot;&gt;// If data already exists, update its value and move it to the head&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span class=&quot;indent&quot;&gt;            &lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;const&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; &lt;/span&gt;&lt;span style=&quot;--0:#79C0FF&quot;&gt;existingNode&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; &lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;=&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; &lt;/span&gt;&lt;span style=&quot;--0:#79C0FF&quot;&gt;this&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;.cacheMap.&lt;/span&gt;&lt;span style=&quot;--0:#D2A8FF&quot;&gt;get&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;(key)&lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;!&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;;&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span class=&quot;indent&quot;&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;            &lt;/span&gt;&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;existingNode.value &lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;=&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; value;&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span class=&quot;indent&quot;&gt;            &lt;/span&gt;&lt;span style=&quot;--0:#79C0FF&quot;&gt;this&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;.&lt;/span&gt;&lt;span style=&quot;--0:#D2A8FF&quot;&gt;removeNode&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;(existingNode);&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span class=&quot;indent&quot;&gt;            &lt;/span&gt;&lt;span style=&quot;--0:#79C0FF&quot;&gt;this&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;.&lt;/span&gt;&lt;span style=&quot;--0:#D2A8FF&quot;&gt;addToHead&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;(existingNode);&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span class=&quot;indent&quot;&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;        &lt;/span&gt;&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;} &lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;else&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; {&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span class=&quot;indent&quot;&gt;            &lt;/span&gt;&lt;span style=&quot;--0:#8B949E&quot;&gt;// Creating a new node for new data&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span class=&quot;indent&quot;&gt;            &lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;const&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; &lt;/span&gt;&lt;span style=&quot;--0:#79C0FF&quot;&gt;newNode&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; &lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;=&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; &lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;new&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; &lt;/span&gt;&lt;span style=&quot;--0:#D2A8FF&quot;&gt;CacheNode&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;(key, value);&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span class=&quot;indent&quot;&gt;            &lt;/span&gt;&lt;span style=&quot;--0:#79C0FF&quot;&gt;this&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;.cacheMap.&lt;/span&gt;&lt;span style=&quot;--0:#D2A8FF&quot;&gt;set&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;(key, newNode);&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span class=&quot;indent&quot;&gt;            &lt;/span&gt;&lt;span style=&quot;--0:#79C0FF&quot;&gt;this&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;.&lt;/span&gt;&lt;span style=&quot;--0:#D2A8FF&quot;&gt;addToHead&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;(newNode);&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;
&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span class=&quot;indent&quot;&gt;            &lt;/span&gt;&lt;span style=&quot;--0:#8B949E&quot;&gt;// If capacity is exceeded, remove the oldest data (the node right before the tail)&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span class=&quot;indent&quot;&gt;            &lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;if&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; (&lt;/span&gt;&lt;span style=&quot;--0:#79C0FF&quot;&gt;this&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;.cacheMap.size &lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;&gt;&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; &lt;/span&gt;&lt;span style=&quot;--0:#79C0FF&quot;&gt;this&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;.capacity) {&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span class=&quot;indent&quot;&gt;                &lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;const&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; &lt;/span&gt;&lt;span style=&quot;--0:#79C0FF&quot;&gt;lruNode&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; &lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;=&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; &lt;/span&gt;&lt;span style=&quot;--0:#79C0FF&quot;&gt;this&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;.tail.prev;&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span class=&quot;indent&quot;&gt;                &lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;if&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; (lruNode &lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;&amp;#x26;&amp;#x26;&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; lruNode &lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;!==&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; &lt;/span&gt;&lt;span style=&quot;--0:#79C0FF&quot;&gt;this&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;.head) {&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span class=&quot;indent&quot;&gt;                    &lt;/span&gt;&lt;span style=&quot;--0:#79C0FF&quot;&gt;this&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;.&lt;/span&gt;&lt;span style=&quot;--0:#D2A8FF&quot;&gt;removeNode&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;(lruNode);&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span class=&quot;indent&quot;&gt;                    &lt;/span&gt;&lt;span style=&quot;--0:#79C0FF&quot;&gt;this&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;.cacheMap.&lt;/span&gt;&lt;span style=&quot;--0:#D2A8FF&quot;&gt;delete&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;(lruNode.key);&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span class=&quot;indent&quot;&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;                &lt;/span&gt;&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;}&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span class=&quot;indent&quot;&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;            &lt;/span&gt;&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;}&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span class=&quot;indent&quot;&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;        &lt;/span&gt;&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;}&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span class=&quot;indent&quot;&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;    &lt;/span&gt;&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;}&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;}&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;
&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span style=&quot;--0:#8B949E&quot;&gt;// Production test execution&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;const&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; &lt;/span&gt;&lt;span style=&quot;--0:#79C0FF&quot;&gt;userCache&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; &lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;=&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; &lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;new&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; &lt;/span&gt;&lt;span style=&quot;--0:#D2A8FF&quot;&gt;LRUCache&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;&amp;#x3C;&lt;/span&gt;&lt;span style=&quot;--0:#79C0FF&quot;&gt;string&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;, &lt;/span&gt;&lt;span style=&quot;--0:#79C0FF&quot;&gt;string&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;&gt;(&lt;/span&gt;&lt;span style=&quot;--0:#79C0FF&quot;&gt;2&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;);&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;userCache.&lt;/span&gt;&lt;span style=&quot;--0:#D2A8FF&quot;&gt;put&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;(&lt;/span&gt;&lt;span style=&quot;--0:#A5D6FF&quot;&gt;&quot;user_1&quot;&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;, &lt;/span&gt;&lt;span style=&quot;--0:#A5D6FF&quot;&gt;&quot;Alice Profile&quot;&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;);&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;userCache.&lt;/span&gt;&lt;span style=&quot;--0:#D2A8FF&quot;&gt;put&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;(&lt;/span&gt;&lt;span style=&quot;--0:#A5D6FF&quot;&gt;&quot;user_2&quot;&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;, &lt;/span&gt;&lt;span style=&quot;--0:#A5D6FF&quot;&gt;&quot;Bob Profile&quot;&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;);&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;
&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;console.&lt;/span&gt;&lt;span style=&quot;--0:#D2A8FF&quot;&gt;log&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;(userCache.&lt;/span&gt;&lt;span style=&quot;--0:#D2A8FF&quot;&gt;get&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;(&lt;/span&gt;&lt;span style=&quot;--0:#A5D6FF&quot;&gt;&quot;user_1&quot;&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;)); &lt;/span&gt;&lt;span style=&quot;--0:#8B949E&quot;&gt;// Alice Profile (user_1 is now the most recently used)&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;
&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span style=&quot;--0:#8B949E&quot;&gt;// Inserting new data exceeds capacity, evicting user_2 (least recently used) from memory&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;userCache.&lt;/span&gt;&lt;span style=&quot;--0:#D2A8FF&quot;&gt;put&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;(&lt;/span&gt;&lt;span style=&quot;--0:#A5D6FF&quot;&gt;&quot;user_3&quot;&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;, &lt;/span&gt;&lt;span style=&quot;--0:#A5D6FF&quot;&gt;&quot;Charlie Profile&quot;&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;);&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;console.&lt;/span&gt;&lt;span style=&quot;--0:#D2A8FF&quot;&gt;log&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;(userCache.&lt;/span&gt;&lt;span style=&quot;--0:#D2A8FF&quot;&gt;get&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;(&lt;/span&gt;&lt;span style=&quot;--0:#A5D6FF&quot;&gt;&quot;user_2&quot;&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;)); &lt;/span&gt;&lt;span style=&quot;--0:#8B949E&quot;&gt;// null (the data has been evicted from the cache)&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;/code&gt;&lt;/pre&gt;&lt;div class=&quot;copy&quot;&gt;&lt;div aria-live=&quot;polite&quot;&gt;&lt;/div&gt;&lt;button title=&quot;Copy to clipboard&quot; data-copied=&quot;Copied!&quot; data-code=&quot;// Architecture of each node in the doubly linked listclass CacheNode&lt;K, V&gt; {    public key: K;    public value: V;    public prev: CacheNode&lt;K, V&gt; | null = null;    public next: CacheNode&lt;K, V&gt; | null = null;    constructor(key: K, value: V) {        this.key = key;        this.value = value;    }}// Complete LRU Cache implementationexport class LRUCache&lt;K, V&gt; {    private capacity: number;    private cacheMap: Map&lt;K, CacheNode&lt;K, V&gt;&gt;;    private head: CacheNode&lt;K, V&gt;;    private tail: CacheNode&lt;K, V&gt;;    constructor(capacity: number) {        this.capacity = capacity;        this.cacheMap = new Map();        // Creating dummy head and tail nodes to make edge case handling easier        this.head = new CacheNode&lt;K, V&gt;({} as K, {} as V);        this.tail = new CacheNode&lt;K, V&gt;({} as K, {} as V);        this.head.next = this.tail;        this.tail.prev = this.head;    }    // Constant time logic to disconnect any node from the linked list    private removeNode(node: CacheNode&lt;K, V&gt;): void {        const prevNode = node.prev;        const nextNode = node.next;        if (prevNode &amp;#x26;&amp;#x26; nextNode) {            prevNode.next = nextNode;            nextNode.prev = prevNode;        }    }    // Constant time logic to add any node right after the head    private addToHead(node: CacheNode&lt;K, V&gt;): void {        node.prev = this.head;        node.next = this.head.next;        if (this.head.next) {            this.head.next.prev = node;        }        this.head.next = node;    }    // Constant time read method    public get(key: K): V | null {        if (!this.cacheMap.has(key)) {            return null;        }        const node = this.cacheMap.get(key)!;        // Since this data was just accessed, move it to the head        this.removeNode(node);        this.addToHead(node);        return node.value;    }    // Constant time write method    public put(key: K, value: V): void {        if (this.cacheMap.has(key)) {            // If data already exists, update its value and move it to the head            const existingNode = this.cacheMap.get(key)!;            existingNode.value = value;            this.removeNode(existingNode);            this.addToHead(existingNode);        } else {            // Creating a new node for new data            const newNode = new CacheNode(key, value);            this.cacheMap.set(key, newNode);            this.addToHead(newNode);            // If capacity is exceeded, remove the oldest data (the node right before the tail)            if (this.cacheMap.size &gt; this.capacity) {                const lruNode = this.tail.prev;                if (lruNode &amp;#x26;&amp;#x26; lruNode !== this.head) {                    this.removeNode(lruNode);                    this.cacheMap.delete(lruNode.key);                }            }        }    }}// Production test executionconst userCache = new LRUCache&lt;string, string&gt;(2);userCache.put(&amp;#x22;user_1&amp;#x22;, &amp;#x22;Alice Profile&amp;#x22;);userCache.put(&amp;#x22;user_2&amp;#x22;, &amp;#x22;Bob Profile&amp;#x22;);console.log(userCache.get(&amp;#x22;user_1&amp;#x22;)); // Alice Profile (user_1 is now the most recently used)// Inserting new data exceeds capacity, evicting user_2 (least recently used) from memoryuserCache.put(&amp;#x22;user_3&amp;#x22;, &amp;#x22;Charlie Profile&amp;#x22;);console.log(userCache.get(&amp;#x22;user_2&amp;#x22;)); // null (the data has been evicted from the cache)&quot;&gt;&lt;div&gt;&lt;/div&gt;&lt;/button&gt;&lt;/div&gt;&lt;/figure&gt;&lt;/div&gt;
&lt;hr&gt;
&lt;h2 id=&quot;recap-and-production-checklist&quot;&gt;Recap and Production Checklist&lt;/h2&gt;
&lt;p&gt;Through this detailed exploration of systems architecture, one core lesson becomes clear: the primary difference between a junior developer and an experienced system architect lies in their depth of thinking. Junior developers focus on whether their code runs and produces the correct output. System architects focus on what happens when that code executes ten million times across distributed networks, evaluating memory layouts, network latency, and processor loads. Data structures and algorithms are not just theoretical trivia meant for passing coding interviews; they form the absolute bedrock of your software engineering career, giving you the power to design fast, scalable, and reliable production systems.&lt;/p&gt;
&lt;p&gt;The next time you design a new system architecture or tackle a complex performance bottleneck, keep this developer decision checklist in mind:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;Use an Array when:&lt;/strong&gt; Your data size is fixed and known in advance, you need maximum memory optimization, and your system frequently reads elements by their index numbers in constant time.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Use a Linked List when:&lt;/strong&gt; Your data size changes constantly during runtime, and your application needs to insert or delete items from the beginning or middle of the sequence without delay.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Use a Hash Table or Map when:&lt;/strong&gt; You need to look up data instantly using a specific key from a massive dataset in constant time.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Use a Tree or Binary Search Tree when:&lt;/strong&gt; Your data naturally forms a hierarchical structure, and you need to execute fast range queries or searches across sorted records.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Use a Graph when:&lt;/strong&gt; You need to model complex networking logic, social media connections, mapping and routing systems, or real-world relationship paths.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Use a Queue when:&lt;/strong&gt; Your system needs to process incoming requests, background tasks, or worker jobs sequentially in a First-In, First-Out order.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Use a Stack when:&lt;/strong&gt; Your logic requires a Last-In, First-Out architecture, such as parsing programming syntax, tracking execution history, or building undo and redo mechanisms.&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;Best of luck on your engineering journey. By making the right architectural decisions, may every system you build be completely production ready and highly scalable.&lt;/p&gt;</content:encoded><category>Software Engineering</category><category>Software Engineering</category><category>Data Structures</category><category>Algorithms</category><category>System Architecture</category><category>Performance Optimization</category><category>Big-O Notation</category><category>Backend Engineering</category><category>Scalability</category><category>Caching</category><category>Database Indexing</category></item><item><title>How Messenger&apos;s &quot;Delete Conversation&quot; Feature Actually Works Under the Hood</title><link>https://www.rafeuddaraj.me/blog/messenger-delete-conversation-architecture-deep-dive/</link><guid isPermaLink="true">https://www.rafeuddaraj.me/blog/messenger-delete-conversation-architecture-deep-dive/</guid><description>A deep architectural breakdown of how high-throughput chat applications clear conversations at Big-O(1) storage complexity using timestamp-based view filtering and metadata pointers instead of database-level hard deletes.</description><pubDate>Wed, 10 Jun 2026 12:05:10 GMT</pubDate><content:encoded>&lt;p&gt;Many everyday developers assume that clicking the &quot;Delete Conversation&quot; button in a chat app fires a direct &lt;code&gt;DELETE&lt;/code&gt; query to the database. If you are building a small weekend project, this brute-force approach might work just fine. But when you are dealing with high-throughput distributed systems like Messenger that process millions of requests per second, running hard deletes or duplicating data for every single user can turn into an engineering disaster. Let us start by looking at why simple approaches completely fail in a production environment.&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;Hard Delete Fallacy: When you delete a chat and the system runs a direct delete query, your request wipes the entire conversation from both your inbox and the inbox of the person you were chatting with. This is unacceptable because it destroys both business record recall and the overall user experience.&lt;/li&gt;
&lt;li&gt;Data Duplication Anti-Pattern: To get around this, many developers think about creating separate database rows for each user. But the moment you write two database rows for every single message, you trigger massive write amplification across your system.&lt;/li&gt;
&lt;li&gt;Impact on Production: Duplicating data causes storage costs to skyrocket. On top of that, your database indexes become extremely heavy, query latency grows exponentially, and the entire system slows to a crawl.&lt;/li&gt;
&lt;li&gt;The Core Solution: To solve this complex problem, scalable systems like Messenger rely on smart metadata management and timestamp-based view filtering. This approach lets the backend clear an entire conversation at Big-O(1) storage complexity without actually deleting any underlying messages.&lt;/li&gt;
&lt;/ul&gt;
&lt;hr&gt;
&lt;h2 id=&quot;foundational-mental-model-and-a-real-world-analogy&quot;&gt;Foundational Mental Model and a Real-World Analogy&lt;/h2&gt;
&lt;p&gt;Before we get into the low-level architecture, we need to clear up one core concept: Shared Immutable Data versus User-Specific View State. The main philosophy here is that your primary data or message log always stays untouched. Instead of altering the real records, we simply shift the boundaries of the user&apos;s read queries. We can use a familiar real-world analogy to make this engineering concept easy to visualize and understand.&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;The Setup: Imagine a massive shared noticeboard on your office wall where everyone posts daily company announcements.&lt;/li&gt;
&lt;li&gt;The Problem: The old notices from several months ago are cluttering your view and distracting you, but your coworker still desperately needs those exact older documents for their current project.&lt;/li&gt;
&lt;li&gt;The Naive Fixes: If you rip those old notices off the board (a Hard Delete), your coworker gets stranded without their data. On the flip side, building two massive, separate noticeboards for the two of you (Data Duplication) is an expensive and unrealistic waste of space.&lt;/li&gt;
&lt;li&gt;The Smart Solution: A much smarter fix is to put on a special pair of glasses or a tinted visor with built-in filter logic that says, &quot;Do not show me any notices posted before 10:00 AM today.&quot; The old notices remain safely tacked to the physical board, but your eyes only register the items posted after ten in the morning.&lt;/li&gt;
&lt;li&gt;Application to Software: In our software architecture, the database is that shared office noticeboard. The timestamp stored inside the user&apos;s profile metadata acts as the digital filter in your glasses.&lt;/li&gt;
&lt;/ul&gt;
&lt;figure&gt;&lt;img src=&quot;https://raw.githubusercontent.com/rafeuddaraj/rafes-blog-assets/refs/heads/messenger-delete-conversation-architecture-deep-dive/assets/shared-vs-duplicated-storage-model.svg&quot; alt=&quot;Shared Data Model vs Duplicated Storage Model&quot; loading=&quot;lazy&quot; decoding=&quot;async&quot; width=&quot;800&quot; height=&quot;400&quot;&gt;&lt;figcaption&gt;Shared Data Model vs Duplicated Storage Model&lt;/figcaption&gt;&lt;/figure&gt;
&lt;hr&gt;
&lt;h2 id=&quot;under-the-hood-architecture-the-core-deep-dive&quot;&gt;Under-the-Hood Architecture (The Core Deep Dive)&lt;/h2&gt;
&lt;p&gt;Now let us step directly inside the database engine to see how this works in practice. To make this architecture function efficiently at scale, we split our relational or NoSQL document store into two distinct operational layers. This separation of concerns allows us to write messages fast while reading them with custom boundaries.&lt;/p&gt;
&lt;h3 id=&quot;a-messages-table-the-immutable-log&quot;&gt;A. &lt;code&gt;messages&lt;/code&gt; Table (The Immutable Log)&lt;/h3&gt;
&lt;p&gt;This is our primary message storage, and it operates entirely as an append-only table. During normal application workflows, we never run &lt;code&gt;UPDATE&lt;/code&gt; or &lt;code&gt;DELETE&lt;/code&gt; queries against this table. Avoiding modifications keeps our write paths fast and prevents locking issues across distributed nodes. The core columns in this table are &lt;code&gt;message_id&lt;/code&gt; (UUID), &lt;code&gt;conversation_id&lt;/code&gt; (Indexed UUID), &lt;code&gt;sender_id&lt;/code&gt; (UUID), &lt;code&gt;payload&lt;/code&gt; (Text/Blob), and &lt;code&gt;created_at&lt;/code&gt; (Timestamp).&lt;/p&gt;
&lt;h3 id=&quot;b-conversationparticipants-table-the-view-state-engine&quot;&gt;B. &lt;code&gt;conversation_participants&lt;/code&gt; Table (The View State Engine)&lt;/h3&gt;
&lt;p&gt;This table is the real engine behind our custom view states. It tracks personal status and visual boundaries for every individual user in every chat thread. Its core columns include &lt;code&gt;conversation_id&lt;/code&gt;, &lt;code&gt;user_id&lt;/code&gt;, &lt;code&gt;last_read_timestamp&lt;/code&gt;, and, most importantly, &lt;code&gt;cleared_at_timestamp&lt;/code&gt;. That final timestamp acts as an invisible wall that blocks older messages from appearing in the user interface.&lt;/p&gt;
&lt;h3 id=&quot;the-query-mechanics&quot;&gt;The Query Mechanics&lt;/h3&gt;
&lt;p&gt;When a user loads their inbox or opens a specific chat thread, our backend engine never runs a basic &lt;code&gt;SELECT *&lt;/code&gt; query. Instead, the system executes a filtered read query that dynamically checks the user&apos;s metadata boundary. The SQL logic for this read operation looks like the following snippet:&lt;/p&gt;
&lt;div class=&quot;expressive-code&quot;&gt;&lt;style&gt;.expressive-code{font-family:var(--ec-uiFontFml);font-size:var(--ec-uiFontSize);font-weight:var(--ec-uiFontWg);line-height:var(--ec-uiLineHt);text-size-adjust:none;-webkit-text-size-adjust:none}.expressive-code *:not(:is(svg, svg *)){all:revert;box-sizing:border-box}.expressive-code pre{display:flex;margin:0;padding:0;border:var(--ec-brdWd) solid var(--ec-brdCol);border-radius:calc(var(--ec-brdRad) + var(--ec-brdWd));background:var(--ec-codeBg)}.expressive-code pre:focus-visible{outline:3px solid var(--ec-focusBrd);outline-offset:-3px}.expressive-code pre &gt; code{all:unset;display:block;flex:1 0 100%;padding:var(--ec-codePadBlk) 0;color:var(--ec-codeFg);font-family:var(--ec-codeFontFml);font-size:var(--ec-codeFontSize);font-weight:var(--ec-codeFontWg);line-height:var(--ec-codeLineHt)}.expressive-code pre{overflow-x:auto}.expressive-code pre.wrap .ec-line .code{white-space:pre-wrap;overflow-wrap:break-word;min-width:min(20ch, var(--ecMaxLine, 20ch))}.expressive-code pre.wrap .ec-line .code span.indent{white-space:pre}.expressive-code pre::-webkit-scrollbar,.expressive-code pre::-webkit-scrollbar-track{background-color:inherit;border-radius:calc(var(--ec-brdRad) + var(--ec-brdWd));border-top-left-radius:0;border-top-right-radius:0}.expressive-code pre::-webkit-scrollbar-thumb{background-color:var(--ec-sbThumbCol);border:4px solid transparent;background-clip:content-box;border-radius:10px}.expressive-code pre::-webkit-scrollbar-thumb:hover{background-color:var(--ec-sbThumbHoverCol)}.expressive-code pre::-webkit-scrollbar-corner{background:transparent}.expressive-code .ec-line{direction:ltr;unicode-bidi:isolate;display:grid;grid-template-areas:&apos;gutter code&apos;;grid-template-columns:auto 1fr;position:relative}.expressive-code .ec-line .gutter{grid-area:gutter;color:var(--ec-gtrFg)}.expressive-code .ec-line .gutter &gt; *{pointer-events:none;user-select:none;-webkit-user-select:none}.expressive-code .ec-line .gutter ~ .code{--ecLineBrdCol:var(--ec-gtrBrdCol)}.expressive-code .ec-line.highlight .gutter{color:var(--ec-gtrHlFg)}.expressive-code .ec-line .code{grid-area:code;position:relative;box-sizing:content-box;padding-inline-start:calc(var(--ecIndent, 0ch) + var(--ec-codePadInl) - var(--ecGtrBrdWd));padding-inline-end:var(--ec-codePadInl);text-indent:calc(var(--ecIndent, 0ch) * -1)}.expressive-code .ec-line .code::before,.expressive-code .ec-line .code::after,.expressive-code .ec-line .code :where(*){text-indent:0}.expressive-code .ec-line .code{--ecGtrBrdWd:var(--ec-gtrBrdWd);border-inline-start:var(--ecGtrBrdWd) solid var(--ecLineBrdCol, transparent)}.expressive-code .sr-only{position:absolute;width:1px;height:1px;padding:0;margin:-1px;overflow:hidden;clip:rect(0, 0, 0, 0);white-space:nowrap;border-width:0}.expressive-code .ec-line.mark{--tmLineBgCol:var(--ec-tm-markBg)}.expressive-code .ec-line.mark .code{--ecLineBrdCol:var(--ec-tm-markBrdCol)}.expressive-code .ec-line.ins{--tmLineBgCol:var(--ec-tm-insBg);--tmLabel:var(--ec-tm-insDiffIndContent)}.expressive-code .ec-line.ins .code{--ecLineBrdCol:var(--ec-tm-insBrdCol)}.expressive-code .ec-line.ins .code::before{color:var(--ec-tm-insDiffIndCol)}.expressive-code .ec-line.del{--tmLineBgCol:var(--ec-tm-delBg);--tmLabel:var(--ec-tm-delDiffIndContent)}.expressive-code .ec-line.del .code{--ecLineBrdCol:var(--ec-tm-delBrdCol)}.expressive-code .ec-line.del .code::before{color:var(--ec-tm-delDiffIndCol)}.expressive-code .ec-line.mark,.expressive-code .ec-line.ins,.expressive-code .ec-line.del{background:var(--tmLineBgCol)}.expressive-code .ec-line.mark .code,.expressive-code .ec-line.ins .code,.expressive-code .ec-line.del .code{--ecGtrBrdWd:var(--ec-tm-lineMarkerAccentWd)}.expressive-code .ec-line.mark .code::before,.expressive-code .ec-line.ins .code::before,.expressive-code .ec-line.del .code::before{display:block;position:absolute;left:0;box-sizing:border-box;content:var(--tmLabel, &apos; &apos;);padding-inline-start:var(--ec-tm-lineDiffIndMargLeft);text-align:center;white-space:pre}.expressive-code .ec-line.mark.tm-label .code::before,.expressive-code .ec-line.ins.tm-label .code::before,.expressive-code .ec-line.del.tm-label .code::before{background:var(--ecLineBrdCol);padding:0 calc(var(--ec-tm-lineMarkerLabelPadInl) + var(--ec-tm-lineMarkerAccentWd)) 0 var(--ec-tm-lineMarkerLabelPadInl);color:var(--ec-tm-lineMarkerLabelCol)}.expressive-code .ec-line mark{--tmInlineBgCol:var(--ec-tm-markBg);--tmInlineBrdCol:var(--ec-tm-markBrdCol)}.expressive-code .ec-line ins{--tmInlineBgCol:var(--ec-tm-insBg);--tmInlineBrdCol:var(--ec-tm-insBrdCol)}.expressive-code .ec-line del{--tmInlineBgCol:var(--ec-tm-delBg);--tmInlineBrdCol:var(--ec-tm-delBrdCol)}.expressive-code .ec-line mark,.expressive-code .ec-line ins,.expressive-code .ec-line del{all:unset;display:inline-block;position:relative;--tmBrdL:var(--ec-tm-inlMarkerBrdWd);--tmBrdR:var(--ec-tm-inlMarkerBrdWd);--tmRadL:var(--ec-tm-inlMarkerBrdRad);--tmRadR:var(--ec-tm-inlMarkerBrdRad);margin-inline:0.025rem;padding-inline:var(--ec-tm-inlMarkerPad);border-radius:var(--tmRadL) var(--tmRadR) var(--tmRadR) var(--tmRadL);background:var(--tmInlineBgCol);background-clip:padding-box}.expressive-code .ec-line mark.open-start,.expressive-code .ec-line ins.open-start,.expressive-code .ec-line del.open-start{margin-inline-start:0;padding-inline-start:0;--tmBrdL:0px;--tmRadL:0}.expressive-code .ec-line mark.open-end,.expressive-code .ec-line ins.open-end,.expressive-code .ec-line del.open-end{margin-inline-end:0;padding-inline-end:0;--tmBrdR:0px;--tmRadR:0}.expressive-code .ec-line mark::before,.expressive-code .ec-line ins::before,.expressive-code .ec-line del::before{content:&apos;&apos;;position:absolute;pointer-events:none;display:inline-block;inset:0;border-radius:var(--tmRadL) var(--tmRadR) var(--tmRadR) var(--tmRadL);border:var(--ec-tm-inlMarkerBrdWd) solid var(--tmInlineBrdCol);border-inline-width:var(--tmBrdL) var(--tmBrdR)}.expressive-code .frame{all:unset;position:relative;display:block;--header-border-radius:calc(var(--ec-brdRad) + var(--ec-brdWd));--tab-border-radius:calc(var(--ec-frm-edTabBrdRad) + var(--ec-brdWd));--button-spacing:0.4rem;--code-background:var(--ec-frm-edBg);border-radius:var(--header-border-radius);box-shadow:var(--ec-frm-frameBoxShdCssVal)}.expressive-code .frame .header{display:none;z-index:1;position:relative;border-radius:var(--header-border-radius) var(--header-border-radius) 0 0}.expressive-code .frame.has-title pre,.expressive-code .frame.has-title code,.expressive-code .frame.is-terminal pre,.expressive-code .frame.is-terminal code{border-top:none;border-top-left-radius:0;border-top-right-radius:0}.expressive-code .frame .title:empty:before{content:&apos;\a0&apos;}.expressive-code .frame.has-title:not(.is-terminal){--button-spacing:calc(1.9rem + 2 * (var(--ec-uiPadBlk) + var(--ec-frm-edActTabIndHt)))}.expressive-code .frame.has-title:not(.is-terminal) .title{position:relative;color:var(--ec-frm-edActTabFg);background:var(--ec-frm-edActTabBg);background-clip:padding-box;margin-block-start:var(--ec-frm-edTabsMargBlkStart);padding:calc(var(--ec-uiPadBlk) + var(--ec-frm-edActTabIndHt)) var(--ec-uiPadInl);border:var(--ec-brdWd) solid var(--ec-frm-edActTabBrdCol);border-radius:var(--tab-border-radius) var(--tab-border-radius) 0 0;border-bottom:none;overflow:hidden}.expressive-code .frame.has-title:not(.is-terminal) .title::after{content:&apos;&apos;;position:absolute;pointer-events:none;inset:0;border-top:var(--ec-frm-edActTabIndHt) solid var(--ec-frm-edActTabIndTopCol);border-bottom:var(--ec-frm-edActTabIndHt) solid var(--ec-frm-edActTabIndBtmCol)}.expressive-code .frame.has-title:not(.is-terminal) .header{display:flex;background:linear-gradient(to top, var(--ec-frm-edTabBarBrdBtmCol) var(--ec-brdWd), transparent var(--ec-brdWd)),linear-gradient(var(--ec-frm-edTabBarBg), var(--ec-frm-edTabBarBg));background-repeat:no-repeat;padding-inline-start:var(--ec-frm-edTabsMargInlStart)}.expressive-code .frame.has-title:not(.is-terminal) .header::before{content:&apos;&apos;;position:absolute;pointer-events:none;inset:0;border:var(--ec-brdWd) solid var(--ec-frm-edTabBarBrdCol);border-radius:inherit;border-bottom:none}.expressive-code .frame.is-terminal{--button-spacing:calc(1.9rem + var(--ec-brdWd) + 2 * var(--ec-uiPadBlk));--code-background:var(--ec-frm-trmBg)}.expressive-code .frame.is-terminal .header{display:flex;align-items:center;justify-content:center;padding-block:var(--ec-uiPadBlk);padding-block-end:calc(var(--ec-uiPadBlk) + var(--ec-brdWd));position:relative;font-weight:500;letter-spacing:0.025ch;color:var(--ec-frm-trmTtbFg);background:var(--ec-frm-trmTtbBg);border:var(--ec-brdWd) solid var(--ec-brdCol);border-bottom:none}.expressive-code .frame.is-terminal .header::before{content:&apos;&apos;;position:absolute;pointer-events:none;left:var(--ec-uiPadInl);width:2.1rem;height:0.56rem;line-height:0;background-color:var(--ec-frm-trmTtbDotsFg);opacity:var(--ec-frm-trmTtbDotsOpa);-webkit-mask-image:var(--ec-frm-trmIcon);-webkit-mask-repeat:no-repeat;mask-image:var(--ec-frm-trmIcon);mask-repeat:no-repeat}.expressive-code .frame.is-terminal .header::after{content:&apos;&apos;;position:absolute;pointer-events:none;inset:0;border-bottom:var(--ec-brdWd) solid var(--ec-frm-trmTtbBrdBtmCol)}.expressive-code .frame pre{background:var(--code-background)}.expressive-code .copy{display:flex;gap:0.25rem;flex-direction:row;position:absolute;inset-block-start:calc(var(--ec-brdWd) + var(--button-spacing));inset-inline-end:calc(var(--ec-brdWd) + var(--ec-uiPadInl) / 2)}@media (scripting: none){.expressive-code .copy{display:none}}.expressive-code .copy{direction:ltr;unicode-bidi:isolate}.expressive-code .copy button{position:relative;align-self:flex-end;margin:0;padding:0;border:none;border-radius:0.2rem;z-index:1;cursor:pointer;transition-property:opacity, background, border-color;transition-duration:0.2s;transition-timing-function:cubic-bezier(0.25, 0.46, 0.45, 0.94);width:2.5rem;height:2.5rem;background:var(--code-background);opacity:0.75}.expressive-code .copy button div{position:absolute;inset:0;border-radius:inherit;background:var(--ec-frm-inlBtnBg);opacity:var(--ec-frm-inlBtnBgIdleOpa);transition-property:inherit;transition-duration:inherit;transition-timing-function:inherit}.expressive-code .copy button::before{content:&apos;&apos;;position:absolute;pointer-events:none;inset:0;border-radius:inherit;border:var(--ec-brdWd) solid var(--ec-frm-inlBtnBrd);opacity:var(--ec-frm-inlBtnBrdOpa)}.expressive-code .copy button::after{content:&apos;&apos;;position:absolute;pointer-events:none;inset:0;background-color:var(--ec-frm-inlBtnFg);-webkit-mask-image:var(--ec-frm-copyIcon);-webkit-mask-repeat:no-repeat;mask-image:var(--ec-frm-copyIcon);mask-repeat:no-repeat;margin:0.475rem;line-height:0}.expressive-code .copy button:hover,.expressive-code .copy button:focus:focus-visible{opacity:1}.expressive-code .copy button:hover div,.expressive-code .copy button:focus:focus-visible div{opacity:var(--ec-frm-inlBtnBgHoverOrFocusOpa)}.expressive-code .copy button:active{opacity:1}.expressive-code .copy button:active div{opacity:var(--ec-frm-inlBtnBgActOpa)}.expressive-code .copy .feedback{--tooltip-arrow-size:0.35rem;--tooltip-bg:var(--ec-frm-tooltipSuccessBg);color:var(--ec-frm-tooltipSuccessFg);pointer-events:none;user-select:none;-webkit-user-select:none;position:relative;align-self:center;background-color:var(--tooltip-bg);z-index:99;padding:0.125rem 0.75rem;border-radius:0.2rem;margin-inline-end:var(--tooltip-arrow-size);opacity:0;transition-property:opacity, transform;transition-duration:0.2s;transition-timing-function:ease-in-out;transform:translate3d(0, 0.25rem, 0)}.expressive-code .copy .feedback::after{content:&apos;&apos;;position:absolute;pointer-events:none;top:calc(50% - var(--tooltip-arrow-size));inset-inline-end:calc(-2 * (var(--tooltip-arrow-size) - 0.5px));border:var(--tooltip-arrow-size) solid transparent;border-inline-start-color:var(--tooltip-bg)}.expressive-code .copy .feedback.show{opacity:1;transform:translate3d(0, 0, 0)}@media (hover: hover){.expressive-code{}.expressive-code .copy button{opacity:0;width:2rem;height:2rem}.expressive-code .frame:hover .copy button:not(:hover),.expressive-code .frame:focus-within :focus-visible ~ .copy button:not(:hover),.expressive-code .frame .copy .feedback.show ~ button:not(:hover){opacity:0.75}}.expressive-code :nth-child(1 of .ec-line) .code{padding-inline-end:calc(2rem + var(--ec-codePadInl))}:root{--ec-brdRad:0.75rem;--ec-brdWd:1.5px;--ec-brdCol:var(--code-line);--ec-codeFontFml:var(--font-code);--ec-codeFontSize:0.875rem;--ec-codeFontWg:400;--ec-codeLineHt:1.75;--ec-codePadBlk:1rem;--ec-codePadInl:1.125rem;--ec-codeBg:var(--code-bg);--ec-codeFg:#e6edf3;--ec-codeSelBg:#264f78;--ec-gtrFg:#6e7681;--ec-gtrBrdCol:#6e768133;--ec-gtrBrdWd:1.5px;--ec-gtrHlFg:#e6edf3;--ec-uiFontFml:var(--font-mono);--ec-uiFontSize:0.75rem;--ec-uiFontWg:400;--ec-uiLineHt:1.65;--ec-uiPadBlk:0.25rem;--ec-uiPadInl:1rem;--ec-uiSelBg:#6e768166;--ec-uiSelFg:#e6edf3;--ec-focusBrd:#1f6feb;--ec-sbThumbCol:#8b949e33;--ec-sbThumbHoverCol:#8b949e3d;--ec-tm-lineMarkerAccentMarg:0rem;--ec-tm-lineMarkerAccentWd:0.15rem;--ec-tm-lineMarkerLabelPadInl:0.2rem;--ec-tm-lineMarkerLabelCol:white;--ec-tm-lineDiffIndMargLeft:0.3rem;--ec-tm-inlMarkerBrdWd:1.5px;--ec-tm-inlMarkerBrdRad:0.2rem;--ec-tm-inlMarkerPad:0.15rem;--ec-tm-insDiffIndContent:&apos;+&apos;;--ec-tm-delDiffIndContent:&apos;-&apos;;--ec-tm-markBg:#264a8980;--ec-tm-markBrdCol:#5570b3d0;--ec-tm-insBg:#26561c80;--ec-tm-insBrdCol:#4e7e41d0;--ec-tm-insDiffIndCol:#7eb070d0;--ec-tm-delBg:#81322b80;--ec-tm-delBrdCol:#ae594fd0;--ec-tm-delDiffIndCol:#e68a7ed0;--ec-frm-shdCol:#0000005b;--ec-frm-frameBoxShdCssVal:none;--ec-frm-edActTabBg:var(--code-bg);--ec-frm-edActTabFg:var(--code-muted);--ec-frm-edActTabBrdCol:transparent;--ec-frm-edActTabIndHt:1.5px;--ec-frm-edActTabIndTopCol:transparent;--ec-frm-edActTabIndBtmCol:#0d1117;--ec-frm-edTabsMargInlStart:0;--ec-frm-edTabsMargBlkStart:0;--ec-frm-edTabBrdRad:0.75rem;--ec-frm-edTabBarBg:var(--code-bg);--ec-frm-edTabBarBrdCol:var(--code-line);--ec-frm-edTabBarBrdBtmCol:var(--code-line);--ec-frm-edBg:var(--code-bg);--ec-frm-trmTtbFg:var(--code-muted);--ec-frm-trmTtbDotsFg:var(--code-muted);--ec-frm-trmTtbDotsOpa:0.15;--ec-frm-trmTtbBg:var(--code-bg);--ec-frm-trmTtbBrdBtmCol:var(--code-line);--ec-frm-trmBg:var(--code-bg);--ec-frm-inlBtnBg:var(--code-ink);--ec-frm-inlBtnBgIdleOpa:0;--ec-frm-inlBtnBgHoverOrFocusOpa:0.2;--ec-frm-inlBtnBgActOpa:0.3;--ec-frm-inlBtnFg:var(--code-ink);--ec-frm-inlBtnBrd:var(--code-line);--ec-frm-inlBtnBrdOpa:0.4;--ec-frm-tooltipSuccessBg:var(--color-emerald);--ec-frm-tooltipSuccessFg:var(--color-bg);--ec-frm-copyIcon:url(&quot;data:image/svg+xml,%3Csvg%20xmlns%3D&apos;http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg&apos;%20viewBox%3D&apos;0%200%2024%2024&apos;%20fill%3D&apos;none&apos;%20stroke%3D&apos;black&apos;%20stroke-width%3D&apos;1.75&apos;%3E%3Cpath%20d%3D&apos;M3%2019a2%202%200%200%201-1-2V2a2%202%200%200%201%201-1h13a2%202%200%200%201%202%201&apos;%2F%3E%3Crect%20x%3D&apos;6&apos;%20y%3D&apos;5&apos;%20width%3D&apos;16&apos;%20height%3D&apos;18&apos;%20rx%3D&apos;1.5&apos;%20ry%3D&apos;1.5&apos;%2F%3E%3C%2Fsvg%3E&quot;);--ec-frm-trmIcon:url(&quot;data:image/svg+xml,%3Csvg%20xmlns%3D&apos;http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg&apos;%20viewBox%3D&apos;0%200%2060%2016&apos;%20preserveAspectRatio%3D&apos;xMidYMid%20meet&apos;%3E%3Ccircle%20cx%3D&apos;8&apos;%20cy%3D&apos;8&apos;%20r%3D&apos;8&apos;%2F%3E%3Ccircle%20cx%3D&apos;30&apos;%20cy%3D&apos;8&apos;%20r%3D&apos;8&apos;%2F%3E%3Ccircle%20cx%3D&apos;52&apos;%20cy%3D&apos;8&apos;%20r%3D&apos;8&apos;%2F%3E%3C%2Fsvg%3E&quot;)}.expressive-code .ec-line :where(span[style^=&apos;--&apos;]:not([class])){color:var(--0, inherit);background-color:var(--0bg, transparent);font-style:var(--0fs, inherit);font-weight:var(--0fw, inherit);text-decoration:var(--0td, inherit)}&lt;/style&gt;&lt;script type=&quot;module&quot; src=&quot;/_astro/ec.0vx5m.js&quot;&gt;&lt;/script&gt;&lt;figure class=&quot;frame has-title&quot;&gt;&lt;figcaption class=&quot;header&quot;&gt;&lt;span class=&quot;title&quot;&gt;SQL&lt;/span&gt;&lt;/figcaption&gt;&lt;pre data-language=&quot;sql&quot;&gt;&lt;code&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;SELECT&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; message_id, sender_id, payload, created_at&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;FROM&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; messages&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;WHERE&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; conversation_id &lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;=&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; &lt;/span&gt;&lt;span style=&quot;--0:#A5D6FF&quot;&gt;&apos;conv_12345&apos;&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span class=&quot;indent&quot;&gt;  &lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;AND&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; created_at &lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;&gt;&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; (&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span class=&quot;indent&quot;&gt;      &lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;SELECT&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; cleared_at_timestamp&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span class=&quot;indent&quot;&gt;      &lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;FROM&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; conversation_participants&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span class=&quot;indent&quot;&gt;      &lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;WHERE&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; conversation_id &lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;=&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; &lt;/span&gt;&lt;span style=&quot;--0:#A5D6FF&quot;&gt;&apos;conv_12345&apos;&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; &lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;AND&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; user_id &lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;=&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; &lt;/span&gt;&lt;span style=&quot;--0:#A5D6FF&quot;&gt;&apos;user_A&apos;&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span class=&quot;indent&quot;&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;  &lt;/span&gt;&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;)&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;ec-line&quot;&gt;&lt;div class=&quot;code&quot;&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;ORDER BY&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt; created_at &lt;/span&gt;&lt;span style=&quot;--0:#FF7B72&quot;&gt;ASC&lt;/span&gt;&lt;span style=&quot;--0:#E6EDF3&quot;&gt;;&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;/code&gt;&lt;/pre&gt;&lt;div class=&quot;copy&quot;&gt;&lt;div aria-live=&quot;polite&quot;&gt;&lt;/div&gt;&lt;button title=&quot;Copy to clipboard&quot; data-copied=&quot;Copied!&quot; data-code=&quot;SELECT message_id, sender_id, payload, created_atFROM messagesWHERE conversation_id = &amp;#x27;conv_12345&amp;#x27;  AND created_at &gt; (      SELECT cleared_at_timestamp      FROM conversation_participants      WHERE conversation_id = &amp;#x27;conv_12345&amp;#x27; AND user_id = &amp;#x27;user_A&amp;#x27;  )ORDER BY created_at ASC;&quot;&gt;&lt;div&gt;&lt;/div&gt;&lt;/button&gt;&lt;/div&gt;&lt;/figure&gt;&lt;/div&gt;
&lt;h3 id=&quot;index-optimization-b-tree-lsm-tree&quot;&gt;Index Optimization (B-Tree / LSM-Tree)&lt;/h3&gt;
&lt;p&gt;To run this query across millions of messages without slowing down, we must avoid a full table scan at all costs. We solve this by building a composite index on &lt;code&gt;(conversation_id, created_at)&lt;/code&gt;. When the read query hits the database, the engine uses this B-Tree or LSM-Tree index to traverse the tree with Big-O(log N) time complexity. Because of how the index is ordered, any messages older than the &lt;code&gt;cleared_at_timestamp&lt;/code&gt; get skipped right at the memory level. This structure makes query execution lightning fast, even when a conversation contains years of history.&lt;/p&gt;
&lt;figure&gt;&lt;img src=&quot;https://raw.githubusercontent.com/rafeuddaraj/rafes-blog-assets/refs/heads/messenger-delete-conversation-architecture-deep-dive/assets/timestamp-boundary-query-execution.svg&quot; alt=&quot;Low Level B-Tree Index Traversal with Timestamp Boundary&quot; loading=&quot;lazy&quot; decoding=&quot;async&quot; width=&quot;800&quot; height=&quot;450&quot;&gt;&lt;figcaption&gt;Low Level B-Tree Index Traversal with Timestamp Boundary&lt;/figcaption&gt;&lt;/figure&gt;
&lt;hr&gt;
&lt;h2 id=&quot;step-by-step-execution-trace-and-code-mechanics&quot;&gt;Step-by-Step Execution Trace and Code Mechanics&lt;/h2&gt;
&lt;p&gt;Let us walk through a step-by-step execution trace to see what happens under the hood when you press that &quot;Delete Conversation&quot; button in your application interface. Understanding this flow helps clarify how the frontend, backend, and database interact without deleting physical rows.&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;Step 1: User Triggers &quot;Delete Conversation&quot;: The client application sends a request to the backend endpoint at &lt;code&gt;POST /api/v1/conversations/{id}/clear&lt;/code&gt;. Once the backend receives this call, it completely ignores the &lt;code&gt;messages&lt;/code&gt; table. The system simply updates the &lt;code&gt;cleared_at_timestamp&lt;/code&gt; column for that specific user in the &lt;code&gt;conversation_participants&lt;/code&gt; table, setting it to the current timestamp. At the same time, it evicts the old metadata from Redis or the application cache to keep read performance sharp.&lt;/li&gt;
&lt;li&gt;Step 2: The Inbox List Re-render: The moment the timestamp updates, the app runs its filtered query to render the inbox. Since no messages exist with a creation time greater than the new &lt;code&gt;cleared_at_timestamp&lt;/code&gt;, the query returns a count of zero. The application UI responds by hiding the chat window or rendering a clean, blank slate.&lt;/li&gt;
&lt;li&gt;Step 3: New Message Arrival: A few minutes later, the other user sends you a fresh message. This new payload gets appended to the &lt;code&gt;messages&lt;/code&gt; table just like normal. A message broker like Kafka or RabbitMQ then routes a push notification directly to your device.&lt;/li&gt;
&lt;li&gt;Step 4: The Re-emergence in Inbox: When you open the application again, the backend executes the same filtered query. Because the &lt;code&gt;created_at&lt;/code&gt; timestamp of this new message is greater than your &lt;code&gt;cleared_at_timestamp&lt;/code&gt; boundary, the database returns the new item. The UI instantly reactivates the chat box to display only the new message, leaving all older chat history trapped behind that invisible wall.&lt;/li&gt;
&lt;/ul&gt;
&lt;figure&gt;&lt;img src=&quot;https://raw.githubusercontent.com/rafeuddaraj/rafes-blog-assets/refs/heads/messenger-delete-conversation-architecture-deep-dive/assets/timeline-state-transition-flow.svg&quot; alt=&quot;Timeline State Transition Flow After Delete Action&quot; loading=&quot;lazy&quot; decoding=&quot;async&quot; width=&quot;800&quot; height=&quot;350&quot;&gt;&lt;figcaption&gt;Timeline State Transition Flow After Delete Action&lt;/figcaption&gt;&lt;/figure&gt;
&lt;div class=&quot;callout&quot; role=&quot;note&quot; data-type=&quot;note&quot;&gt;
&lt;p class=&quot;callout-title&quot;&gt;Important&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Soft Delete vs. Timestamp Boundary&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;Setting an individual &lt;code&gt;is_deleted&lt;/code&gt; flag on every single message (Soft Delete) is a slow and expensive operation because the database must update every historical row. In contrast, updating a single &lt;code&gt;cleared_at_timestamp&lt;/code&gt; metadata value guarantees Big-O(1) time complexity and brings system write amplification down to zero.&lt;/p&gt;
&lt;/div&gt;
&lt;hr&gt;
&lt;h2 id=&quot;edge-cases-pitfalls-and-architectural-trade-offs&quot;&gt;Edge Cases, Pitfalls, and Architectural Trade-offs&lt;/h2&gt;
&lt;p&gt;When you design a scalable architecture, you cannot rely solely on the happy path. High production loads and strict memory constraints force us to account for several critical edge cases and system trade-offs. Let us examine the most common traps developers encounter and how to engineer around them.&lt;/p&gt;
&lt;h3 id=&quot;a-storage-growth-vs-garbage-collection-gdpr-compliance&quot;&gt;A. Storage Growth vs. Garbage Collection (GDPR Compliance)&lt;/h3&gt;
&lt;p&gt;Problem: If we never delete underlying messages and store logs forever, our storage costs will eventually shoot through the roof. On top of that, international privacy laws like Europe&apos;s GDPR make it illegal to store deleted user data forever.&lt;/p&gt;
&lt;p&gt;Solution: We handle this by running background asynchronous garbage collection or scheduled cron jobs. The background job regularly checks the database. When the &lt;code&gt;cleared_at&lt;/code&gt; timestamps for both participants in a conversation are greater than the &lt;code&gt;created_at&lt;/code&gt; timestamp of a specific message, it means neither user wants to see it anymore. Only then does the system execute a hard delete to wipe those old messages from the disk.&lt;/p&gt;
&lt;div class=&quot;callout&quot; role=&quot;note&quot; data-type=&quot;warning&quot;&gt;
&lt;p class=&quot;callout-title&quot;&gt;Warning&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;The Compliance &amp;#x26; Privacy Trap&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;If your system lacks an automated data retention policy and a dual-deletion purge mechanism, relying purely on timestamp-based filtering will expose you to severe legal risks. Building background garbage collection is mandatory for protecting user privacy and staying compliant.&lt;/p&gt;
&lt;/div&gt;
&lt;h3 id=&quot;b-index-bloating-and-performance-degradation&quot;&gt;B. Index Bloating and Performance Degradation&lt;/h3&gt;
&lt;p&gt;Problem: When millions of deleted messages accumulate in your tables, the database engine has to bypass a massive number of dead or invisible nodes every time it traverses an index. Over time, this overhead causes read latency to creep upward and degrades overall system responsiveness.&lt;/p&gt;
&lt;p&gt;Solution: We stop this performance drop by using database partitioning and time-series bucketing. We regularly move aging data out of the active index and shift it into cold storage. This practice keeps the hot, active index compact and lightning fast.&lt;/p&gt;
&lt;h3 id=&quot;c-clock-skew-in-distributed-servers&quot;&gt;C. Clock Skew in Distributed Servers&lt;/h3&gt;
&lt;p&gt;Problem: In a global distributed system, servers spread across different regions can experience slight timing differences known as clock skew. Even a few milliseconds of drift can cause timestamp mismatches and trigger race conditions where brand-new messages accidentally get trapped behind the invisible wall.&lt;/p&gt;
&lt;p&gt;Solution: You should never rely on local server time to prevent these timing discrepancies. Instead, use database-generated UTC timestamps or centralized, monotonically increasing time sources like Google TrueTime or Snowflake IDs.&lt;/p&gt;
&lt;div class=&quot;callout&quot; role=&quot;note&quot; data-type=&quot;tip&quot;&gt;
&lt;p class=&quot;callout-title&quot;&gt;Tip&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Query Optimization Pro-Tip&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;Always follow the Leftmost Prefix Rule when building composite indexes in your database. Because of our specific query pattern, your &lt;code&gt;(conversation_id, created_at)&lt;/code&gt; index must place &lt;code&gt;conversation_id&lt;/code&gt; first and &lt;code&gt;created_at&lt;/code&gt; second. This structure lets the database isolate the correct chat thread first before it filters out the timestamp boundaries.&lt;/p&gt;
&lt;/div&gt;
&lt;hr&gt;
&lt;h2 id=&quot;summary-and-production-decision-rules&quot;&gt;Summary and Production Decision Rules&lt;/h2&gt;
&lt;p&gt;The core takeaway from our deep dive is simple: when building scalable systems, always replace brute-force database operations with smart metadata and query boundaries. As you design the architecture for your next project, use this production decision matrix as a practical reference guide to choose the right approach for your specific requirements.&lt;/p&gt;
&lt;section class=&quot;table-wrap&quot; tabindex=&quot;0&quot; aria-label=&quot;Table 1&quot;&gt;
























&lt;table&gt;&lt;thead&gt;&lt;tr&gt;&lt;th&gt;Architectural Model&lt;/th&gt;&lt;th&gt;When to Use&lt;/th&gt;&lt;th&gt;Key Advantages and Trade-offs&lt;/th&gt;&lt;/tr&gt;&lt;/thead&gt;&lt;tbody&gt;&lt;tr&gt;&lt;td&gt;&lt;strong&gt;Duplicated Data Model&lt;/strong&gt;&lt;/td&gt;&lt;td&gt;Small-scale applications or systems that require strict, isolated end-to-end encryption.&lt;/td&gt;&lt;td&gt;Gives each user total control over their data, but write amplification and storage costs are extremely high.&lt;/td&gt;&lt;/tr&gt;&lt;tr&gt;&lt;td&gt;&lt;strong&gt;Row-Level Soft Delete&lt;/strong&gt;&lt;/td&gt;&lt;td&gt;When users need to delete specific, individual messages (such as &quot;Unsend&quot; or &quot;Delete for everyone&quot; features).&lt;/td&gt;&lt;td&gt;Makes it easy to target single items, but clearing entire chat histories puts heavy operational pressure on the database.&lt;/td&gt;&lt;/tr&gt;&lt;tr&gt;&lt;td&gt;&lt;strong&gt;Timestamp-Based View Filtering&lt;/strong&gt;&lt;/td&gt;&lt;td&gt;When users want to clear entire chat threads or inbox feeds with a single click.&lt;/td&gt;&lt;td&gt;Delivers zero write amplification and Big-O(1) complexity. However, it requires you to manage background garbage collection and strict timestamp synchronization.&lt;/td&gt;&lt;/tr&gt;&lt;/tbody&gt;&lt;/table&gt;&lt;/section&gt;
&lt;p&gt;Hopefully, the next time you design a database or chat system for a high-throughput application, this timestamp-based filtering logic will help you build a cleaner, faster, and more reliable backend. Happy coding!&lt;/p&gt;</content:encoded><category>System Design</category><category>Deep Dive</category><category>Under the hood</category><category>Architecture</category><category>Distributed Systems</category><category>Database Design</category><category>Big-O</category><category>Scalability</category><category>Backend Engineering</category></item></channel></rss>