<?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 Anish Singh Chauhan on Medium]]></title>
        <description><![CDATA[Stories by Anish Singh Chauhan on Medium]]></description>
        <link>https://medium.com/@fromanish?source=rss-2557ccacf9ba------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*3Pycwq8ypEFl69DaFSyYUQ.jpeg</url>
            <title>Stories by Anish Singh Chauhan on Medium</title>
            <link>https://medium.com/@fromanish?source=rss-2557ccacf9ba------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 05 Dec 2026 20:10:00 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@fromanish/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[Your Mutex Can Die]]></title>
            <link>https://medium.com/@fromanish/your-mutex-can-die-9c08540a6a31?source=rss-2557ccacf9ba------2</link>
            <guid isPermaLink="false">https://medium.com/p/9c08540a6a31</guid>
            <category><![CDATA[backend-development]]></category>
            <category><![CDATA[design-systems]]></category>
            <category><![CDATA[concurrency]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[distributed-systems]]></category>
            <dc:creator><![CDATA[Anish Singh Chauhan]]></dc:creator>
            <pubDate>Sat, 28 Nov 2026 05:42:08 GMT</pubDate>
            <atom:updated>2026-11-28T05:42:08.972Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QVgtitPhL6V87krWr6_nig.png" /></figure><p>Here’s a question worth sitting with for a second: what happens to a lock when the thing holding it dies?</p><p>On one machine, you almost never have to ask. The thread and the mutex live in the same process, so if the process goes down, the lock goes with it. Nobody is left standing at the door of a room whose owner is gone. (There are corner cases, like robust mutexes shared between processes, but the common case holds.)</p><p>That guarantee is so quiet you’ve probably never noticed it. You lose it the moment your workers live on different machines. And almost everything that goes wrong with distributed queues comes from not noticing it’s gone.</p><h3>First, why we wanted the lock at all</h3><p>You know this part, so I’ll be quick. count++ compiles to a single addl on x86, but the CPU runs it as load, add, store. Two cores can interleave those three steps, both read 5, both write 6, and one increment vanishes. No crash, no error, just a number that&#39;s quietly wrong.</p><p>A queue is the same bug with more moving parts. Enqueue writes a slot and moves an index. Dequeue reads a slot and moves it back. Two threads doing either at once can corrupt the structure. So you wrap the operations in a mutex, one thread at a time, and sleep fine.</p><p>Now move the workers onto separate machines, put the queue behind a network, and ask again: who holds the lock, and how do you know they still do?</p><h3>You can’t tell dead from slow</h3><p>This is the entire problem, so let me say it plainly. A worker that stops responding might have crashed. Or it might be in a long GC pause. Or its VM got frozen for a live migration. Or a network blip cut it off for forty seconds. From the outside, every one of those looks identical. You don’t get an answer, you get silence.</p><p>So distributed queues drop the idea of “hold the lock until you’re done” and use something weaker: a <strong>lease</strong>. You get the item for a fixed window. If you haven’t finished by then, the system assumes you’re gone and hands the work to someone else.</p><p>SQS is the cleanest example. When a consumer receives a message, SQS doesn’t remove it. It hides it for the visibility timeout, 30 seconds by default. Delete it in time and you’re done. Miss the window and it reappears for the next consumer. That’s a lock with an expiry date, and it’s a smart design, because a crashed worker can never jam the queue forever.</p><p>Which sounds great, until you read the fine print.</p><h3>The bug the lease creates</h3><p>Say the timeout is 30 seconds and the job is “charge the customer.”</p><pre>0:00  worker A receives the message (hidden for 30s)<br>0:05  A calls the payment API, then the process stalls<br>      (GC pause, frozen VM, pick your favorite)<br>0:35  lease expires, message becomes visible again<br>0:36  worker B receives it, charges the customer, deletes it<br>0:50  A wakes up, has no idea 45 seconds just passed,<br>      and carries on with the charge</pre><p>The customer gets charged twice. And look closely at who messed up: nobody. A did nothing it could have detected. SQS did exactly what it promises. Every component behaved correctly and the system still did the wrong thing.</p><p>This is where the mutex analogy breaks. With a real mutex, A could never wake up still believing it was in charge after B had been let in. A lease can’t promise that, because A’s belief and the lease’s expiry run on different clocks, and only one of them knows time passed.</p><p>“Fine, I’ll raise the timeout.” That’s the first thing everyone tries, and it doesn’t close the hole. A bigger window just makes the failure rarer, and rarer is the worst possible property for a bug, because it survives testing and shows up at launch. Meanwhile a genuine crash now takes minutes to recover from. You’re tuning a number, not fixing a flaw.</p><h3>What actually fixes it</h3><p>Two ideas. They aren’t alternatives, and mature systems use both.</p><p><strong>1. Make doing it twice harmless.</strong></p><p>If processing a message twice has the same effect as processing it once, the zombie worker can wake up and do whatever it likes. In practice that’s an idempotency key (the message ID, or a business key like the order ID) checked atomically:</p><pre>INSERT INTO processed (job_id) VALUES ($1)<br>ON CONFLICT DO NOTHING;<br>-- 0 rows inserted: someone already did this one, skip it</pre><p>The check has to sit in the same transaction as the effect, otherwise you’ve just moved the race one step over. That’s a local database transaction covering your own state. You can’t stretch one over someone else’s API, so for calls to third parties, pass the key along with the request and let them deduplicate on their side. Stripe, for example, accepts an idempotency key for exactly this reason.</p><p>People talk about “exactly-once delivery” as if you can buy it. In practice it’s at-least-once delivery plus an idempotent consumer, and the second half is your job.</p><p><strong>2. Make stale workers unable to write.</strong></p><p>This is the <strong>fencing token</strong>. Every time the system grants a lease, it also hands out a number that only ever goes up. SQS doesn’t give you one (its receipt handle is just an opaque string), so you mint the token yourself when a worker claims a job, for example from a database sequence or a counter in etcd. The worker sends that number with every write, and the storage layer remembers the highest one it has seen and rejects anything lower:</p><pre>UPDATE accounts<br>SET balance = $2, last_token = $3<br>WHERE id = $1 AND last_token &lt; $3;<br>-- 0 rows updated: you&#39;re a zombie, stop</pre><p>If that looks familiar, it should. It’s compare-and-swap again: check what you saw before you write. Same idea as the CPU instruction, just done in the database. The difference is what you get out of it. Idempotency makes duplicates harmless. Fencing makes the old lease holder <em>unable</em> to do damage in the first place. Martin Kleppmann made this argument against lock-with-a-timeout schemes in his well-known piece on distributed locking, and it’s still the best explanation of why an expiring lock alone isn’t safe.</p><h3>Kafka has the same problem in a different outfit</h3><p>Kafka doesn’t hand out messages one at a time with a timer, but the shape is identical. Partitions are assigned to consumers in a group. A consumer that stops heartbeating, or takes too long between polls, gets kicked out, and its partitions go to someone else. If it was only stalled, it wakes up believing it still owns the partition and keeps working.</p><p>Kafka does fence one thing for you: a consumer from a stale generation that tries to commit its offset gets rejected. That protects your position in the log. It does nothing for the other stuff the zombie did, like writing to a database or calling another service. Those side effects already happened, so idempotency is still on you. Transactional producers use an epoch-based fence for the same reason. Same pattern, third costume.</p><p>The broker can tell you who the current owner is. It can’t un-do what a former owner already did.</p><h3>If you’re deciding, not coding</h3><p>A quick note for the managers and founders reading. “We use a queue with retries” is not a statement about safety. It’s a statement about at-least-once delivery, which means every consumer of that queue will, someday, see the same job twice.</p><p>The question for design review isn’t “how long is the timeout?” It’s “what happens when this job runs twice?” The answer should be a mechanism, like a unique constraint, an idempotency key, or a version check. “It probably won’t” isn’t one.</p><p>And you can test this cheaply, before launch. Freeze a worker mid-job, let the lease expire, then let it resume. If anything surprising happens, you just found out for free.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9c08540a6a31" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>