<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by gati sahu on Medium]]></title>
        <description><![CDATA[Stories by gati sahu on Medium]]></description>
        <link>https://medium.com/@gati.sahu?source=rss-fcb9046d516e------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*DRA-Qt14MA6Xh2Oj.</url>
            <title>Stories by gati sahu on Medium</title>
            <link>https://medium.com/@gati.sahu?source=rss-fcb9046d516e------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 06 Dec 2026 13:38:11 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@gati.sahu/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[From Timeouts to Evidence: How φ Accrual Failure Detector Rethinks Liveness]]></title>
            <link>https://medium.com/@gati.sahu/from-timeouts-to-evidence-how-%CF%86-accrual-failure-detector-rethinks-liveness-068dded694a1?source=rss-fcb9046d516e------2</link>
            <guid isPermaLink="false">https://medium.com/p/068dded694a1</guid>
            <dc:creator><![CDATA[gati sahu]]></dc:creator>
            <pubDate>Sun, 23 Aug 2026 05:22:37 GMT</pubDate>
            <atom:updated>2026-08-23T05:23:42.818Z</atom:updated>
            <content:encoded><![CDATA[<p>Every distributed system leans on one primitive constantly: figuring out which peers are still alive. Leader election, quorum reads, hinted handoff, replica placement — all of it branches on liveness at some point. The uncomfortable truth, formalized by Fischer, Lynch, and Paterson back in 1985, is that in an asynchronous network this question has no clean answer. There’s no upper bound on message delay, so a node that’s merely slow looks identical, from the outside, to a node that has crashed. Consensus itself is provably impossible under these conditions with even a single faulty process.</p><h3>The problem with timeout nobody can set correctly</h3><p>In practice, essentially every failure detector reduces to the same mechanism: heartbeats plus a timeout. A process <em>q</em> sends process <em>p</em> a heartbeat at a fixed interval, Δi. If <em>p</em> doesn’t hear from <em>q</em> within a timeout period, Δto, it suspects <em>q</em> of having failed.</p><p>It sounds too simple to be the whole story. It is the whole story, and that’s exactly the problem.</p><p>That single constant, Δto, encodes the entire safety-liveness tradeoff of the system. A short timeout produces fast detection, but at the cost of frequent false positives: flapping, spurious failover, unnecessary data movement triggered by a peer that was never actually down. A long timeout produces the opposite effect: few false positives, but slower detection, stale routing information, and blocked writes sitting behind a failure nobody’s noticed yet.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vk_birj5P3k4ta5EiwxwiA.png" /></figure><p><strong>Binary output forces one tradeoff on every consumer.</strong> A classical detector outputs a single bit: trust or suspect. But different subsystems reading that same bit have genuinely different risk profiles.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UPqk2k_KUfeip-Y3pratEw.png" /></figure><p><strong>Fixed timeouts don’t survive contact with real networks.</strong> Latency distributions shift with load, GC, congestion, and topology. A timeout tuned for a quiet LAN mis-fires on a busy WAN link.</p><p><strong>Adaptive detectors adapt the wrong layer.</strong> Adaptive schemes (Chen FD, Bertier FD) do estimate the next expected arrival time from observed history and add a safety margin. That’s a real improvement — but the output is still binary, and the safety margin is still a hardwired application-level judgment baked into the detector itself. The interpretation policy remains fused to the monitoring mechanism.</p><p><strong>Accrual failure detectors. </strong>The core idea is easy to state: instead of answering “is it alive” with a yes or no, an accrual failure detector gives you a number. The higher that number climbs, the more confident the system is that the process has actually crashed. Nothing gets decided at the detector level — the number just keeps accruing, and it’s up to whoever’s watching it to decide what “too high” means for them.</p><p>To see why that’s a bigger deal than it sounds, it helps to break failure detection into three separate jobs:</p><ol><li><strong>Monitoring</strong> — gathering the raw signal. Usually this means watching for heartbeats or timing how long a query takes to get a response.</li><li><strong>Interpretation</strong> — turning that raw signal into a judgment. This is where “the process is probably dead” gets decided.</li><li><strong>Action</strong> — actually doing something about it. Retrying a request, rerouting traffic, kicking a node out of the cluster, whatever the situation calls for.</li></ol><p>The particular accrual implementation proposed in the paper — the φ failure detector — dynamically adjusts the scale of its suspicion level to current network conditions. Define P_later(t) as the probability, estimated from a recent sampling window, that a heartbeat arrives more than t time units after the previous one. Then:</p><p>φ(t_now) = -log10( P_later(t_now — T_last) )</p><p>where T_last is the time the last heartbeat arrived. Given a threshold Φ, deciding to suspect p when φ ≥ Φ = 1 means the likelihood of being wrong is about 10%. At Φ = 2 it is about 1%, at Φ = 3 about 0.1%, and so on. φ is the negative log-base-10 of the probability of a mistake — roughly, the number of nines of confidence behind the decision.</p><p>Two clusters, both heart beating once per second. A node has been silent for 3 seconds in both.</p><p>Cluster A — quiet datacenter LAN. Observed intervals: 1.00, 1.01, 0.99, 1.00, 1.02s (mean ≈ 1.0, tight). Three seconds of silence is wildly out of character ⇒ P_later(3s) is minuscule ⇒ φ is high ⇒ suspect now.</p><p>Cluster B — congested WAN link, noisy neighbors. Observed intervals: 0.9, 2.8, 1.1, 4.2, 0.8, 3.5s (mean ≈ 1.0, heavy tail). Three seconds of silence happens all the time ⇒ P_later(3s) is unremarkable ⇒ φ is low ⇒ keep waiting.</p><p><strong>φ Measures Surprise, Not Death</strong></p><p>The easiest mistake when learning φ is to interpret it as “φ = 8 means the node is probably dead.” It doesn’t. φ answers a much narrower question: assuming the node is healthy and continues behaving as it normally has, how surprising is the silence we are observing? In statistical terms, the detector starts with the assumption that the node is fine, and then measures how inconsistent the current observation is with that assumption.</p><p>Suppose Node A normally sends a heartbeat every 1 second. The detector observes a steady cadence, then the last heartbeat arrives and nothing happens.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BVFa8gN8aUgsz03_I1r5bQ.png" /></figure><p>The detector is saying: if this node were behaving normally, a silence this long would be extraordinarily unlikely. It is not saying the node has an 8% chance of being dead. The distinction matters because the node may still be alive.</p><p>A GC pause looks the same to the detector</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TjRQVB85rYBLGX11LzJPOg.png" /></figure><p>A network partition looks the same too</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CxaqgI_YrU7mS7naDdqZkQ.png" /></figure><p>In both cases φ can climb very high. The detector knows only one thing with confidence: the node has become unusually quiet. It does not know why. That is why φ should be thought of as a surprise score, not a death probability.</p><p>Once we know that φ measures surprise, we need a way to quantify that surprise. The starting point is a survival probability. Define P_later(t) as the probability that a normal heartbeat gap will last longer than t — in other words, if this node is behaving normally, how likely is it that we will have to wait at least t seconds for the next heartbeat? At the beginning of the silence, this probability is high. As the silence continues, it falls toward zero.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*n46h71zbV8TEjroxd46xsg.png" /></figure><p>Cassandra models this using an exponential distribution:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*J1O7Ic7ZcPfvjGZdigFNFQ.png" /></figure><p>Example Suppose a node normally gossips every second (μ = 1s), and it has now been silent for 3 seconds:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*okYOr6bD-bGsg4fbVlM4Gw.png" /></figure><p><strong>The Threshold Is Not a Timeout</strong></p><p>This is where φ becomes fundamentally different from a traditional timeout. A traditional failure detector might be configured as: if no heartbeat for 20 seconds, declare the node failed. That embeds a fixed assumption about the environment. φ does something different. You configure how much statistical evidence is required before acting. From φ = t / (μ × ln10),</p><p>we can derive the time required to reach a threshold:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*EYC-ygskgdTkAGUgO8Tocg.png" /></figure><p>Example — same threshold, different networks</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*la1YZeaQ0TwPlgcIpNOdmQ.png" /></figure><p>The configuration is identical, but the WAN node automatically receives more patience because its normal heartbeat intervals are already longer. If the WAN improves and its μ drops from 3 seconds to 1.5 seconds, the effective timeout automatically falls from roughly 55.3s to 27.6s — no configuration change is required. The operator configures risk tolerance; the detector derives the appropriate time from observed behavior. A fixed timeout cannot provide this without maintaining separate environment-specific configurations.</p><p><strong>The Detector Produces Evidence; Policy Decides What It Means</strong></p><p>Now the pieces come together. The failure detector does not really need to answer “is this node dead?” — that is too strong a conclusion from the information available. Instead, it produces a continuously increasing measure of suspicion, and the consumers of that signal make different decisions</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5I9fyAF0n6zcqyU9JZ7gZA.png" /></figure><p>Why should these thresholds be different? Because the cost of being wrong is different. Temporarily avoiding a node for a request may be relatively cheap. Starting replica repair may consume significant network and storage resources. Removing a node from cluster membership is an even more consequential decision. A single global timeout forces every decision to share the same risk tolerance. An accrual detector does not — it provides a common measurement, “how improbable is this silence,” and each subsystem decides how much evidence it needs.</p><p>The entire model can now be viewed as one chain, from raw heartbeat history down to three independently governed decisions.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4WLOCMfdgbUEX6COH-guRg.png" /></figure><p>That is the deeper idea behind φ accrual failure detection. A fixed timeout says: silence for N seconds means failure. φ says: this amount of silence is this unlikely given what we know about the node. The first is a deadline. The second is evidence. And once failure detection becomes an evidence-producing mechanism rather than a binary verdict, the system can make different decisions based on different risk tolerances — while continuously adapting those decisions to the behavior of the environment.</p><p><a href="https://paperhub.s3.amazonaws.com/f516fdfa940caa08c679d3946b273128.pdf">https://paperhub.s3.amazonaws.com/f516fdfa940caa08c679d3946b273128.pdf</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=068dded694a1" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Little’s Law Why a Bigger Thread Pool Doesn’t Buy You Throughput]]></title>
            <link>https://medium.com/@gati.sahu/littles-law-why-a-bigger-thread-pool-doesn-t-buy-you-throughput-525de5457f4a?source=rss-fcb9046d516e------2</link>
            <guid isPermaLink="false">https://medium.com/p/525de5457f4a</guid>
            <dc:creator><![CDATA[gati sahu]]></dc:creator>
            <pubDate>Sat, 18 Jul 2026 11:26:15 GMT</pubDate>
            <atom:updated>2026-07-18T11:33:56.363Z</atom:updated>
            <content:encoded><![CDATA[<ul><li>Throughput, concurrency, and latency are related by Little’s Law: Concurrency = Throughput × Latency. To raise throughput without raising latency, the only variable left is concurrency.</li><li>A platform thread is an expensive proxy for one unit of concurrency — roughly a megabyte of reserved stack and a kernel-scheduled entity. Past a certain pool size, adding more of them adds scheduling overhead faster than it adds usable concurrency.</li><li>Virtual threads change the cost side of the equation, not the math. The mechanism is stack chunks: a virtual thread’s stack is copied to the heap when it parks and copied back when it resumes, so a parked virtual thread costs a few hundred bytes instead of a reserved OS thread.</li><li>The scheduler underneath is the common ForkJoinPool, running in FIFO mode since Java 21. Understanding its work-stealing deques explains why this scales without a global lock, and where the technique stops helping — compute-bound work.</li></ul><p><strong>The pattern</strong></p><p>A common response to an I/O-bound service falling behind under load is to increase the thread pool — take a saturated pool, double it, and expect throughput to recover. It sometimes works. Just as often, doubling a pool from 200 threads to 400 makes latency worse: more timeouts, slower responses, and a JVM that spends a measurable share of every second deciding which of four hundred threads gets to run next.</p><p>The goal — more throughput — is correct. The lever being pulled usually isn’t.</p><p><strong>Little’s Law, stated precisely</strong></p><p>Little’s Law is a result from queueing theory that holds for any system in steady state, independent of architecture, language, or hardware:</p><pre>Concurrency = Throughput × Latency</pre><p>The average number of requests in flight equals the rate at which the system completes them, multiplied by how long each one takes. Rearranged into the form that matters for capacity planning:</p><pre>Throughput = Concurrency / Latency</pre><p>If per-request latency is held constant, throughput scales only with concurrency: the number of requests genuinely in flight at the same time. This is not a metaphor — it is the entire lever available once latency is fixed.</p><p><strong>Why more platform threads don’t equal more concurrency</strong></p><p>The failure mode above comes from conflating “threads” with “concurrency.” A platform thread is not concurrency itself; it is an OS-managed mechanism for achieving it, and that mechanism has a fixed, non-trivial cost: roughly a megabyte of reserved stack per thread, a kernel-scheduled entity, and a context switch every time the scheduler reassigns a core. Four hundred platform threads contending for eight or sixteen cores do not provide four hundred times the concurrency of eight cores. They provide the parallelism of eight cores, plus four hundred threads’ worth of scheduling overhead layered on top of it. Beyond a certain pool size, each additional thread does not add capacity to the Little’s Law equation — it taxes the threads already doing useful work.</p><p><strong>What virtual threads change: stack chunks</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7jGypFWTfZltETAdorF10Q.png" /></figure><p>Ron Pressler’s JVMLS 2023 talk, <em>Continuations Under the Covers</em>, walks through how the JVM actually implements virtual threads, and the mechanism is deliberately unglamorous. When a virtual thread would block, the JVM copies the relevant slice of its stack out of the carrier thread and into a heap-allocated object called a stack chunk. When the operation it was waiting on completes, that chunk is copied back onto whichever carrier thread is available, and execution resumes at the exact point it left off — same stack shape, same local variables, no callback, no hand-written state machine.</p><p>The consequence: a parked virtual thread costs a few hundred bytes on the heap, not a reserved OS thread sitting idle. This makes it practical to hold a hundred thousand mostly-waiting virtual threads in flight, mounted onto a small pool of carrier threads — typically sized to the CPU core count — only while they are actually running. The carrier pool handles the genuinely scarce resource, CPU time; the waiting state, which is most of an I/O-bound request’s life, costs almost nothing to hold open. That is the mechanism that lets Little’s Law be taken at its word: concurrency increases without a corresponding increase in per-request latency.</p><p><strong>The scheduler: ForkJoinPool</strong></p><p>The stack-chunk mechanism explains how a virtual thread’s state is stored while parked. It does not explain which carrier thread picks it up next — that is the job of the common ForkJoinPool, which has been the default scheduler for virtual threads since Java 21, running in FIFO mode rather than the LIFO mode it uses for ordinary fork/join tasks.</p><p>This scheduler is why the mechanism scales without a global lock in the hot path. Each carrier thread — a plain platform thread, sized by default to Runtime.availableProcessors() — owns a private double-ended work queue rather than sharing one. A runnable virtual thread is pushed onto a queue as a task. An idle carrier steals work from the opposite end of another carrier&#39;s queue rather than contending on a shared structure, so two carriers picking up work concurrently rarely interfere with each other. Mounting a virtual thread is a carrier thread pulling that task off a queue and resuming its stack chunk; unmounting is the same carrier returning to the pool&#39;s rotation the instant that virtual thread parks, instead of holding an entire OS thread hostage to one slow socket read.</p><p>This also marks the boundary of the technique. For CPU-bound work, none of this adds capacity: a carrier pool sized to the core count can run only as many things in parallel as there are cores, regardless of how many virtual threads are queued behind them — Little’s Law still caps throughput at what the carriers can process. The gain is specific to I/O-bound concurrency, where a virtual thread spends most of its lifetime parked rather than running, and a parked virtual thread occupies no carrier at all. For the case where a carrier must genuinely block — most commonly a synchronized block wrapping blocking I/O, which prevents a clean unmount — the pool can compensate by spinning up an additional carrier temporarily, via the same ManagedBlocker mechanism fork/join tasks have used to avoid starving the pool during a blocking call.</p><p><strong>Same interface, different economics</strong></p><pre>// platform threads: concurrency hard-capped at pool size<br>ExecutorService fixed = Executors.newFixedThreadPool(200);</pre><pre>// virtual threads: one per task, unmounted while waiting<br>ExecutorService virtual = Executors.newVirtualThreadPerTaskExecutor();</pre><p>Both satisfy ExecutorService. Both accept the same Runnable, the same Callable, the same submit() call. The difference is entirely in what happens underneath. The fixed pool caps concurrency at 200; the 201st task queues, and every task behind it inherits the wait time of everything ahead of it. That queueing delay is added directly to latency, which by Little&#39;s Law reduces throughput even though nothing about the downstream dependency changed. The pool, in that scenario, is the bottleneck rather than a safeguard.</p><p>The virtual-thread executor has no such ceiling by construction. Concurrency rises to meet actual demand, bounded eventually by memory or by what the downstream dependency can absorb — not by a fixed number set during capacity planning. Latency per request tracks what the downstream call actually takes, since a virtual thread is not competing with hundreds of siblings for a CPU core while it sits idle waiting on a socket.</p><p><strong>Implication</strong></p><p>Increasing a thread pool does not increase throughput once the pool itself is the bottleneck; it increases scheduling overhead on threads that were already productive. The actionable lever, per Little’s Law, is concurrency held at constant latency — and the reason virtual threads deliver that is a specific, well-defined mechanism: cheap stack storage via stack chunks, scheduled by a work-stealing pool that only occupies a carrier while a task is genuinely running. For I/O-bound systems, this changes the achievable throughput ceiling substantially. For CPU-bound systems, it changes nothing — the ceiling was always the core count, and Little’s Law does not negotiate.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=525de5457f4a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Why State-Aware Systems Outperform Stateless Ones]]></title>
            <link>https://medium.com/@gati.sahu/why-state-aware-systems-outperform-stateless-ones-de8f46844ccc?source=rss-fcb9046d516e------2</link>
            <guid isPermaLink="false">https://medium.com/p/de8f46844ccc</guid>
            <dc:creator><![CDATA[gati sahu]]></dc:creator>
            <pubDate>Sat, 27 Jun 2026 08:14:30 GMT</pubDate>
            <atom:updated>2026-06-27T08:14:30.186Z</atom:updated>
            <content:encoded><![CDATA[<p><em>The reflex to “make it stateless” usually just moves the state somewhere you can see it less and hammer it more. Vimeo’s video packager is a clean lesson in why locality wins — and how to keep it from blowing up.</em></p><p>Somewhere along the way, “stateless” stopped being an engineering choice and became a moral position. Stateless is clean. Stateless scales. Stateless is what you put on the architecture diagram when the principal engineer is in the room. State, on the other hand, is the thing you apologize for.</p><p>I want to push back on that, because the reflex costs teams real latency and real money, and it usually rests on a misunderstanding of what “stateless” actually bought them.</p><p>Here’s the uncomfortable part: when you make a service stateless, you don’t delete its state. You relocate it. The session, the cache, the running aggregate, the dedup table — it all still exists. You moved it out of the process and into a database, a Redis cluster, a shared cache. And now every request that used to read state from local memory in nanoseconds reads it across the network in milliseconds, and that shared store you leaned on becomes the busiest, hottest, most failure-sensitive thing you own.</p><p>The honest framing was never stateless versus stateful. It’s <em>where does the state live, and how do requests find it.</em></p><h3>A real production case: Vimeo’s packager</h3><p>Vimeo runs a dynamic video packager called Skyfire that serves close to a billion streaming requests a day. When a player asks for the 37th segment of a video, Skyfire pulls the exact bytes from the source MP4, reshapes them into DASH or HLS on the fly, and ships them back. To do that it first builds an <em>index</em> of the file — where every keyframe and packet sits. Building that index costs an HTTP fetch and real CPU, sometimes a lot of it for long videos. The same video gets requested over and over, so the obvious move is to build the index once and cache it.</p><p>The question is <em>where</em>. And this is where the stateless-versus-stateful debate stops being abstract.</p><p>Vimeo’s first design was unapologetically stateful: cache each index in memory on the server that built it, and use consistent hashing in the load balancer to send every request for a given video to the same server. Same video, same box, warm cache. Beautiful — when it works.</p><p>It didn’t entirely work. Consistent hashing spreads <em>keys</em> evenly, but it has no idea that some videos are wildly more popular than others. A handful of hot videos all hash to the same unlucky servers, those servers melt, and playback suffers. That’s the dirty secret of naive key-affinity: locality and load balance are in tension, and popular content breaks the tie the wrong way.</p><p>So Vimeo did what most teams do at this point. They retreated to stateless. They switched the balancer to “least connections” — spread requests evenly, ignore affinity — and added a shared memcached layer so any server could fetch an index another server had already built. Load got even. Everyone was happy. And the price of that happiness was a shared cache pushing 8 gigabits a second at peak, each memcached node hauling 400–500 Mbit/s, sitting square in the critical path as a single point of failure.</p><p>That’s the trade nobody draws on the diagram. “Stateless” here didn’t remove the state. It centralized it, put a network hop in front of it, and made it the thing most likely to take the service down.</p><h3>The fix wasn’t to pick a side</h3><p>The interesting move came when an engineer stopped treating it as stateless-or-stateful and asked the real question: <em>can I keep the locality and bound the hotspot?</em></p><p>The answer was a 2016 result from Google researchers — Vahab Mirrokni, Mikkel Thorup, and Morteza Zadimoghaddam — called <strong>consistent hashing with bounded loads</strong>. It’s almost embarrassingly simple once you see it. You keep consistent hashing exactly as before, but you give every server a capacity: a ceiling of, say, 1.25× the current average load. You route each request to its hashed-to server as usual — unless that server is already at capacity, in which case you walk to the next server on the ring, and the next, until you find one with room.</p><p>That one rule buys a surprising amount:</p><ul><li>When nothing is overloaded, it behaves <em>exactly</em> like plain consistent hashing — full locality, warm local caches.</li><li>No server can run past its capacity factor, so the hot-video meltdown simply can’t happen.</li><li>The overflow is deterministic: a popular video always spills to the same “second choice” server, so even the spillover stays cacheable.</li><li>But different videos spill to <em>different</em> second choices, so the overflow spreads instead of piling onto one poor box.</li></ul><p>There’s one knob, <em>c</em>. Push it toward infinity and you have pure consistent hashing — maximum locality, maximum hotspots. Pull it toward 1 and you have least-connections — maximum balance, no locality. The entire stateless-vs-stateful spectrum collapses into a single dial, and you get to choose where you sit on it.</p><p>Vimeo shipped this into HAProxy; it’s been in mainline since 1.7. Local cache hit rates jumped and stayed high no matter how aggressively autoscaling added or removed servers. Shared-cache bandwidth fell from those 400–500 Mbit/s spikes to comfortably under 100. The single point of failure stopped being scary. Google, separately, put the same algorithm into Cloud Pub/Sub and reported the same kind of uniformity win. Response times, tellingly, didn’t move — the point was never raw speed. It was turning a fragile bottleneck back into headroom.</p><h3>The pattern is everywhere once you see it</h3><p>This isn’t a video-streaming trick. It’s the shape of every well-built stateful system.</p><p>A Kafka consumer group is consistent hashing with bounded loads wearing different clothes: partition by key so related events land on the same consumer, rebalance when membership changes, cap how much any one consumer owns. A Flink job keeps its aggregation state in embedded RocksDB <em>on the same node doing the compute</em>, keyed so each subtask owns a slice — precisely so it never pays a database round-trip per event. Sticky sessions, sharded databases, cache-aware routing in a service mesh — same idea every time. Route by key. Keep the state next to the compute. Bound the worst case. Move as little as possible when the topology shifts.</p><p>So no, stateful is not the enemy. <em>Unbounded</em> state is. Stateful systems with no answer for the hot key, no plan for rebalancing, and no ceiling on any one node — those will hurt you. But that’s a discipline problem, not a reason to shove every byte of state into a shared store and call it architecture.</p><p>The next time someone says “let’s just make it stateless,” ask the only question that matters: <em>where does the state go?</em> Sometimes the right answer really is to externalize it. Often the senior move is the opposite — keep the state where the work happens, and spend your cleverness on routing to it. Vimeo got a billion requests a day to behave by changing one rule in a load balancer. Locality was never the problem. We just needed a ceiling.</p><p>Reference</p><p><a href="https://medium.com/vimeo-engineering-blog/improving-load-balancing-with-a-new-consistent-hashing-algorithm-9f1bd75709ed">https://medium.com/vimeo-engineering-blog/improving-load-balancing-with-a-new-consistent-hashing-algorithm-9f1bd75709ed</a></p><p><a href="https://arxiv.org/pdf/1608.01350">https://arxiv.org/pdf/1608.01350</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=de8f46844ccc" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Beyond Chatbots: Designing Conversational AI That Thinks Before It Acts]]></title>
            <link>https://medium.com/@gati.sahu/beyond-chatbots-designing-conversational-ai-that-thinks-before-it-acts-1cd62ea9fd4e?source=rss-fcb9046d516e------2</link>
            <guid isPermaLink="false">https://medium.com/p/1cd62ea9fd4e</guid>
            <dc:creator><![CDATA[gati sahu]]></dc:creator>
            <pubDate>Sun, 31 May 2026 13:21:16 GMT</pubDate>
            <atom:updated>2026-05-31T13:21:16.025Z</atom:updated>
            <content:encoded><![CDATA[<p>Every engineering team building customer-facing automation eventually hits the same wall. The system works well at launch — a dozen carefully mapped flows, clean decision trees, predictable outcomes. Then the product grows. Edge cases multiply. The support team reports users giving up because the chatbot keeps asking them to “press 1 for billing.” The maintenance backlog accumulates faster than the team can clear it. This is not a failure of execution. It is a failure of architecture.</p><p>Traditional conversational systems are built on two structural assumptions that become liabilities at scale:</p><p><strong>Limited flexibility</strong>: Workflows are tightly coupled to predefined flows, limiting adaptability to dynamic or multi-step scenarios. A user who describes a problem in an unexpected order breaks the state machine. <strong>Poor scalability</strong>: Each new use case requires manual workflow and task creation — leading to duplication, higher engineering effort, and increased risk of inconsistency across flows.</p><p>The deeper issue: these systems are optimized for the questions customers should ask, not the questions they do ask. Natural language is messy. Context spans multiple turns. Intent shifts mid-conversation. Rule-based systems cannot handle this gracefully</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Z6ewvEDJlrqFHCr3TfTvGA.png" /></figure><p><strong>LLM-Powered Conversational AI</strong></p><p>The shift from rule-based to LLM-powered systems is not just a technology upgrade — it is an architectural philosophy change. Instead of encoding knowledge into decision trees, you encode it into context: system prompts, tool descriptions, and example conversations. The model becomes the orchestrator. With an LLM at the center, customers can engage in natural, open-ended conversations. They can describe their issues in their own words, across multiple turns, with full context carrying forward. The model interprets queries more effectively because it maintains a semantic understanding of the entire dialogue — not just the most recent utterance.</p><p><strong>What Changes Architecturally</strong></p><p>The architectural shift involves three fundamental changes to how the system is designed and operated:</p><ol><li><strong>From Hardcoded Flows to Prompt-Driven Orchestration</strong></li></ol><p>Traditional workflows are encoded in code: if-else chains, state machines, or BPMN diagrams. Changing a flow means changing code, testing, deploying. In an LLM-driven system, the workflow logic lives in the system prompt and the tool registry. Adjusting behavior means adjusting text — with iteration cycles measured in minutes, not sprints.</p><p>2. <strong>From Task-Specific Bots to General Reasoning Engines</strong></p><p>A rule-based bot is a collection of specialized handlers. An LLM-powered system is a general reasoning engine constrained by the tools and context you provide. The same model that handles billing inquiries can handle technical troubleshooting and appointment scheduling — because it reasons about the problem, not pattern-matches against a fixed taxonomy.</p><p>3. <strong>From Deterministic to Probabilistic with Guardrails</strong></p><p>This is the key tradeoff. LLMs are not deterministic — the same input may produce slightly different outputs. This requires a reliability strategy: evaluation frameworks to measure quality, guardrails to prevent harmful outputs, fallback mechanisms for low-confidence scenarios, and observability to detect when the system drifts from expected behavior.</p><p><strong>What Is Chain-of-Thought Prompting?</strong></p><p>Chain-of-Thought (CoT) is one of the most impactful prompting patterns in modern AI agent design. At its core, it enables a large language model to reason step-by-step before committing to an answer — rather than jumping directly from a question to a conclusion. The pattern was formalized in a 2022 Google Research paper by Wei et al., which demonstrated that providing LLMs with intermediate reasoning demonstrations dramatically improves their accuracy on complex tasks: arithmetic, commonsense reasoning, and multi-condition logic. The key finding was striking in its simplicity</p><p>Before CoT, models were prompted with a question and expected to produce an answer. With CoT, the prompt includes worked examples where the reasoning process is shown explicitly. The model learns not just what the answer is, but how to arrive at it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qUgIDyCOmLS6aJTBLEf4TA.png" /></figure><p><strong>The Reasoning Loop Architecture</strong></p><p>The practical application of Chain-of-Thought in production systems is a pattern called the reasoning loop — sometimes called ReAct (Reasoning + Acting) in the research literature. The idea is to use the LLM as a reasoning layer that decides which tools to invoke and in what sequence. Tools represent the platform’s existing capabilities: checking order status, retrieving policy documents, sending notifications, escalating to human agents, querying a knowledge base. The LLM does not execute these directly — it decides when to call them and with what parameters, based on its understanding of the user’s request and the conversation so far.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*oJxV_PNRBZKzGenn7ZsEnQ.png" /></figure><p><strong>How the Loop Works, Step by Step Step</strong></p><p>1: <strong>Prepare Context</strong> Before the loop begins, context is assembled: the system prompt (describing the assistant’s role, available tools, and behavioral constraints), the conversation history (all prior turns), and</p><p>any retrieved data (user profile, account status, recent transactions). This context forms the input for the first LLM call.</p><p><strong>2: Ask the LLM for Reasoning</strong> The model receives the full context and is asked: based on what you know so far, do you have enough information to answer the user’s question? If yes, produce the final answer. If no, which tool should you call next to get the missing information? This is where Chain-of-Thought shines. The model generates its reasoning before committing to a tool call. It might reason: “The user is asking about a refund. I need to check the order status first. Then I need to verify whether the item is within the return window. Then I can determine the appropriate response.”</p><p><strong>3: Execute Tool or Return Answer</strong> If the model requests a tool, the orchestration layer executes it and appends the result to the context. The loop repeats. If the model determines it has sufficient information, it produces the final answer — a natural language response that the platform delivers to the user.</p><p>Architecture Design Moving from a prototype to a production-grade LLM-powered conversational system requires careful attention to the components that surround the model. The LLM is the reasoning core — but the architecture that wraps it determines whether the system is reliable, observable, and maintainable at scale.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PoHjwAPvylkzD3AX08jYMg.png" /></figure><p><strong>Layer-by-Layer Breakdown</strong></p><p><strong>API Gateway &amp; Authentication</strong></p><p>All user interactions enter through a gateway that handles authentication, rate limiting, and routing. This layer is also responsible for request validation and abuse prevention — critical when the system is publicly accessible. The gateway should be model-agnostic: if you switch from one LLM provider to another, the gateway should not require changes.</p><p><strong>LLM Orchestration Layer</strong></p><p>This is the heart of the system. The orchestration layer manages the reasoning loop, maintains conversation state, constructs the context for each LLM call, parses tool call requests from the model response, and routes results back into the loop. Frameworks like LangChain, LlamaIndex, or custom implementations can serve this role — the key requirement is deterministic tool routing and robust error handling when tool calls fail.</p><p><strong>Tool Execution Layer</strong></p><p>Each tool is a well-defined function with a clear contract: a name, a description (used by the model to decide when to call it), typed input parameters, and a structured output schema.</p><p>Tools should be idempotent where possible, implement timeouts, and return structured errors that the model can reason about (“order not found” is more useful than a generic 404).</p><p><strong>Data &amp; Memory Layer</strong></p><p>Conversational AI systems require a memory strategy. At minimum: conversation history persistence (so sessions can resume across disconnections), user context retrieval (account data, preferences, recent interactions), and a semantic cache (to avoid calling the LLM for repeated queries with similar intent). At larger scales, a vector store enables retrieval-augmented generation (RAG) — injecting relevant knowledge base content into the context without overwhelming the context window.</p><p><strong>Cross-Cutting Concerns</strong></p><p><strong>Guardrails</strong></p><p>LLMs can produce outputs that are technically correct but inappropriate for the context: too verbose, off-topic, inconsistent with company policy, or — in rare cases — harmful. Guardrails are classification layers that inspect model outputs before they reach the user. They can be implemented with a separate, smaller model trained on policy-relevant examples, or with rule-based filters for high-confidence cases.</p><p><strong>Observability</strong></p><p>Every LLM call, every tool invocation, and every user interaction should be logged with structured metadata: latency, token count, tool name, user intent classification, and a session identifier. This data enables the evaluation framework: offline analysis of conversation quality, A/B testing of prompt changes, detection of intent drift, and measurement of resolution rates versus escalation rates</p><p><strong>Tool Design Principles</strong></p><p>The quality of tool definitions is as important as the quality of the system prompt. The model uses tool descriptions to decide when to call them — ambiguous or overlapping descriptions lead to incorrect tool selection.</p><ul><li>Be specific about scope: “Look up the status of an order given an order ID” is better than “get order information.”</li><li>Define failure modes: Describe what the tool returns when data is not found, so the model can communicate appropriately to the user.</li><li>Avoid tool overlap: If two tools could plausibly be called for the same intent, the model will sometimes choose the wrong one. Consolidate or rename.</li><li>Return context, not just data: Include relevant metadata in tool responses — like whether a policy applies, not just what the policy says.</li></ul><p><strong>Prompt Engineering for Reliability</strong></p><p>The system prompt is the primary lever for controlling model behavior in production. Key elements of a reliable system prompt for a reasoning loop:</p><ul><li>Role definition: Clearly state what the assistant is, what it can and cannot do, and what tone to use.</li><li>Tool usage instructions: Specify when to call tools versus when to answer from context. Prevent the model from hallucinating data that a tool should provide.</li><li>Escalation criteria: Define explicitly when to transfer to a human agent. Ambiguity here leads to under-escalation or over-escalation.</li><li>Reasoning format: Instruct the model to reason before acting. “Think step by step before deciding which tool to call” consistently improves tool selection accuracy.</li></ul><p><strong>Evaluation Framework</strong></p><p>An LLM-powered system without an evaluation framework is a system you cannot safely improve. Every prompt change is a risk without measurement. A minimal evaluation framework includes:</p><ul><li>Golden dataset: A curated set of conversations with known correct outcomes — used to verify that prompt changes do not regress existing functionality.</li><li>Intent classification accuracy: Does the model correctly identify what the user wants? Measured against human-labeled samples.</li><li>Tool call precision: When the model calls a tool, is it the right tool with the right parameters?</li><li>Resolution rate: What fraction of conversations are resolved without human escalation? Tracked over time to detect drift.</li><li>Latency distribution: P50, P95, and P99 latency for the full reasoning loop — including tool execution time.</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1cd62ea9fd4e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Decouple or Suffer: Why Search Systems Fail at Scale]]></title>
            <link>https://medium.com/@gati.sahu/decouple-or-suffer-search-at-scale-983298058ac3?source=rss-fcb9046d516e------2</link>
            <guid isPermaLink="false">https://medium.com/p/983298058ac3</guid>
            <dc:creator><![CDATA[gati sahu]]></dc:creator>
            <pubDate>Sun, 12 Apr 2026 07:31:06 GMT</pubDate>
            <atom:updated>2026-04-12T07:33:41.639Z</atom:updated>
            <content:encoded><![CDATA[<p>When you start building log search infrastructure, Elastic search is the obvious choice. Full-text search, aggregations, a mature ecosystem, Kibana out of the box. You throw logs at it and it works — right up until the moment it doesn’t.</p><p>What follows is an honest accounting of what breaks in Elastic search at scale, why it breaks the way it does, and the architectural pattern — compute/storage separation — that elegantly solves most of it. Every principle here applies to any system built on top of Lucene, or any search engine that couples its compute and storage concerns together.</p><h3>The fundamental problem: Elastic search couples everything together</h3><p>Before we get into failure modes, you need to understand the original sin. An Elastic search node is simultaneously a:</p><ul><li>Shard host (data storage)</li><li>Indexing engine (write compute)</li><li>Query executor (read compute)</li><li>Cluster coordination participant</li></ul><p>This conflation of responsibilities is convenient when you’re getting started. It becomes catastrophic at scale. Every operation you perform on an Elastic search cluster is now entangled with every other operation. You can’t scale them independently. You can’t fail them independently. And crucially, you can’t reason about their resource contention independently.</p><p>Let’s walk through each failure mode in detail.</p><h3>Problem 1: Adding a node triggers a rebalancing storm</h3><p>This is the one that bites you hardest at 3am. Your cluster is saturated. You add three new nodes. Everything gets worse for the next 45 minutes.</p><p>Here’s the mechanics. Elastic search uses shard allocation to distribute each index’s primary and replica shards evenly across nodes. When you add a node, the cluster master decides it needs to move shards to the new node to achieve balance.</p><p>Moving a shard means transferring its full segment data over the network. A shard holding 50GB of Lucene segments requires 50GB of transfer. During that transfer, the source node is simultaneously serving live queries, indexing new documents, and now shipping 50GB of data over its network interface.</p><p>The cascade is predictable:</p><ul><li>Network bandwidth saturates on nodes shipping shards</li><li>Indexing falls behind because the indexing thread pool is starved</li><li>Queries time out because the query thread pool competes with rebalancing I/O</li><li>Cluster health goes red (shard under replicated) during the move</li><li>If a node dies during this window, the rebalancing storm intensifies</li></ul><p>You can tune cluster.routing.allocation.node_concurrent_recoveries, indices.recovery.max_bytes_per_sec, and a dozen other settings to throttle rebalancing. But throttling just means the storm lasts longer. You&#39;re still sharing resources between live traffic and shard migration. The coupling is the problem.</p><h3>Problem 2: Consumer lag under a traffic spike destroys freshness — and then recovery makes it worse</h3><p>This is the subtlest and most dangerous failure mode. It plays out over hours, and by the time you’re debugging it, you’re already deep in the hole.</p><p>Most production log ingestion pipelines look like this: logs arrive at a Kafka topic, a set of Elastic search indexers consume from that topic, and users query the indexed data. Under normal conditions, the indexers keep pace. Consumer lag is low, data is fresh.</p><p>Now a traffic spike hits. Maybe a deploy caused elevated error rates. Maybe it’s Monday morning and five hundred engineers just started querying the logging dashboard. Ingest volume doubles.</p><p>Here’s what happens step by step.</p><p>First, the indexers fall behind. They’re consuming from Kafka but can’t process fast enough. Consumer lag starts climbing — from seconds, to minutes, to potentially hours.</p><p>Second, you try to help. You add more indexer nodes. But new indexers need Kafka partition assignments. In the default consumer group model, rebalancing the consumer group causes all consumers to pause briefly while partition assignments are renegotiated. You’ve added capacity but caused a pause in all consumers simultaneously.</p><p>Third, the new indexers come online and try to catch up. Heavy catch-up indexing triggers frequent Lucene segment merges. Segment merges are I/O heavy and compete with query serving. Your query latency degrades exactly when your users are most actively searching — because this is an incident and everyone is in the logs.Fourth, the spike has also caused disk pressure — incident logs are verbose. Some nodes hit their disk watermarks. Elasticsearch stops allocating shards to those nodes, which triggers another rebalancing event.</p><p>Fifth, the lag finally clears — but now you have a cluster that has been running hot for hours, with elevated merge pressure and potentially recently moved shards. The “recovery” from the spike has itself caused damage.</p><p>The core of this problem: <strong>the compute for catching up on lag is the same compute that serves live queries.</strong> When you throw more resources at lag recovery, you rob from live query performance. There is no way to say “use these CPUs for lag recovery and leave those CPUs alone for queries.”</p><p>Here’s what that failure cascade looks like. Notice how tightly coupled the failure domains are — there is no isolation boundary anywhere.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cT-Bc9wylT4UMaFIU-EzrA.png" /></figure><h3>Problem 3: Hot shard and hot node concentration</h3><p>Elastic search distributes shards based on count, not on query load or ingest load. In multi-tenant or uneven workload environments, a node can end up hosting two popular shards while another node hosts six quiet ones. The busy node is overwhelmed; the quiet nodes are idle.</p><p>You can address this with custom allocation filters, rack awareness settings, and shard rebalancing triggers — but these are all manual interventions. The cluster has no concept of “this shard receives 80% of the queries.” It just counts shards.</p><p>When a hot shard is overwhelmed, the only recourse is to increase replica count (more copies means more nodes can serve the query) or shrink shard size (add more shards, requiring reindexing). Both are expensive, slow, and typically require downtime windows.</p><h3>Problem 4: Snapshot and restore is dangerously slow</h3><p>Elasticsearch’s native snapshot API backs up shard data to object storage. This is the right thing to use. But restoration is painfully slow because restoration and query serving share the same I/O path.</p><p>When you restore a shard, the node downloads the shard data. During download, that node serves queries against partial data. You cannot parallelize restoration across more nodes than you have shards — if you have a 30-shard index, only 30 nodes work on restoration simultaneously. You can’t throw fifty nodes at a 30-shard restore.</p><p>This means historical data recovery is bottlenecked by a count chosen at index creation time, decided before you knew anything about future restoration requirements.</p><h3>The root cause across all four problems</h3><p>Every one of these problems traces back to the same architectural decision: <strong>compute and storage are coupled on the same nodes.</strong></p><p>When you add nodes to scale, you’re adding compute and storage simultaneously — and data has to move to achieve balance.</p><p>When indexing falls behind, catch-up work and query serving fight for the same CPU on the same nodes.</p><p>When you want historical restoration, you’re constrained by shard count, because shards are simultaneously the unit of storage and the unit of compute parallelism.</p><p>The fix is conceptually clean: separate them.</p><h3>The solution: disaggregate compute from storage</h3><p>The architectural insight is simple to state: <strong>make storage cheap, durable, and infinite. Make compute elastic, stateless, and independently scalable.</strong></p><p>In practice this means your indexed data lives in object storage — S3 or equivalent. Compute nodes have no responsibility for the durability of data. They can come and go freely because the data they’re working with is always recoverable from object storage.</p><p>This is not a new idea. Snowflake, Rockset, and ClickHouse Cloud all use variants of this architecture. The specific implementation we’ll walk through is based on the Aggregator/Leaf/Tailer pattern described by Rockset, adapted for log and trace data at production scale.</p><p>Let me walk through each component and what problem it solves.</p><h3>The component architecture</h3><p>The system has six distinct roles. Each is independently scalable and each has a clean failure domain.</p><p><strong>Preprocessors</strong> sit at the ingest edge. They consume from your HTTP ingest endpoint, validate messages — data types, timestamps, schema — apply per-service rate limits, and partition messages into Kafka. Scaling preprocessors is purely horizontal: add instances, update the instance count configuration, and load distributes automatically. No data migration, no partition rebalancing, no cluster-wide coordination. Preprocessors are stateless.</p><p><strong>Kafka</strong> provides the durability buffer between ingest and indexing. This is the key architectural decision that enables recovery. Because messages sit in Kafka with configurable retention, an indexer that falls behind, crashes, or gets added to the cluster can always replay from any offset. Kafka is the source of truth for “what needs to be indexed,” not the indexers themselves.</p><p><strong>Indexers</strong> are single-responsibility compute: They read from a specific Kafka partition, index documents into a Lucene index on local disk in a bounded unit called a chunk, and upload completed chunks to object storage. Once a chunk is uploaded and registered in the cluster metadata, the indexer deletes its local copy. Indexers are stateful in-flight but not stateful at rest — their state is always reconstructible from Kafka (the log) and object storage (the indexed data).</p><p>This is where the lag problem gets solved in a fundamental way. When an indexer falls too far behind the current Kafka head — more than a configurable offset threshold — it creates a recovery task in the cluster coordination layer, jumps to the current head, and resumes indexing live data. A separate pool of recovery nodes picks up the recovery task and indexes the gap independently. Live indexing freshness is never sacrificed to catch-up work, because they are literally different processes on different nodes with different resources.</p><p><strong>Recovery nodes</strong> are purpose-built for catch-up work. They don’t serve queries. They are tuned for maximum indexing throughput. They autoscale based on CPU utilization — when lag creates recovery work, the recovery pool grows; when recovery is done, it shrinks. This is the key design: catch-up compute is elastic and completely isolated from the live query compute path.</p><p><strong>Cache nodes</strong> serve historical queries. They download completed chunks from object storage onto local disk and serve Lucene queries against them. A cluster manager assigns specific chunks to specific cache nodes. When a cache node comes online, it checks its assignment and downloads the relevant chunks. When it goes offline, the manager reassigns its chunks to other cache nodes, which download from object storage. The data is never lost — it is always in object storage. The cache layer is a warm disk tier on top of cold object storage.</p><p>Adding cache capacity is a zero-disruption operation: provision nodes, the manager assigns chunks, they download from object storage, they become live for queries. No data movement between existing nodes. The I/O burden falls entirely on the new nodes downloading from object storage. Existing nodes serving live queries are completely unaffected.</p><p><strong>Query nodes</strong> are fully stateless scatter-gather coordinators. For a given query, the query node identifies which partitions hold data for the requested service and time range, identifies the snapshots produced by those partitions, picks one replica of each snapshot — preferring a non-live cache node over a live indexer — fans the query out across all relevant nodes in parallel, and merges the results. Query nodes can scale up and down at any time with no operational ceremony.</p><p>A cluster manager backed by ZooKeeper (or equivalent distributed coordination) maintains all the metadata: chunk locations, replica assignments, cache node states, recovery tasks, partition-to-service mappings. Its only job is coordination — not data, not compute.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tTZF0AeB8bM6EIJfxdFRRQ.png" /></figure><h3>How each Elasticsearch problem is solved by this design</h3><p>Let’s be precise about the mapping.</p><p><strong>The rebalancing storm when adding nodes</strong> — solved by making all compute stateless. When you add cache nodes, they download chunk assignments from object storage. Existing cache nodes don’t move any data. The new nodes bear the I/O cost entirely themselves. Existing nodes serving live queries are completely unaffected. Adding indexer nodes requires adding Kafka partitions and updating partition assignments — indexers read from Kafka, not from each other.</p><p><strong>Consumer lag cascading into query degradation</strong> — solved by the dedicated recovery node tier. When an indexer detects it’s too far behind — specifically, when current_head - last_indexed_offset exceeds a configurable threshold — it creates a recovery task in ZooKeeper specifying the start and end offsets it is skipping. It then jumps to the current head and resumes live indexing immediately. The cluster manager assigns the recovery task to a free recovery node. Recovery nodes are CPU-autoscaled — they spin up during high-lag situations and back down when caught up. Their I/O and CPU burden never touches the indexer or cache nodes. Query freshness degrades only by the amount of lag at the moment of detection, then heals as recovery completes. The two workloads are physically separate.</p><p><strong>Hot shard concentration</strong> — solved by the chunk model. A chunk is a bounded unit of indexed data, configurable by size or offset range. When a chunk is full, the indexer uploads it and starts a new one. The cluster manager assigns replicas of chunks to cache nodes accounting for available capacity. Hot time ranges can be served by more cache replicas simply by increasing the replica count for those snapshots. You can scale up query replicas for hot data without touching the indexing tier at all.</p><p><strong>Slow snapshot and restore</strong> — object storage is the primary store, not a backup. Restoration of historical data means pointing more cache nodes at older chunks in object storage. When a user queries data older than the hot retention window, the cluster manager creates restore replicas and assigns them to a reserved pool of cache nodes. Those nodes download the chunks and become live for queries. Since this is a separate pool, historical restore work does not compete with live query serving. And the parallelism ceiling is the number of chunks, not the number of shards — which can be made very high by choosing a small chunk size at indexing time.</p><h3>The chunk lifecycle in detail</h3><p>The indexer lifecycle is worth understanding precisely because it is the heart of write-path correctness.</p><p>When an indexer starts, it looks up the most recent snapshot published for its assigned partition. If the gap between that snapshot’s last offset and the current Kafka head is within the configurable threshold, it resumes from the snapshot offset. If the gap is too large, it creates a recovery task for that range and jumps to the head. No data is lost — it is deferred to the recovery tier.</p><p>During normal operation, the indexer maintains exactly one active chunk — a Lucene index open for both reads and writes on local disk. The indexer also exposes a query endpoint, allowing query nodes to reach in-flight data before it is uploaded to object storage. This is how live data — seconds-old logs — is queryable even before it has been committed to durable storage.</p><p>When a chunk reaches its size or time threshold, the indexer closes it for writes, marks it read-only, uploads it to object storage, and registers a snapshot record with the cluster manager. The cluster manager, seeing the new snapshot, runs replica creation — it creates replica metadata records pointing at the snapshot — and the cache assignment protocol assigns those replicas to free cache nodes.</p><p>The indexer retains the read-only chunk locally for a configurable period (to serve queries before cache nodes have finished downloading it), then runs a cleaner task that removes it. At that point, the chunk lives exclusively in object storage, served by cache nodes. The indexer node’s local disk usage stays bounded regardless of total data volume.This is the clean handoff that Elasticsearch cannot do. The unit of work — a chunk — has a defined lifecycle with a start, an upload, a handoff, and a cleanup. In Elasticsearch, shards live indefinitely on whatever node the cluster has assigned them to, moving unpredictably as the cluster rebalances.</p><h3>The query path: scatter-gather across tiers</h3><p>Query nodes use metadata from the cluster manager to build their query plan. For each query the protocol is:</p><ol><li>Identify which Kafka partitions serve the requested service and time range.</li><li>Identify the snapshots produced by those partitions that overlap the time range.</li><li>For each snapshot, pick one replica — preferring a non-live cache node replica over a live indexer replica, since cache nodes serve from disk without competing write work.</li><li>Scatter the query across all selected replicas in parallel.</li><li>Gather and merge responses, then return.</li></ol><p>Because query nodes are stateless and hold no data, they scale up and down at any time. A query node going down mid-flight causes in-flight queries to fail, which the client retries — there is no shard state to recover, no reassignment to coordinate. The query tier exposes an OpenSearch-compatible API, so Grafana and Kibana connect without modification.</p><h3>What you give up</h3><p>This architecture is not free. Understanding the tradeoffs is as important as understanding the benefits.</p><p>Document mutability is gone. This is an append-only system. Lucene’s update model — delete plus re-insert — is expensive on immutable chunks. If you need to update or delete indexed documents, you need a compaction layer or a separate mutable index for recent data.</p><p>You now depend on object storage availability and throughput. The cache layer absorbs most reads, but cold data access and new cache node startup are gated by object storage throughput. In practice this is manageable — S3 is extremely reliable — but it is a dependency you did not have when everything was on local disk.</p><p>The operational model has more moving parts at first glance. Six distinct component types instead of one. You need to understand chunk assignment, replica lifecycles, recovery tasks, and distributed coordination metadata. The payoff is that each component is individually simple and independently operable — but the learning curve is real.</p><p>Strong consistency during reads requires care. A query spanning live indexer data and historical object-storage-backed cache data stitches together two sources. The query node handles this merge, but architects need to understand the semantics: indexers serve their active chunks; cache nodes serve older chunks; time ranges are designed not to overlap. This holds under normal operation, but edge cases around chunk boundary times require explicit handling.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=983298058ac3" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The F-16 Lesson EveryEngineer Misses]]></title>
            <link>https://medium.com/@gati.sahu/the-f-16-lesson-everyengineer-misses-b30d6997fc8f?source=rss-fcb9046d516e------2</link>
            <guid isPermaLink="false">https://medium.com/p/b30d6997fc8f</guid>
            <dc:creator><![CDATA[gati sahu]]></dc:creator>
            <pubDate>Sun, 29 Mar 2026 08:48:36 GMT</pubDate>
            <atom:updated>2026-03-29T08:48:36.850Z</atom:updated>
            <content:encoded><![CDATA[<p>There is a particular kind of failure that is invisible until it’s too late. Not the failure of a system crashing under load, or a bug that corrupts data — those are recoverable. I mean the failure of solving the wrong problem, perfectly. Building a machine that does exactly what was asked, while delivering none of what was needed.</p><p><strong>Everyone Wanted Mach 2.5. Nobody Asked Why.</strong><br>The next-generation fighter must reach Mach 2 to 2.5. Every major defense contractor wrote proposals around it. Every budget meeting assumed it. It had the weight of consensus, which is often confused with the weight of truth.</p><p>Then a chief designer named Harry Hillaker, working alongside the strategist John Boyd, asked a question that was somehow considered rude: when do we actually need Mach 2.5?</p><p>The data was damning. Supersonic flight accounted for less than 5% of total flight time across the entire active fleet. Pilots engaged enemies at subsonic speeds. Dogfights were decided by turn rate, acceleration, and pilot visibility — not top speed. The Mach 2.5 requirement was not operationally derived. It was emotionally appealing.</p><p>Boyd’s Energy-Maneuverability theory reframed the entire problem. The real requirement was not “go fastest.” It was “win dogfights.” That reframing produced one of the most consequential design decisions in aviation history: the F-16 Fighting Falcon. Lighter, cheaper, more agile, and more effective in actual combat than anything designed around the Mach 2.5 specification.</p><p>The lesson is not about jets. It is about the difference between a stated requirement and a real one — and what happens when you confuse the two.</p><p><strong>Kafka’s Mach 2.5 Moments</strong><br>The language changes, but the pattern is identical. Somebody writes a requirement that sounds rigorous, impresses the room, and goes completely unquestioned. Here are the four most common Kafka versions of Mach 2.5:</p><p>The Phantom Requirements<br>“The system must handle 1,000,000 events/sec.” · “Latency must be under 10ms end-to-end.” · “We need exactly-once semantics everywhere.” · “We must use Flink + Spark for real-time processing.”</p><p>These statements feel like engineering. They have numbers. They use correct terminology. But apply the Hillaker test to each one: when do we actually need this?</p><p>“1M events/sec” as a hard requirement. Their actual production peak was 200,000 events per second. Their average load was 20,000. Ninety-nine percent of their uptime operated below 50,000 events per second. They had over-engineered by a factor of twenty — paying for infrastructure, operational complexity, and cognitive overhead they would never need.</p><p><strong>Five Questions Before Writing a Single Line of Config</strong><br>The Fighter team did not guess their way to the F-16. They followed a disciplined methodology for converting stated requirements into real ones. Here is the engineering equivalent — five questions that should precede every Kafka architecture decision.</p><p><strong>1. Challenge the requirement directly</strong><br>Ask “why is this needed?” until you reach a business outcome, not another technical metric. “1M QPS” is not an outcome. “The checkout flow must not degrade during flash sales” is an outcome. These produce radically different designs.</p><p><strong>2. Quantify actual usage — not theoretical maximums</strong><br>Supersonic usage was under 5% of flight time. What is your real load distribution? Pull actual percentile data. The 99th percentile peak matters, but the design should not be held hostage by it if the 50th percentile is 20x smaller.</p><p><strong>3. Translate from feature to outcome</strong><br>Every technical requirement should map to a business outcome. “Exactly-once semantics” maps to “no business-critical duplicate processing.” These are not the same design problem, and the second one has cheaper solutions.</p><p><strong>4. Make the hidden costs visible</strong><br>Every Kafka feature carries a weight penalty. The F-16 was designed lighter precisely because they rejected requirements that added weight without adding combat effectiveness. Make your team price every requirement in operational complexity, not just infrastructure cost.</p><p><strong>5. Optimize for the dominant use case</strong><br>The F-16 was optimized for dogfights — the scenario that determined outcomes, not the scenario that sounded impressive. Design your Kafka pipeline for your p50 traffic pattern, with headroom for your p99. Do not design for theoretical edge cases as the primary constraint.</p><p><strong>What Over-Engineering Actually Costs</strong><br>The Mach 2.5 aircraft that never became the F-16 would have been heavier, more expensive, less agile, and harder to manufacture in sufficient numbers. The engineers building it would have been solving an impressive problem incorrectly framed. Here is the direct Kafka equivalent:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*n5X4ImxdE0cpWsQJrYDu-Q.png" /></figure><p><strong>Redefining the Problem, Not Optimizing the Solution</strong><br>The most important insight from the F-16 program is one that rarely appears in engineering retrospectives: the team did not optimize an existing solution. They redefined the problem.</p><p>There is a meaningful difference between these two modes of work. Optimizing an existing solution — making the Mach 2.5 aircraft lighter, cheaper, more reliable — would have produced a better Mach 2.5 aircraft. Still the wrong answer, executed more efficiently. Redefining the problem meant asking what air combat effectiveness actually required, then building backwards from that answer.</p><p>Software architecture works identically. The engineer who optimizes a Kafka pipeline for 1M QPS is doing good work on the wrong problem. The architect who asks why the system needs 1M QPS — and discovers the actual peak is 200K — is doing the work that actually matters.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b30d6997fc8f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Head-of-Line Blocking in Kafka]]></title>
            <link>https://medium.com/@gati.sahu/head-of-line-blocking-in-kafka-58ea9da64a58?source=rss-fcb9046d516e------2</link>
            <guid isPermaLink="false">https://medium.com/p/58ea9da64a58</guid>
            <dc:creator><![CDATA[gati sahu]]></dc:creator>
            <pubDate>Sun, 08 Mar 2026 07:03:35 GMT</pubDate>
            <atom:updated>2026-03-08T07:03:35.900Z</atom:updated>
            <content:encoded><![CDATA[<p>In any distributed system that processes messages asynchronously, there is one failure mode that engineers fear above all others: the completely stuck consumer. Unlike a crashed service or a network outage — both of which are loud, visible, and trigger alerts — a stuck consumer is quiet. It looks alive. It is connected. It just isn’t making progress.</p><p>This post explores exactly that problem — Head-of-Line (HOL) Blocking — in the context of a push-based consumer proxy sitting between Apache Kafka and downstream microservices. We will cover what it is, why it happens, how to detect it automatically using observable system signals, and how to resolve it without causing data loss.</p><p><strong>The Problem: A Consumer That Looks Alive But Is Dead</strong></p><p>In any Kafka consumer pipeline, one failure mode stands above the rest in its danger: the completely stuck consumer. It does not crash. It does not raise loud alerts. From the outside it looks healthy — connected to the broker, heartbeating normally. But it is making no progress whatsoever.</p><p>This is Head-of-Line (HOL) Blocking. A single message at the front of the queue that cannot be processed holds back every message behind it — even messages that are perfectly ready to complete.</p><p>To understand it fully, we need to understand two things: why Kafka’s ordering guarantee creates this risk, and what classes of failure cause messages to get permanently stuck.</p><p><strong>Kafka’s Ordering Guarantee and Why It Creates HOL Risk</strong></p><p>Kafka guarantees in-order delivery within a partition. A consumer thread cannot commit offset N+1 until offset N has been committed. This is a broker-level contract — it cannot be bypassed.</p><p>For simple, fast-processing use cases this guarantee is invisible. But in a real production pipeline, processing times are uneven. Consider an order processing platform where the billing service charges customers via UPI, Credit Card, or Wallet.</p><p><strong>Order_1</strong> uses UPI — the UPI gateway is currently under high latency. <strong>Order_2</strong> uses Credit Card — responding in under 100ms, fully ready to complete.</p><p>Both messages land in the same partition. The consumer thread processes Order_1 first — and waits. Order_2 cannot start because Order_1 has not committed. The partition throughput collapses to the speed of the slowest message, regardless of how fast every other message could run.</p><p><strong>Poison-Pill Messages</strong></p><p>A poison-pill message is one that always fails — it throws an exception on every attempt. Without mitigation, the consumer thread retries the same message in an infinite loop. Kafka’s ordering guarantee means no message behind the poison pill can be processed. The consumer is permanently stuck until an engineer manually advances the offset.</p><p><strong>The In-Process Baseline: Out-of-Order Commit and DLQ</strong></p><p>The standard in-process solution addresses both of these. Out-of-Order Commit allows each message’s offset to be tracked independently in a Sequence HashMap. Worker threads process messages in parallel, and a background Offset Commit Thread periodically commits the lowest contiguous committed offset back to Kafka — satisfying the broker’s ordering requirement without serializing the actual processing work.</p><p>When a message fails past its retry limit, a Dead-Letter Queue (DLQ) catches it — routing it to a separate topic for inspection while allowing the main pipeline to advance.</p><p>This combination handles the common HOL cases well. But when a Consumer Proxy enters the picture, a new class of failure emerges that the DLQ alone cannot catch.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lZpVhzESRUNiCOdRlVMUoA.png" /></figure><p><strong>The Out-of-Order Commit Tracker</strong></p><p>The Consumer Proxy processes messages from a single partition in parallel across multiple worker threads. Since Kafka requires ordered offset commits, the proxy maintains a fixed-size data structure per partition — the out-of-order commit tracker — that records the status of every in-flight offset.</p><p>Each slot in the tracker holds one of three states:</p><ul><li><strong>PENDING</strong> — the message has been dispatched to a worker but not yet resolved.</li><li><strong>COMMITTED</strong> — the message was processed successfully and its offset is safe to commit.</li><li><strong>CANCELED</strong> — the message was routed to the DLQ; this slot is treated as done for offset advancement purposes.</li></ul><p>The tracker acts as a sliding window over the partition’s offset space. The window can only advance when the slot at the head transitions out of PENDING. If the head slot is stuck at PENDING — for any reason — the window cannot move. No new messages can be fetched. The partition is completely stopped.</p><p><strong>The core tension</strong></p><p>Out-of-Order Commit exists precisely to prevent HOL blocking — messages behind a slow one can still commit. But a fail-in-transit message bypasses all the application-level commit paths. It stays PENDING forever, and eventually fills the entire tracker window. When the window is full and nothing can advance, Out-of-Order Commit itself is blocked.</p><p><strong>Detection: Reading the Blocking Signature</strong></p><p>HOL blocking has a specific, detectable signature in the tracker’s state. The key insight is that blocking is observable before the consumer is fully stuck — because the tracker’s utilization and uncommitted ratio tell you exactly what kind of situation you are in.</p><p><strong>Signal 1 — Tracker Utilization</strong></p><p>If the tracker still has empty slots, the pipeline can keep moving. New messages are being fetched, new slots are being consumed, and there is no crisis yet. High utilization — the tracker being nearly full — is the first necessary condition for HOL blocking. Below a certain threshold, the problem has not yet materialized.</p><p>Threshold: Tracker utilization &gt; <strong>90%</strong></p><p><strong>Signal 2 — Percentage of Uncommitted Offsets</strong></p><p>This is the signal that separates a busy pipeline from a blocked one, and it is counterintuitive.</p><p>Imagine the tracker is 95% full. In one scenario, 50% of its slots are still PENDING — lots of messages are actively being processed. That is a healthy, busy pipeline. In another scenario, 95% of the tracker is full and only 1% of slots are PENDING. Almost everything is done — but a tiny number of slots near the head cannot commit.</p><p>The fewer the uncommitted slots in a near-full tracker, the higher the probability of HOL blocking. This follows directly from the definition: HOL blocking is a small number of messages blocking a large number of already-completed messages. Low uncommitted percentage in a full tracker is the signature.</p><p>Threshold: Uncommitted offsets &lt; <strong>2% of tracker capacity</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*E9kU1Yqgs9iETc0JARosmw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QM5BAL-y797Gj4fVR2ajWA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qjYq4ChLXeLwGCJgsoD2Dw.png" /></figure><p>The order of these four steps is not arbitrary. Changing the sequence breaks the safety guarantee:</p><ul><li><strong>CANCELED before COMMITTED</strong> — prevents any new delivery attempt from starting in the gap between canceling the service call and marking the offset done. Without this, a race condition can cause duplicate processing.</li><li><strong>DLQ write before COMMITTED</strong> — if the DLQ write fails, the procedure halts and does not proceed to COMMITTED. Marking the offset committed without a successful DLQ entry means the message disappears with no record — that is real, unrecoverable data loss.</li><li><strong>Service call cancellation before COMMITTED</strong> — in-flight network calls might still complete after the offset is marked committed. Canceling them first eliminates the window for a late response to trigger duplicate processing.</li></ul><p><strong>Detection Fires</strong></p><p>The Offset Commit Thread observes the tracker state. Utilization crosses 90%. Uncommitted percentage drops to 1% — only the one oversized message remains PENDING, while 99% of slots are COMMITTED and waiting. Both thresholds are breached simultaneously.</p><p><strong>Mitigation Executes</strong></p><ul><li>The stuck offset is marked CANCELED in the tracker.</li><li>All pending and scheduled service calls for this offset are aborted.</li><li>The message is written to the DLQ with metadata: topic name, partition number, offset value, and error reason (payload size exceeded).</li><li>The offset is marked COMMITTED. The tracker head advances.</li><li>All five committed offsets that were waiting behind it are now free to commit to Kafka in sequence.</li><li>The pipeline resumes at full throughput.</li></ul><p><strong>After the Incident</strong></p><p>The owning team receives a DLQ alert. They inspect the entry, identify the oversized payload, fix the producer to chunk large messages, and replay the DLQ entry once the fix is deployed. No data was lost. The pipeline was blocked for seconds, not hours.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=58ea9da64a58" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Why the Saga Pattern Alone Isn’t Enough in Real-World Distributed Systems]]></title>
            <link>https://medium.com/@gati.sahu/saga-pattern-in-microservices-the-common-misunderstanding-bd736ef5dffc?source=rss-fcb9046d516e------2</link>
            <guid isPermaLink="false">https://medium.com/p/bd736ef5dffc</guid>
            <dc:creator><![CDATA[gati sahu]]></dc:creator>
            <pubDate>Sat, 21 Feb 2026 08:40:48 GMT</pubDate>
            <atom:updated>2026-02-21T09:13:15.607Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Slk4ypFNQeZMq4YZDEda2A.png" /></figure><p>The <a href="https://learn.microsoft.com/en-us/azure/architecture/patterns/saga">Saga pattern</a> is widely adopted in microservices architectures as an alternative to classic distributed transactions like the Two-phase commit protocol.</p><p>At a surface level, this sounds straightforward. But this framing hides an important architectural reality.</p><h3>What “Avoid Distributed Transactions” Really Means</h3><p>Avoiding distributed transactions typically means not relying on protocols such as the Two-phase commit protocol, which provide:</p><ul><li>Global atomic commit</li><li>Coordinator-driven consensus</li><li>Lock retention across participants</li><li>Strong consistency guarantees (ACID across services)</li></ul><p>In microservices, this model is problematic because:</p><ul><li>It introduces a <strong>global coordination point</strong></li><li>Participants must remain available during the prepare/commit phases</li><li>Locks may be held across network boundaries</li><li>Failure handling becomes blocking and complex</li></ul><p>Thus, avoiding distributed transactions is primarily about <strong>removing synchronous cross-service coordination and global locking</strong></p><p>Adopting the Saga pattern implies a fundamental architectural shift from infrastructure-managed atomicity to application-managed consistency. Instead of relying on a distributed commit protocol such as the Two-phase commit protocol to guarantee all-or-nothing behaviuor across services, a Saga decomposes a global transaction into a sequence of independent local ACID transactions. These local transactions are connected through durable messages — events or commands — and coordinated either via orchestration (a centralized saga coordinator controlling the workflow) or choreography (purely event-driven propagation across services). Each step commits its changes locally and then publishes an event to trigger the next step. There is no distributed prepare/commit phase and no global atomic boundary; consistency is achieved progressively over time.</p><h3><strong>Saga Does Not Provide ACID Isolation</strong></h3><p>A Saga does not guarantee atomicity across services, isolation between concurrent workflows, or immediate consistency of distributed state. Once a local transaction commits within a service, that state change is durable and externally visible. If a downstream service fails due to a technical issue — network partition, process crash, broker outage — the system is already in a partially committed state. Compensation in such cases is not equivalent to atomic rollback; it is merely another forward-moving state transition attempting to semantically counteract a prior business action. Moreover, compensating transactions themselves can fail, retry, or conflict with concurrent updates, further diverging the system from any notion of global isolation.</p><h3>Saga Does handle Technical error</h3><p>A <strong>business error</strong> is a domain rule violation. The system is technically healthy, but the requested action is invalid. Examples include charging an expired credit card or exceeding a credit limit. The database is reachable, services are up, messages flow correctly — the failure is purely semantic. This is the type of failure the Saga pattern is designed to handle, because compensating actions can logically reverse previously committed business steps.</p><p>A <strong>technical error</strong>, however, originates from the infrastructure layer. The business request is valid, but the platform fails to execute it reliably. Examples include database timeouts, IOException, service crashes, network partitions, lost messages, or replication lag in eventually consistent systems. From a business perspective, nothing is wrong — but from a system perspective, execution is unreliable.</p><p>This difference is critical.</p><p>If a database write fails due to a transient infrastructure issue and we immediately trigger a compensating action using Saga, we assume the compensating step will succeed. But distributed systems exhibit <strong>non-deterministic, often clustered failures</strong>. If one component is unstable, others may be unstable as well. The compensating transaction can fail for the same technical reason.</p><p>Technical failures are unpredictable in timing and manifestation. Their probability is never zero. Saga, however, is a deterministic workflow model built for business-level correction, not infrastructure-level fault recovery.If you attempt to handle technical errors purely through compensation logic, you are layering deterministic business workflows on top of non-deterministic infrastructure faults. Over time, this guarantees state divergence.</p><p>The complexity increases when failures are persistent rather than transient. Replica loss, quorum conflicts, or corrupted state can leave the system in a condition that automatic retries cannot resolve. In such cases, the system must first restore a valid baseline state before reapplying pending changes. This requires operational tooling, deterministic recovery procedures, and often architectural patterns such as event sourcing with snapshotting and replay. Manual recovery without structured tooling is highly error-prone, especially under operational pressure. For large-scale systems, automated reconciliation and recovery workflows are essential, because persistent technical inconsistencies are statistically inevitable.</p><h3>Counter measure for handling the lack of Isolation</h3><p>Because the Saga pattern does not provide ACID isolation across services, concurrent workflows may observe intermediate states or conflict with each other. To mitigate this, we must introduce <strong>application-level concurrency control mechanisms</strong>.</p><h3>1. Semantic Locks (Business-Level Locking)</h3><p>Instead of database row locks, use <strong>domain-level state transitions</strong> to prevent conflicting operations.<br> Example: mark an order as PENDING_PAYMENT before triggering downstream steps. Other workflows cannot modify or cancel the order while it is in this intermediate state.</p><p>This is a <strong>logical lock</strong>, not a physical DB lock.<br> It avoids distributed blocking while protecting business invariants.</p><h3>2. Communicative Updates (Intent Signaling)</h3><p>Services explicitly communicate state changes through events before finalization.<br> Consumers treat intermediate states as provisional and avoid acting on incomplete workflows.</p><p>This makes state transitions visible and reduces hidden race conditions.<br> It shifts from silent writes to <strong>explicit state progression</strong>.</p><h3>3. Pessimistic View at Business Level</h3><p>Even without distributed DB locks, you can enforce pessimistic behaviour by:</p><ul><li>Rejecting concurrent commands for the same aggregate</li><li>Serializing updates per entity key</li><li>Using single-writer principles per business entity</li></ul><p>This reduces concurrency scope without global coordination.</p><h3>4. Re-Read Before Commit (Validation Pattern)</h3><p>Before committing a step, re-read the current version of the entity and validate invariants again.<br> If the state changed during processing, abort or retry.</p><p>This is effectively <strong>application-level repeatable read</strong>.</p><h3>5. Versioning / Optimistic Concurrency Control</h3><p>Attach a version number (or ETag) to aggregates.<br> On update:</p><ul><li>Read version N</li><li>Write with expected version N</li><li>Fail if version has changed</li></ul><p>This prevents lost updates and ensures deterministic conflict detection.</p><h3>Counter measure for Technical error</h3><h3>A Two-Layer Architectural Model</h3><p>When adopting Saga-based workflows, the core mistake is assuming compensation alone can address distributed failure modes.</p><p>It cannot.</p><p>A production-grade system separates <strong>technical reliability concerns</strong> from <strong>business workflow coordination</strong>.</p><h3>Technical Layer — Reliability Foundation</h3><h3>Objective</h3><p>Provide deterministic execution guarantees in the presence of non-deterministic infrastructure failures.</p><p>This layer absorbs uncertainty caused by:</p><ul><li>Network partitions</li><li>Process crashes</li><li>Partial writes</li><li>Duplicate deliveries</li><li>Broker redelivery</li><li>Leader re-election / failover</li></ul><h3>Core Guarantees</h3><ul><li><strong>Durable intent logging</strong> (write-ahead persistence before side effects)</li><li><strong>At-least-once delivery with idempotent effect</strong></li><li><strong>Idempotent command handlers</strong></li><li><strong>Retry orchestration with exponential backoff</strong></li><li><strong>Crash recovery via replay</strong></li><li><strong>Monotonic state transitions</strong></li><li><strong>Deterministic failure classification</strong></li><li><strong>Eventual completion or explicit terminal failure</strong></li></ul><h3>Design Characteristics</h3><ul><li>Side effects are never executed without durable intent.</li><li>Replays are safe.</li><li>Duplicate execution is tolerated.</li><li>State machines are explicit and recoverable.</li><li>Event publishing is atomic with state transition (e.g., outbox pattern).</li></ul><p>This layer transforms unreliable infrastructure into a <strong>reliable execution substrate</strong>.</p><p>It ensures:</p><blockquote><em>Every command either eventually completes or deterministically fails — even across crashes.</em></blockquote><p>The business layer should never reason about timeouts, retries, or partitions.</p><h3>Business Layer — Saga Coordination</h3><h3>Objective</h3><p>Coordinate long-running, multi-step business workflows and enforce semantic invariants.</p><h3>Responsibilities</h3><ul><li>Define workflow state machines</li><li>Orchestrate or choreograph step execution</li><li>Encode business rules and invariants</li><li>Define compensating transactions</li><li>Maintain process state and progression</li></ul><h3>Operating Assumptions</h3><p>The business layer assumes:</p><ul><li>Commands it emits will eventually execute</li><li>Retries are transparent</li><li>Infrastructure instability is abstracted away</li><li>Compensations will eventually execute once triggered</li></ul><p>Saga determines <strong>when</strong> to compensate.<br> The technical layer guarantees compensation <strong>will</strong> execute.</p><p>This layered approach aligns with the principles described by Pat Helland in <a href="https://ics.uci.edu/~cs223/papers/cidr07p15.pdf"><em>Life Beyond Distributed Transactions: An Apostate’s Opinion</em></a>. The core idea: replace distributed transactions with reliable messaging infrastructure and build business coordination on top.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bd736ef5dffc" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Dealing with Failure in Optimistic Systems]]></title>
            <link>https://medium.com/@gati.sahu/dealing-with-failure-in-optimistic-systems-02076d1bc922?source=rss-fcb9046d516e------2</link>
            <guid isPermaLink="false">https://medium.com/p/02076d1bc922</guid>
            <dc:creator><![CDATA[gati sahu]]></dc:creator>
            <pubDate>Sat, 31 Jan 2026 11:23:24 GMT</pubDate>
            <atom:updated>2026-01-31T11:23:24.477Z</atom:updated>
            <content:encoded><![CDATA[<p><strong>When you can’t check if something will work, just try it and handle the consequences</strong></p><p>Most modern software operates optimistically — it attempts operations without guaranteeing they’ll succeed, then deals with failures as they arise. This approach, rooted in optimistic transaction protocols, has become ubiquitous in concurrent and distributed systems. But why would developers intentionally skip precondition checks?</p><h3>The Try-and-See Philosophy</h3><p>Optimistic control designs flip traditional programming wisdom on its head. Instead of verifying conditions before acting, they take action first and validate results afterward, typically by catching exceptions or checking postconditions. The pattern looks like:</p><ol><li>Attempt the operation</li><li>Check if it succeeded</li><li>If failed, apply a recovery strategy</li></ol><p>This isn’t lazy programming — it’s often the only practical approach.</p><h3>When You Can’t Check First</h3><p>The need for optimistic methods stems from fundamental limitations in what developers can verify beforehand:</p><p><strong>Temporal preconditions</strong> create a race against time. In concurrent systems, conditions hold for <strong>moments</strong>, not durations.</p><ul><li>Disk space might exist when checked, but disappear during the write</li><li>A service might be reachable during a health check but crash milliseconds later</li></ul><p><strong>Database example</strong><br> Row-level locks checked ahead of time would serialize the system. Instead, MVCC allows concurrent writes and resolves conflicts later.</p><p><strong>Asynchronous state changes</strong> State can change independently of your thread.</p><ul><li>Thread interruption</li><li>Task cancellation</li><li>Leadership changes in distributed systems</li></ul><p><strong>JVM example</strong><br> A thread may be interrupted <em>after</em> you check isInterrupted() but before the operation completes. Correct code reacts to interruption when it occurs, not before.</p><p><strong>Precondition Checks Can Be More Expensive Than Failure</strong></p><p>Sometimes validation costs more than simply trying.</p><p><strong>Example</strong></p><ul><li>Validating a complex data structure</li><li>Checking deep invariants</li><li>Coordinating distributed locks</li></ul><p><strong>Flink example</strong><br> Instead of preventing failure, Flink processes events optimistically and relies on checkpoints to recover. Re-execution is cheaper than coordination.</p><h3>Why This Matters</h3><p>Optimistic approaches acknowledge a fundamental truth about distributed and concurrent systems: you cannot fully control or predict the environment your code operates in. Other processes, network conditions, hardware failures, and asynchronous signals create a context where guarantees are impossible.</p><p>The postcondition-checking strategy — attempting operations and validating results — becomes not just an optimization but a necessity. It’s the only way to build reliable systems when the ground beneath you constantly shifts.</p><p>For developers, this means designing robust failure policies is just as critical as implementing happy-path logic. Exception handlers, retry mechanisms, and rollback strategies aren’t edge cases — they’re first-class concerns in any system that can’t guarantee preconditions will hold.</p><p>Multithreaded programming introduces a unique challenge: when one thread fails, others keep running. Without careful design, a single failed operation can corrupt shared state, causing a cascade of failures across your entire application. The key is choosing the right failure response strategy — and making that choice explicit.</p><h3>Failure Handling Strategies</h3><p>When a method detects it cannot achieve its intended effect, it typically throws an exception or sets a failure indicator. What happens next falls into six general strategies:</p><h3>1. Abrupt Termination</h3><p>The method dies immediately via exception, regardless of object state. This applies when:</p><ul><li>The entire activity is fundamentally doomed (e.g., file conversion when the input file doesn’t exist)</li><li>Objects are session-confined and won’t be reused</li><li>Programming errors occur (NullPointerException, ArrayIndexOutOfBoundsException)</li></ul><p><strong>The corrupted flag pattern:</strong> When shared objects cannot be restored to consistent states, set a corruption marker that forces all future operations to fail until manual repair occurs. This prevents other threads from operating on broken state.</p><h3>2. Continuation (Ignoring Failure)</h3><p>Simply proceed despite the failure. Appropriate when:</p><ul><li>Failure has no bearing on overall functionality (e.g., animation frame drops in UI notifications)</li><li>Error handlers themselves encounter incidental exceptions (e.g., failures while closing files)</li><li>Threads providing essential services must never terminate (database management services)</li></ul><p>While seemingly irresponsible, continuation is common in event frameworks and cleanup code within finally blocks.</p><h3>3. Rollback</h3><p>Provide clean-fail guarantees: either complete success or revert to pre-operation state. Two implementation approaches:</p><p><strong>Provisional action:</strong> Construct new state representations, perform updates on the tentative version, then atomically swap only upon success. Nothing requires undoing. Essential when actions aren’t fully synchronized, as it prevents other threads from observing inconsistent intermediate states.</p><p><strong>Checkpointing:</strong> Record current state (often as a Memento), perform direct updates, then restore from checkpoint on failure. Simpler to implement when full synchronization exists.</p><p><strong>Antimessages:</strong> For operations beyond state updates, every message sent must have an inverse (credit/debit pairs). Some operations — particularly IO and physical device actuation — cannot be provisionally attempted or undone, making rollback impossible.</p><h3>4. Roll-forward (Recovery)</h3><p>When rollback is impossible but continuation is inadequate, advance conservatively to establish any legal, consistent state. This differs from rollback in that the final state may differ from the entry state, but both are valid. Often implemented in finally clauses performing minimal cleanup (closing files, canceling dependent activities). Easier than rollback since it doesn’t require full saved state representations.</p><p><strong>Point of no return pattern:</strong> Some methods have preliminary sections that can easily roll back, followed by sections past a commitment point that must roll forward to completion even upon failure (e.g., protocol acknowledgment requirements).</p><h3>5. Retry</h3><p>Contain failure locally by attempting the operation again, based on belief that transient conditions caused the failure. Requires rollback capability to restore state between attempts.</p><p>Common scenarios:</p><ul><li>Temporary resource contention</li><li>IO device or network transients</li><li>Optimistic concurrency control (interference patterns rarely persist)</li></ul><p><strong>Exponential backoff:</strong> Insert progressively longer delays between attempts to reduce contention and CPU waste. Critical consideration: retries can consume unbounded CPU time without proper termination conditions.</p><h3>6. Delegation to Handlers</h3><p>Offload error processing to specialized handler objects when:</p><ul><li>Exceptions in one thread require compensating actions in other threads</li><li>Centralized error management is needed</li><li>Client code cannot be expected to know appropriate responses</li></ul><p>Handlers can perform any action a catch clause can: thread shutdown, cleanup thread spawning, cross-thread communication, exception wrapping, or protocol engagement. However, handlers escape stack-based control flow, potentially making system-wide failure responses harder to predict.</p><p>Optimistic design doesn’t eliminate failure — it <strong>embraces it</strong>.In distributed systems, correctness doesn’t come from preventing failure but from <strong>surviving it gracefully</strong>. The real engineering challenge isn’t “how do we avoid errors?” — it’s “how do we recover without breaking everything else?”</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=02076d1bc922" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Why Modern Systems Need Adaptive Rate Limiting]]></title>
            <link>https://medium.com/@gati.sahu/why-modern-systems-need-adaptive-rate-limiting-4d3344f846ec?source=rss-fcb9046d516e------2</link>
            <guid isPermaLink="false">https://medium.com/p/4d3344f846ec</guid>
            <dc:creator><![CDATA[gati sahu]]></dc:creator>
            <pubDate>Sat, 06 Dec 2025 07:36:42 GMT</pubDate>
            <atom:updated>2025-12-06T07:36:42.849Z</atom:updated>
            <content:encoded><![CDATA[<p><strong>Why Rate Limiting Matters</strong></p><p>In any high-volume, business-critical service, <strong>quality of service (QoS)</strong> becomes just as important as correctness. As traffic grows, multiple clients, features, and automated systems compete for shared backend capacity. Without guardrails, a single misbehaving client, unexpected spike, or automation loop can overwhelm the system — not because the system is poorly designed, but because <strong>no shared infrastructure can protect itself from unbounded load</strong>.</p><p>This is where <strong>rate limiting</strong> enters the picture.</p><p><strong>What Problem Rate Limiting Actually Solves</strong></p><h4>1. Protection Against Misbehaving Clients</h4><p>If one client floods the service with requests, it can saturate CPU, memory, DB connections, or thread pools.<br> <strong>Without rate limits → the entire system collapses, affecting all customers.</strong><br> <strong>With rate limits → only the misbehaving client is throttled.</strong></p><p>This first-generation model typically uses simple counters (e.g.,</p><p>QPS counters) to enforce fixed quotas.</p><h4>2. Isolation Between Tenants</h4><p>Shared services must guarantee fairness:</p><ul><li>A VIP client cannot starve background jobs.</li><li>A noisy background job must not slow down interactive user flows.</li><li>Internal batch systems should not disrupt public APIs.</li></ul><p>Rate limits create <strong>tenant isolation</strong>, ensuring one group cannot degrade others.</p><h4>3. Controlled Backpressure (Prevent Meltdowns)</h4><p>Once concurrency exceeds system capacity:</p><ul><li>queue lengths grow</li><li>latencies spike</li><li>tail latency explodes</li><li>and the system enters a death spiral.</li></ul><p>Rate limiting is the first line of defense to <strong>shed load early</strong>, before the system degrades.</p><p><strong>Why Fixed Quotas Became Insufficient</strong></p><h4>1. Cost Variance: All Requests Looked the Same, Even When Their Load Was Very Different</h4><p>The fixed-quota system treated every request identically, whether it was a simple primary-key lookup or an expensive multi-row scan. Architecturally, this is a major blind spot: two operations with orders-of-magnitude difference in CPU, I/O, or storage impact were assigned the same quota weight.<br> As a result, <strong>the system couldn’t prioritize cheap, high-value work over expensive, low-value work</strong>, nor could it prevent inefficient queries from consuming disproportionate resources. This lack of cost-awareness not only reduced overall goodput but also made the system vulnerable to accidental or poorly designed heavy queries.</p><h4>2. Traffic Skew: Caller-Based Limits Failed to Protect Hot Data or Hot Shards</h4><p>Per-caller rate limits assume that overload happens because a single client misbehaves, but real systems experience <strong>data-driven hotspots</strong>.<br> When thousands of well-behaved clients concurrently access the same “hot key” — such as a popular product, trending item, or shared resource — the backend storage shard handling that key becomes overwhelmed. Even though <em>each caller is within their quota</em>, the <strong>aggregate load collapses the underlying shard</strong>, creating a localized bottleneck that spills over and degrades performance for unrelated traffic.</p><p>In other words, <strong>isolating by caller wasn’t enough</strong>; the system needed visibility into <em>what</em> data was being accessed, not just <em>who</em> was calling.</p><h4>3. Unable to maximize Good put</h4><p>Static quotas mainly aim to stop overload, not to optimize throughput. They operate as blunt instruments, often leaving a large portion of system capacity unused simply because the configured limit is conservative. In high-scale systems, unused capacity directly translates to lost opportunities — fewer processed requests, slower pipelines, and lower operational efficiency. To truly maximize goodput, a system must dynamically tune its limits based on actual performance, freeing unused headroom when available and tightening controls under stress. Fixed quotas are fundamentally incapable of this adaptive behaviour.</p><p>To fix these limitations, we had to stop thinking in terms of raw QPS and start modeling the real work behind every operation, applying controls that reflect its true cost.</p><p><strong>1. Resource-Aware Rate Control: Every Request Has a Cost</strong></p><p>Two requests that look identical on the surface may impose very different loads on backend storage. For example:</p><ul><li>Request A: 1 KB lookup hitting cache</li><li>Request B: 1 KB lookup that misses cache → performs disk seek → causes 10 ms latency spike</li></ul><p>Traditional rate-limiting treats these as identical.<br> Resource-aware rate control (RARC) fixes that.</p><p><strong>How It Works</strong></p><p>Instead of QPS, the system uses <strong>Request Units (RU)</strong> — a currency representing real backend work.RU is calculated using a linear cost model .</p><p><strong>Example</strong></p><p>Two reads each return 1 MB:</p><ul><li>Read A: 2 ms latency (cache hit) → Cheap</li><li>Read B: 40 ms latency (disk hit) → Expensive</li></ul><p>Raw bytes look the same, but RARC charges 20× more RU to the disk-miss request. This simple shift <strong>eliminates unfairness</strong> and stops expensive operations from hogging cluster capacity.</p><p><strong>2. Hot-Key Detection and DDoS Defense .</strong></p><p>Think of a product listing that suddenly goes viral after being featured by a major news outlet. Tens of thousands of people refresh their browser at once. Or imagine a misconfigured crawler that fixates on a single record and pounds it thousands of times per second.<br> The pattern is identical: <strong>the system receives a massive burst of <em>identical reads</em>, all targeting one hot spot in the key space.</strong></p><p><strong>Real-time Hot-Key Detection in Constant Space</strong></p><p>Every proxy service continuously streams incoming keys into a lightweight, in-memory <strong>top-k counter</strong>.<br> The algorithm behind it is a close relative of the <strong>Space-Saving</strong> algorithm — a probabilistic method designed to track the most frequent items in a stream using just a few megabytes of memory.</p><p>This is exactly the technique highlighted in the <a href="https://www.americanscientist.org/article/the-britney-spears-problem"><em>Britney Spears Problem</em></a>, where Hayes explains how to identify the hottest items (or in his example, the most-searched stars) without storing the entire request history.</p><p><strong>Why this algorithm?</strong></p><ul><li>It runs in <strong>constant space</strong>, no matter how many unique keys exist.</li><li>It keeps an approximate but <strong>continuously updated</strong> ranking of the hottest keys.</li><li>It is fast enough to update <strong>on every incoming request</strong> without slowing down dispatching.</li></ul><p>With this technique, each proxy service knows <em>in real time</em> which keys are becoming dangerously hot — often within milliseconds of a traffic spike.</p><p><strong>Local Caching for Instant Relief</strong></p><p>When a key crosses the hotness threshold, the dispatcher flips a switch:</p><p><strong>Future reads for that key are served directly from a process-local LRU cache.</strong></p><p>A few important characteristics make this safe and effective:</p><ul><li><strong>TTL is tiny</strong> — about 3 seconds. Hot keys cool quickly, and so does their cache entry.</li><li><strong>No global cache is needed</strong> — no Redis, no mem cached cluster.</li><li><strong>The protection is local per dispatcher pod</strong>, avoiding cross-node coordination.</li></ul><p>This turns a sudden thundering herd of identical requests into a trickle: the first read populates the cache, and thousands of subsequent reads are served instantly without ever touching storage.</p><p><strong>3. Request Coalescing: One Miss, Many Waiters</strong></p><p>Even with caching, multiple requests for a hot key may arrive in the same millisecond before the cache is populated. Without coordination, these would all punch through to storage — exactly what we want to avoid.</p><p>To fix this, dispatchers maintain an <strong>in-flight map</strong> for hot keys.</p><p>The logic:</p><ul><li>The first request for the key triggers a backend fetch.</li><li>Any other request arriving while that fetch is in progress simply <strong>attaches to the same pending future</strong>.</li><li>When the backend responds, the dispatcher <strong>fans out the result</strong> to all attached waiters.</li></ul><p>Effectively:</p><p>One backend request per hot key per pod.<br>All others are merged and replayed from that single result</p><p>This collapses thousands of redundant backend calls into one, dramatically reducing load and protecting the storage layer from overload or cascading failure.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4d3344f846ec" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>