<?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 Atish Rhabar on Medium]]></title>
        <description><![CDATA[Stories by Atish Rhabar on Medium]]></description>
        <link>https://medium.com/@atish.rhabar14?source=rss-e55cdc59ce66------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*0dkv-CHqPdYV6JbY</url>
            <title>Stories by Atish Rhabar on Medium</title>
            <link>https://medium.com/@atish.rhabar14?source=rss-e55cdc59ce66------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 06 Dec 2026 09:37:44 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@atish.rhabar14/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[The Outbox Is Not Enough: Exactly-Once Effects on At-Least-Once Delivery]]></title>
            <link>https://medium.com/@atish.rhabar14/the-outbox-is-not-enough-exactly-once-effects-on-at-least-once-delivery-d58407e576b7?source=rss-e55cdc59ce66------2</link>
            <guid isPermaLink="false">https://medium.com/p/d58407e576b7</guid>
            <category><![CDATA[distributed-systems]]></category>
            <category><![CDATA[backend-development]]></category>
            <category><![CDATA[fintech]]></category>
            <category><![CDATA[system-design-concepts]]></category>
            <category><![CDATA[software-engineering]]></category>
            <dc:creator><![CDATA[Atish Rhabar]]></dc:creator>
            <pubDate>Mon, 23 Nov 2026 14:03:49 GMT</pubDate>
            <atom:updated>2026-11-23T14:03:49.954Z</atom:updated>
            <content:encoded><![CDATA[<p>A customer withdraws $2,000 and receives $4,000. Finance spots it during reconciliation two days later. You pull the traces, expecting to find the bug quickly, and find no bug at all.</p><p>The withdrawal service wrote the debit and an outbox row in a single transaction, as it should. The relay published the event once. The payout consumer picked it up, called the bank’s transfer API, and then spent 31 seconds waiting on a slow ledger write. The queue’s visibility timeout was 30 seconds, so the message became visible again and a second consumer took it and called the bank as well. Both consumers then deleted the message successfully.</p><p>Every component kept its promise. The outbox promised the event would never be lost, and it wasn’t. SQS promised at-least-once delivery and delivered at least once. What nobody promised was that the money would move only once, and that’s the promise that mattered.</p><h3>Delivery is not the same thing as effect</h3><p>Delivery is a property of the transport: how many times a message reaches a consumer. Effect is a property of your state: how many times the world changes because of that message. Message brokers can only make promises about delivery. Effects are your responsibility.</p><p>Exactly-once <em>delivery</em> across a network is impossible. The acknowledgement that a message was processed can be lost just as easily as the message itself, so a broker that wants to lose nothing has to redeliver whenever it’s unsure. What you can build is exactly-once <em>effect</em>: at-least-once delivery feeding a consumer that recognises a message it has already handled.</p><p>Picture a bank clerk cashing cheques. The postman can knock twice and hand over the same envelope both times, and that’s fine. The clerk keeps a ledger of cheque numbers, checks it before stamping anything, and cashes cheque #4471 once no matter how many copies arrive. That ledger is what this article is about, along with the exact moment the clerk writes in it.</p><h3>The outbox produces duplicates by design</h3><p>The transactional outbox fixes the dual-write problem, so you never commit a debit and then lose the event that goes with it. The relay pays for that guarantee with duplicates. It reads an unsent row, publishes it, and marks it sent, and if it crashes between publishing and marking, the row goes out again on restart. That behaviour is correct, because the alternative is losing events silently.</p><p>The relay is only the first place duplicates come from. A consumer can finish its work and crash before it acks. A slow handler can outlive its visibility timeout. A Kafka rebalance can hand a partition to a new owner before offsets are committed. Someone can redrive a DLQ after a fix, or an engineer can replay last Tuesday’s events to repair a projection. At any real scale, redelivery is a normal condition of the system, not an edge case.</p><p>The guarantees your platform advertises are narrower than they sound. SQS FIFO deduplicates <em>sends</em> that share a dedup ID within a five-minute window, but it does nothing for a consumer that processes a message and then fails to delete it. Kafka’s exactly-once semantics cover read-process-write <em>inside Kafka</em>, and the guarantee ends the moment your handler writes to PostgreSQL or calls a bank. Exactly-once effects that reach outside the broker are always something you build yourself.</p><h3>The inbox: dedup and effect share a fate</h3><p>The fix is an inbox table, written in the <em>same database transaction</em> as the effect. You don’t check first and then act. The claim on the message and the state change commit together or roll back together.</p><pre>BEGIN;<br><br>INSERT INTO inbox (consumer, event_id)<br>VALUES (&#39;payout-writer&#39;, $1)<br>ON CONFLICT DO NOTHING<br>RETURNING 1;<br>-- no row back → already handled: COMMIT, then ack<br><br>INSERT INTO ledger_entries (...) VALUES (...);<br>UPDATE balances SET available = available - $2 WHERE account_id = $3;<br><br>COMMIT;<br>-- only now: DeleteMessage / commit offset</pre><p>There are three details here, and each one matters.</p><p>The key is event_id, and it&#39;s the ID the producer generated inside its own business transaction and stored on the outbox row. It is <em>not</em> the broker&#39;s message ID. When the relay republishes after a crash, SQS assigns a brand-new MessageId to the same logical event, so a dedup check on MessageId sees two different messages.</p><p>The key also includes consumer. One event fanned out through SNS to a payout writer, a notifications service, and an analytics sink is three separate pieces of work. If they share a dedup key, the first consumer to run blocks the other two.</p><p>The ack comes after the commit. If the process dies between COMMIT and DeleteMessage, the message comes back, the insert hits the unique index, and the handler commits a no-op and acks. In the other direction, if the handler throws halfway through, the inbox row rolls back with everything else and the retry starts clean. This is the property that makes the pattern safe: whether the message was handled is recorded in the same place, and by the same commit, as what handling it changed.</p><h3>Where the simple version breaks</h3><h4>Concurrent duplicates</h4><p>The opening scene wasn’t a retry. Two consumers held the same message at the same moment. The inbox still covers this, as long as the insert comes <em>first</em> in the transaction. PostgreSQL makes the second INSERT ... ON CONFLICT wait on the unique index until the first transaction finishes, then resolves it as a conflict, so the unique constraint is what serialises them. The cost is that a row lock is held for the length of your transaction, which is one more reason never to make an HTTP call inside it.</p><h4>Effects your database can’t see</h4><p>That brings us to the hard case. The payout’s real effect is a bank transfer, and you can’t put a bank inside a PostgreSQL transaction. An inbox row can’t protect a side effect that commits somewhere else.</p><p>There are two tools for this, and you should use both. The first is to carry the idempotency key downstream. Derive a deterministic key from the event, such as payout:{event_id}, and send it on every call, so any partner that honours keys deduplicates for you. The second is to make the external call an explicit state machine. Record PAYOUT_REQUESTED with that key in one transaction, make the call outside any transaction, and record SUBMITTED or FAILED in another. When a message is redelivered and finds the payout already in REQUESTED, the consumer must not call again. It asks the partner for the status of that key and moves forward from the answer. Treat &quot;unknown&quot; as a real state with its own handling, because sooner or later a partner will time out after doing the work.</p><h4>Visibility timeouts are a tuning knob, not a lock</h4><p>Set the timeout above your p99.9 handler latency, and extend it with ChangeMessageVisibility heartbeats for long jobs. That cuts down duplicate work. It doesn&#39;t prevent it, because a GC pause or a network partition can still let the timeout expire. Correctness comes from the inbox, and the timeout only affects throughput.</p><h4>Dedup is not ordering</h4><p>An inbox stops the same event from being applied twice, but it does nothing about AccountFrozen arriving before AccountOpened. If order matters for an aggregate, give each event a per-aggregate sequence number and apply only WHERE version = $seq - 1, or deliberately park and retry anything that arrives out of order.</p><h4>Retention, and the inbox you don’t need</h4><p>An inbox table grows without limit, so you’ll prune it, which means picking a horizon. That horizon has to outlast your longest possible redelivery: SQS retention can be up to 14 days, a DLQ can hold messages longer, and a manual replay can reach back however far you allow. Partition the table by day and drop old partitions, and make the horizon an explicit, documented decision.</p><p>Wherever you can, push idempotency into the effect itself. A UNIQUE (source_event_id) constraint on ledger_entries never expires, survives any replay, and needs no pruning job. The inbox is the general-purpose tool, and a natural key on the effect is the stronger one.</p><h3>The traps I keep seeing</h3><ul><li><strong>Check-then-act.</strong> The handler runs SELECT on the inbox, finds nothing, does the work, and inserts afterwards. Between the read and the write there&#39;s a window, and two concurrent consumers will both get through it. The claim has to be the first write in the transaction, not a read.</li><li><strong>Redis SETNX as the dedup store.</strong> Whichever order you choose, it fails. If you set the key before committing, a crash before the commit means the message is marked handled and never applied, so it’s silently dropped. If you set it after committing, you’ve reopened the window. A dedup marker that doesn’t commit with the effect is a cache, and caches don’t guarantee anything.</li><li><strong>Acking before the work is done.</strong> Teams sometimes delete the message at the start of the handler to “avoid duplicates”. All that does is turn at-least-once into at-most-once and trade duplicates for lost money.</li><li><strong>Idempotent writes, non-idempotent fan-out.</strong> The ledger update is protected, but the handler also publishes PayoutCompleted straight to the broker. On redelivery the write is skipped and the event goes out again, along with a second email to the customer. Anything the handler emits should go through its own outbox, inside the same transaction.</li><li><strong>Treating the platform’s guarantee as end-to-end.</strong> FIFO dedup windows and Kafka transactions are real and useful, but they protect the broker, not your ledger.</li></ul><h3>Exactly-once is a database property</h3><p>It’s tempting to think of exactly-once as a feature you can buy: the right broker, the right flag, the right managed service. It isn’t something the network can provide. You get exactly-once effects when a unique index and a commit agree that something happened, and when every call that leaves your database carries a key that lets the other side reach the same agreement.</p><p>The outbox gets the message out of your service, and the inbox makes it safe to receive more than once. You need both, and neither works without the other.</p><p>Go back to the $4,000 withdrawal. Suppose the inbox row and a PAYOUT_REQUESTED record had been committed before the bank call, and the bank had received a key derived from the event. The second consumer would have found the event already claimed and deleted the message, and even a retry that got through would have been deduplicated by the bank using that key. The customer would have received $2,000, nobody would have been paged, and reconciliation would have had nothing to report. A well-built payment system is a boring one.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d58407e576b7" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Money Is Not a Float: Building a Multi-Currency Ledger That Balances]]></title>
            <link>https://medium.com/@atish.rhabar14/money-is-not-a-float-building-a-multi-currency-ledger-that-balances-f064953055cc?source=rss-e55cdc59ce66------2</link>
            <guid isPermaLink="false">https://medium.com/p/f064953055cc</guid>
            <category><![CDATA[payments]]></category>
            <category><![CDATA[design-systems]]></category>
            <category><![CDATA[fintech]]></category>
            <category><![CDATA[software-engineering]]></category>
            <dc:creator><![CDATA[Atish Rhabar]]></dc:creator>
            <pubDate>Thu, 05 Nov 2026 05:29:34 GMT</pubDate>
            <atom:updated>2026-11-05T05:29:34.857Z</atom:updated>
            <content:encoded><![CDATA[<p>The reconciliation report has been off by one cent every day for three weeks. Never two cents, never zero. Always one, always in the same direction, always on the MYR settlement account. Finance has a spreadsheet tracking it. Engineering has a ticket labelled “rounding?” that nobody has picked up, because one cent a day doesn’t feel like an incident.</p><p>Then a Japanese merchant gets a payout for ¥1,200,000 instead of ¥12,000. Same root cause, different currency. Somewhere in the stack, someone assumed every currency has two decimal places.</p><p>Multi-currency is where most ledgers quietly stop being correct. Not because the arithmetic is hard, but because every shortcut that works for a single currency — floats, a global decimal precision, summing a column — turns into a small, persistent lie the moment a second currency shows up.</p><h3>Integers, but not the same integers</h3><p>Everyone knows not to store money in a float. 0.1 + 0.2 is not 0.3, and a ledger that can&#39;t add ten cents is not a ledger. The standard fix is to store amounts as integers in minor units: $12.34 becomes 1234 cents.</p><p>The part that gets missed is that “cents” is a USD idea. ISO 4217 gives every currency its own exponent — the number of decimal places in its minor unit — and they don’t agree:</p><pre>Currency               Exponent   1 unit in minor units<br>JPY, KRW               0          1<br>USD, EUR, MYR          2          100<br>KWD, BHD, OMR          3          1,000<br>USDT (most chains)     6          1,000,000<br>BTC                    8          100,000,000<br>ETH                    18         1,000,000,000,000,000,000</pre><p>So 1234 means nothing on its own. In USD it&#39;s $12.34; in JPY it&#39;s ¥1,234; in KWD it&#39;s 1.234 dinar. The amount and its currency are one value, and the exponent comes from the currency, never from a global setting. That ¥1,200,000 payout is what happens when the API layer multiplies every incoming amount by 100 because it always has.</p><p>Crypto breaks the next assumption. ETH has 18 decimals, so one ether is 1⁰¹⁸ wei, and a signed 64-bit integer tops out around 9.2 × 1⁰¹⁸. A BIGINT column can hold about 9.2 ETH before it overflows. Ledgers that carry tokens store amounts as NUMERIC(78, 0) in PostgreSQL — enough for a full 256-bit integer — and handle them as arbitrary-precision integers in application code.</p><p>Two more details belong in the currency table, not in code: the exponent can differ between ISO and your payment processor (some processors treat ISO zero-decimal currencies as two-decimal for API purposes), and exponents occasionally change. Version the table, and record on each entry which exponent it was written under.</p><h3>Balance per currency, not in total</h3><p>The rule of double entry is that debits equal credits. In a multi-currency ledger that rule needs one more word: debits equal credits <em>per currency</em>. A journal entry that debits $100 and credits RM 470 is not balanced. It’s two unbalanced entries that happen to share an ID.</p><p>That forces two design decisions most teams make implicitly and regret.</p><p>First, every account holds exactly one currency. A customer with USD and MYR balances has two accounts, not one account with a currency column on each row. The moment an account can hold mixed currencies, its “balance” is a sum of incomparable numbers, and every query that touches it has to remember to group by currency. Some query won’t.</p><p>Second, a currency conversion is not a single posting. It’s two balanced postings, one in each currency, linked through conversion accounts the platform owns. The customer’s USD goes into the platform’s USD conversion account; the platform’s MYR conversion account pays out to the customer’s MYR account. Each currency balances on its own. The two conversion accounts are where the platform’s FX position lives — holding more USD and less MYR than it did a minute ago — and that position is now a first-class thing you can report on, hedge and reconcile, instead of an accident buried in a rate.</p><h3>One conversion, written out</h3><p>A customer converts $100.00 to ringgit. The mid-market rate is 4.7000; the customer is quoted 4.6530, a 1% spread. They receive RM 465.30.</p><pre>Leg  Account                 Ccy   Debit    Credit<br>USD  Customer wallet (USD)   USD   100.00<br>USD  FX conversion (USD)     USD            100.00<br>MYR  FX conversion (MYR)     MYR   470.00<br>MYR  Customer wallet (MYR)   MYR            465.30<br>MYR  FX spread revenue       MYR              4.70</pre><p>Customer wallets are liabilities, so the debit on the USD wallet reduces what the platform owes them and the credit on the MYR wallet increases it. Each currency balances on its own: USD 100.00 = 100.00, MYR 470.00 = 465.30 + 4.70.</p><p>The useful trick is booking the conversion leg at mid and posting the spread as its own line. The conversion accounts then hold exactly +$100.00 and −RM 470.00 — a clean position at the market rate that treasury can hedge — and the platform’s margin shows up as revenue the moment it’s earned, not as a number someone derives at month end by comparing two balances.</p><p>All five lines share one journal entry ID and are written in one database transaction, alongside the rate, the quote ID and the rate source. Either the whole conversion exists or none of it does.</p><h3>Every fraction of a cent goes somewhere</h3><p>Conversions rarely land on a whole minor unit. $12.34 at 4.6537 is RM 57.426658. The customer gets RM 57.43 or RM 57.42, and the leftover 0.003342 ringgit has to be somebody’s. A ledger that just drops it doesn’t balance; a ledger that drops it in two different places doesn’t reconcile.</p><p>That’s the one-cent-a-day bug from the opening. The payment service computed the merchant’s share and rounded half-up. The settlement job recomputed the same share from the gross amount and rounded half-to-even. On most days they agreed. On days with an exact half-cent somewhere in the batch, they didn’t.</p><p>Three rules keep this honest.</p><p>Round exactly once, at the moment a computed amount becomes a posting — and store the result. Everything downstream reads the posted amount; nothing recomputes it from inputs. The rounding mode is a named, per-use decision (“customer credits round down”, “fees round half-to-even”), not whatever the language’s default happens to be.</p><p>When a value is split, allocate it instead of rounding each piece. $100.00 split three ways is not three times $33.33; that loses a cent. Take the floor of each share in minor units, then hand out the remaining units one at a time, by largest remainder, in a deterministic order. The pieces always sum to the whole.</p><p>When a residue genuinely belongs to no one, post it to an explicit rounding account. That account is your smoke detector. Its balance should wobble around zero; if it climbs steadily, two parts of the system disagree about how to round, and you’ve found the bug before finance does.</p><h3>The rate is part of the record</h3><p>An amount in a foreign currency is only half a fact. The other half is the rate that produced it, and rates move every second. If the journal entry doesn’t store the rate it used, nobody can explain that entry next month — not the auditor, not the support agent, not you.</p><p>So every conversion entry carries the rate as an exact decimal (NUMERIC, never a float), the direction it was quoted in, the source it came from, the timestamp of that source, and the quote ID the customer accepted. Rates are stored as quoted, not normalized: if the provider says 1 USD = 4.7000 MYR, store that, and don&#39;t store 1 MYR = 0.212766 USD that you derived from it.</p><p>The quote is the other half of the contract. A customer who sees “you’ll receive RM 465.30” has been promised a price, usually valid for 30 to 60 seconds. The flow that holds up in production is quote, then execute:</p><pre>POST /fx/quotes      { from: &quot;USD&quot;, to: &quot;MYR&quot;, amount: 10000 }<br>→ { quote_id: &quot;q_8f2…&quot;, rate: &quot;4.6530&quot;, receive: 46530, expires_at: &quot;…T10:15:30Z&quot; }</pre><pre>POST /fx/conversions { quote_id: &quot;q_8f2…&quot; }   // with an idempotency key</pre><p>Execution reads the locked quote, checks it hasn’t expired and hasn’t been used, and posts at exactly that rate. An expired quote fails and the client asks for a new one. It never silently re-prices.</p><p>Between the quote and the moment treasury actually trades, the platform is carrying the market risk. That’s what the spread pays for, and it’s why the quote window is short. Make it long and generous, and you’ve written customers a free option on the exchange rate; the ones who notice will take it.</p><h3>The traps</h3><p>A few mistakes show up in almost every multi-currency system eventually.</p><ul><li><strong>SUM(amount) without </strong><strong>GROUP BY currency.</strong> It runs, it returns a number, and the number is meaningless. Make it impossible: put the currency in the account, not the row, and have reporting views that refuse to aggregate across currencies without an explicit conversion step.</li><li><strong>Treating the inverse rate as exact.</strong> 1 ÷ 4.7000 is 0.2127659574…, which you have to round. Convert USD→MYR, then MYR→USD at the rounded inverse, and you won’t land back where you started. Quote both directions independently, and never derive one from the other inside a posting.</li><li><strong>Refunding at today’s rate.</strong> A customer paid RM 465.30 for $100 last month. Now they want a refund. Do they get RM 465.30 back, or $100 converted at today’s rate? Either can be right; that’s a product decision. What’s never right is leaving it to whichever code path the refund happens to hit. Decide, write it down, and post the FX difference to an explicit account.</li><li><strong>Floats at the edges.</strong> The ledger stores integers and NUMERIC, and then a Node service parses the rate with parseFloat and multiplies. Use a decimal library end to end, and send amounts and rates over the wire as strings.</li><li><strong>Revaluing by editing balances.</strong> At month end, finance wants foreign balances in the reporting currency. That’s a report, or a separate set of revaluation entries. It is never an UPDATE to the original accounts.</li></ul><h3>A number, a currency and a decision</h3><p>The mistake behind every bug in this article is the same: treating money as a number. It isn’t. It’s a number, a currency that gives that number its scale, and a decision about what happens to the part that doesn’t fit. Leave out any one of the three and the ledger still runs. It just stops telling the truth, a cent at a time.</p><p>The team in the opening fixed theirs in an afternoon, once they knew where to look. Round once, store the result, give the leftover a home. The rounding account now moves a few sen a week, in both directions. The spreadsheet tracking the missing cent was archived. Nobody misses it.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f064953055cc" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Hot Accounts: When One Row Becomes Your Bottleneck]]></title>
            <link>https://medium.com/@atish.rhabar14/hot-accounts-when-one-row-becomes-your-bottleneck-de99e4eae741?source=rss-e55cdc59ce66------2</link>
            <guid isPermaLink="false">https://medium.com/p/de99e4eae741</guid>
            <category><![CDATA[fintech]]></category>
            <category><![CDATA[system-design-concepts]]></category>
            <category><![CDATA[distributed-systems]]></category>
            <category><![CDATA[postgresql]]></category>
            <dc:creator><![CDATA[Atish Rhabar]]></dc:creator>
            <pubDate>Wed, 04 Nov 2026 17:16:30 GMT</pubDate>
            <atom:updated>2026-11-04T17:16:30.778Z</atom:updated>
            <content:encoded><![CDATA[<p>It’s the first hour of a big sale and payment latency is climbing. p99 was 80 milliseconds this morning; now it’s four seconds and still rising. The database isn’t struggling — CPU sits at 30%, disk is quiet, the connection pool has headroom. Nothing is slow. Everything is <em>waiting</em>.</p><p>You open pg_stat_activity and the picture snaps into focus. Hundreds of sessions, all with wait_event_type = Lock, all queued behind the same tuple. Not a table, not an index — one row. The platform&#39;s fee account, which every single payment credits with its 1.5% cut.</p><p>Your system can process thousands of payments a second. It can update that one row a few hundred times a second. Today, the second number won.</p><h3>One row, every transaction</h3><p>A hot account is any ledger account that a large share of your transactions touch. The platform fee account. The FX spread account. The settlement or omnibus account that sits behind every customer wallet. The payout float that funds every withdrawal. In a double-entry ledger these aren’t optional — every payment has two sides, and one of those sides keeps landing on the same account.</p><p>The posting itself looks innocent:</p><pre>UPDATE accounts<br>SET    balance = balance + 150, version = version + 1<br>WHERE  id = &#39;acct_platform_fees&#39;;</pre><p>That UPDATE takes a row lock, and PostgreSQL holds it until the transaction commits — not until the statement finishes. Everything else in that transaction runs while the lock is held: the customer-side posting, the journal insert, the outbox row, a network round trip or two between your service and the database, and the commit&#39;s WAL flush at the end.</p><p>That gives you the uncomfortable arithmetic. If the lock is held for 4 ms end to end, the account can absorb at most 1 / 0.004 = 250 postings a second. It doesn’t matter how many cores the database has or how many replicas you run. Writes to that row are serialized, and the ceiling is set by how long each writer holds it.</p><p>This is why the problem hides in staging. At 50 TPS, the queue behind the row never forms. At 300, it forms and never drains — and because waiting sessions hold their connections, the pool drains too, and suddenly payments that never touch the fee account are timing out as well.</p><h3>The fixes that don’t fix it</h3><p>The first instinct is a bigger instance. It buys almost nothing. The lock hold time is dominated by round trips and the commit flush, not by CPU, so a machine twice the size serializes on that row at roughly the same rate.</p><p>SKIP LOCKED comes up next, usually from someone who has built a job queue. It works for queues because any free row will do. Here, every transaction needs <em>that</em> row. Skipping it means skipping the posting.</p><p>Optimistic concurrency feels more modern: read the version, write with WHERE version = $n, retry on conflict. Under real contention it&#39;s worse than the lock. Most attempts lose the race, every loser retries, and you&#39;ve traded an orderly queue for a retry storm that burns connections and inflates latency for everyone.</p><p>Then there’s the shortcut: keep the hot balance in Redis with INCRBY and sync it back later. It&#39;s fast, and it quietly gives up the property your ledger exists to provide. You now have two balances, a dual write between them, and a reconciliation job whose only purpose is to tell you which one is lying.</p><p>All four fail for the same reason. They try to make writes to one row faster. The real fix is to stop requiring every transaction to write to one row.</p><h3>Pattern 1: split the account into buckets</h3><p>The most direct fix is to stop having one fee account. You have sixteen. acct_platform_fees:00 through acct_platform_fees:15, each a real ledger account with its own balance row, rolling up to one logical account for reporting. Each posting picks a bucket — by hashing the transaction ID, or at random — and writes there. The logical balance is the sum.</p><p>Sizing follows from the same arithmetic as the problem. If you need 2,000 postings a second and each lock is held for 4 ms, one row gives you 250; you need at least eight buckets, and you provision sixteen because traffic is never evenly spread and peaks are never polite.</p><p>Credits are trivial. Debits are where this gets interesting. Bucket 7 might hold $40 while the logical account holds $90,000, and a $500 debit that lands on bucket 7 fails even though the money is there. You have three honest options: debit from several buckets in one transaction, always locking them in a fixed order so two debits can’t deadlock; run a rebalancing sweep that moves funds between buckets to keep them roughly level; or route debits to whichever bucket you know has room. Most teams end up with the sweep plus a fallback to multi-bucket debits.</p><p>One rule makes everything downstream survivable: record the bucket on every journal entry. Reversals, refunds and chargebacks must post against the bucket the original entry hit, or your per-bucket balances drift and the sweep starts compensating for errors it can’t see.</p><h3>Pattern 2: write the entry now, the balance later</h3><p>The second fix starts from an observation: the journal entry and the balance update are two different writes, and only one of them needs to contend.</p><p>Inserting a row into an append-only journal_entries table touches no shared row at all. A thousand concurrent transactions can each insert their fee entry without waiting on each other. The contention only appears when every one of them also tries to bump the same balance column in the same transaction.</p><p>So don’t. For the hot account, the payment transaction writes the journal entry and stops. A background roller, running every few hundred milliseconds, reads the new entries for that account past its last checkpoint, sums them, and applies the total in a single UPDATE — one lock acquisition for a thousand postings instead of a thousand. The checkpoint is a high-water mark on the journal&#39;s sequence, stored in the same transaction as the balance update, so the roller can crash and resume without double-applying anything.</p><p>The cost is that the stored balance now lags the journal by up to one roll interval. Anyone who needs the exact current number reads the checkpointed balance plus the sum of entries since the checkpoint — still cheap, because that tail is small. Anyone who can live with a few hundred milliseconds of staleness reads the balance row directly.</p><p>This is the same move databases make with group commit: if every writer pays for its own flush, you’re bound by flush latency; if writers share one, you’re bound by throughput.</p><h3>Pattern 3: ask which direction needs the lock</h3><p>The most useful question about a hot account is not how many writes it takes. It’s which direction they flow.</p><p>A lock on a balance row exists to protect an invariant — almost always “this balance must not go below zero” or “must not go below the reserved amount”. Look at what can violate that invariant: only debits. Adding money to an account can’t overdraw it. A credit has nothing to check.</p><p>That asymmetry is the whole game. Your fee account is credited by every payment and debited once a day when revenue sweeps to treasury. Its credits need no balance check, so they can go through Pattern 2 with no lock at all, and the one daily debit can take the slow, strict path. Nobody notices the sweep waiting 200 ms for a lock.</p><p>The payout float is the mirror image, and the hard case. It’s debited by every withdrawal and credited by an occasional top-up from treasury. Here every write is the dangerous direction, so you can’t defer the check — you need Pattern 1. Pre-fund the buckets, debit each withdrawal from one bucket under its own lock, and let the top-up spread across all of them.</p><p>Most hot accounts in a real ledger are lopsided like this. Once you classify them, the choice of pattern mostly makes itself.</p><h3>What you pay for it</h3><p>None of these patterns is free, and the bill shows up in places the original design never had to think about.</p><ul><li><strong>“The balance” stops being one number.</strong> With buckets it’s a sum; with deferred posting it’s a checkpoint plus a tail. Every report, dashboard and finance export needs to know which it’s reading — and one that reads a single bucket row will be wrong in a way that looks plausible.</li><li><strong>Reconciliation gets an extra hop.</strong> The bank statement shows one settlement account. Your ledger shows sixteen. The recon job has to roll them up before it matches, and a break now has two possible causes: real money missing, or buckets drifting from each other.</li><li><strong>Reversals have to remember where they came from.</strong> A refund that posts to a random bucket instead of the original one leaves the books balanced in total and wrong in every bucket. The sweep will mask it for months.</li><li><strong>Lag becomes a product decision.</strong> Deferred posting is invisible until someone builds a real-time revenue counter on top of the balance row and asks why it trails the payments table.</li><li><strong>Lock ordering is now load-bearing.</strong> The moment any transaction touches two buckets — or a bucket and a customer account — it must lock them in a fixed order. Get it wrong and the hot-account problem becomes a deadlock problem, which is the same outage with a worse log line.</li></ul><p>The audit trail, at least, survives untouched. Every posting is still its own journal entry, with its own ID, against a real account. You changed where the balance lives, not what the ledger records.</p><h3>Choosing a pattern</h3><p>The decision comes down to two questions: which direction is hot, and whether the strict path can keep up.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*EsSkFBp8Og8oQL3e7JnJuA.png" /></figure><p>Credit-heavy accounts defer; debit-heavy accounts split into buckets only once the write rate passes what one row can serialize.</p><h3>The row is telling you something</h3><p>It’s tempting to treat a hot account as a performance bug — something to tune away. It’s better understood as a design signal. The row your transactions queue on is the exact place your system has promised to check an invariant synchronously, on every write. Sometimes that promise is necessary. Often it was never made deliberately; it just fell out of a schema where every account had one balance column.</p><p>A ledger that scales isn’t one with faster locks. It’s one where every lock protects something that genuinely needs protecting, and everything else just writes.</p><p>Back to that sale. The fix that shipped the following week was small: fee credits moved to deferred posting, the payout float split into sixteen pre-funded buckets, one line in the refund path to remember the original bucket. Next peak, the fee account took six times the traffic. Nobody opened pg_stat_activity.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=de99e4eae741" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Distributed Transactions: 2PC, Sagas, and the Problem With “All or Nothing”]]></title>
            <link>https://medium.com/@atish.rhabar14/distributed-transactions-2pc-sagas-and-the-problem-with-all-or-nothing-4592565f408a?source=rss-e55cdc59ce66------2</link>
            <guid isPermaLink="false">https://medium.com/p/4592565f408a</guid>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[micoservices]]></category>
            <category><![CDATA[distributed-systems]]></category>
            <category><![CDATA[saga-pattern]]></category>
            <category><![CDATA[fintech]]></category>
            <dc:creator><![CDATA[Atish Rhabar]]></dc:creator>
            <pubDate>Wed, 03 Jun 2026 15:36:21 GMT</pubDate>
            <atom:updated>2026-06-03T15:36:21.240Z</atom:updated>
            <content:encoded><![CDATA[<p>A customer clicks “place order.” Your system charges their card, reserves the item from inventory, and books a courier. Three services, three databases, three things that must all happen or none of them should. The card gets charged. Inventory comes back and says the item sold out a half-second ago. The courier service never even got the call.</p><p>Now what? There’s no ROLLBACK to type. The money is already gone from the customer&#39;s account, sitting in a payment service that has no idea the order it belonged to just collapsed. You&#39;re holding a half-finished transaction with no single place to undo it.</p><p>This is the central problem of distributed transactions, and it’s one of those things that’s invisible right up until the moment a service boundary sits between two steps that used to live in the same database.</p><h3>Why the easy answer stopped working</h3><p>Inside a single database, this problem is solved and you don’t even think about it. You wrap your writes in BEGIN and COMMIT, and the database gives you ACID: the whole thing happens atomically, or none of it does, with isolation so nobody sees a half-applied state. One engine, one transaction log, one authority deciding the outcome. It&#39;s a genuinely beautiful guarantee, and we lean on it so heavily we forget it&#39;s there.</p><p>The moment you split that work across two databases — or two services that each own their own data, which is the whole point of microservices — that single authority disappears. There is no shared transaction log. No one process can lock all the rows and flip them at once. Each service can only guarantee its <em>own</em> local consistency. Stitching those local guarantees back into something that behaves like one atomic operation is the entire game, and there are essentially two families of answers: hold everything still until everyone agrees, or let each step commit immediately and clean up afterward if something goes wrong.</p><h3>Two-phase commit: everyone agrees before anyone commits</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*aOvYg5BqT7Tz7N4ob0E_nw.png" /><figcaption>Two-phase commit</figcaption></figure><p>The first approach, two-phase commit, tries to recreate that single-authority feeling across multiple participants. It introduces a coordinator whose job is to drive everyone to the same outcome, and it does it in — as the name promises — two phases.</p><p>In the <strong>prepare</strong> phase, the coordinator asks every participant a single question: <em>are you ready to commit?</em> Each participant does all the work right up to the edge of committing — validates, writes to its log, locks the rows it’s about to change — and then answers either “prepared” or “no.” Crucially, a participant that votes “prepared” is making a promise: it has done everything necessary to commit and guarantees it can follow through, even if it crashes and restarts.</p><p>In the <strong>commit</strong> phase, the coordinator tallies the votes. If every participant said “prepared,” it broadcasts <em>commit</em>, and everyone finalizes and releases their locks. If even one said “no,” it broadcasts <em>abort</em>, and everyone discards their tentative work. Either way, the outcome is unanimous. You get atomicity across the whole set.</p><p>It works, and for a long time it was the default for anything spanning two databases. But the cost is buried in that word <em>locks</em>. Between voting “prepared” and hearing the final decision, every participant is holding its rows hostage — nobody else can touch them. And now consider the ugly case: every participant has voted “prepared,” and then the coordinator crashes before sending the decision. The participants are stuck. They’ve promised to commit, so they can’t unilaterally abort; they haven’t been told to commit, so they can’t proceed. They sit there holding locks, blocking other work, waiting for a coordinator that may not come back. This is the blocking problem, and it’s why 2PC is described as a <em>synchronous, availability-reducing</em> protocol — it chooses consistency over availability, and it makes the coordinator a single point of failure.</p><p>There are deeper variants (three-phase commit adds a round to reduce blocking) but they trade simplicity for guarantees that still wobble under network partitions. The honest summary is this: 2PC gives you the strongest guarantee — true atomic isolation — and charges you in latency, availability, and the assumption that every participant speaks the protocol. That last assumption is the killer in a microservices world, where one of your “participants” is a third-party payment API that has never heard of your coordinator and is never going to vote “prepared” on anything.</p><h3>So is 2PC dead? No — it moved downstairs</h3><p>It’s tempting to read all that and conclude nobody uses 2PC anymore. That’s the wrong lesson, and it’s worth being precise about, because it’s exactly the kind of half-truth that gets repeated in design reviews.</p><p>What’s true is that you rarely <em>build</em> application-level 2PC across your own microservices anymore. What’s false is that 2PC went away. It got absorbed into the layer beneath you, where systems purpose-built to manage its failure modes run it constantly on your behalf:</p><p>Distributed databases use it internally. When you run a transaction that spans shards in Google Spanner, CockroachDB, YugabyteDB, or TiDB, there’s a two-phase commit underneath. The crucial difference is that each “participant” is itself a consensus group (Paxos or Raft), so the coordinator’s state is replicated and survives a crash — which dissolves the classic single-point-of-failure weakness. That pairing of 2PC for atomicity with consensus for durability is the modern answer to the blocking problem, and it’s why these systems offer strong guarantees without the fragility the textbook version has. Kafka’s exactly-once transactions use a 2PC-style protocol with a transaction coordinator. And XA / JTA two-phase commit is still very much alive in enterprise and banking systems, particularly older database-plus-message-broker setups.</p><p>So the accurate framing isn’t “2PC is obsolete.” It’s: <em>you use 2PC all the time, you just don’t operate it by hand.</em> It lives in your storage and messaging layers now, run by people who solved its hard parts so you don’t have to.</p><h3>Sagas: commit now, apologize later</h3><p>The saga pattern starts from the opposite premise. Instead of holding everyone still until consensus, it lets each step commit its own local transaction immediately — and accepts that if a later step fails, you’ll have to <em>semantically undo</em> the earlier ones.</p><p>A saga is a sequence of local transactions. T1 charges the card and commits. T2 reserves inventory and commits. T3 books the courier and commits. Each step does its work in its own database, for real, right away. If every step succeeds, you’re done. But if T2 fails, the saga runs <strong>compensating transactions</strong> in reverse — C1 to undo T1 — to walk the system back to a consistent state.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fEYdA9EBdDMuCIQkJ3Qssw.png" /><figcaption>Sagas: commit now, apologize later</figcaption></figure><p>The word <em>semantically</em> is doing heavy lifting there, and it’s the most important idea in the whole pattern. A compensating transaction is not a rollback. T1 already committed — the charge is real and visible. C1 can’t pretend it never happened; it can only issue a <em>new</em> transaction that reverses the effect, like a refund. The customer’s statement will show a charge followed by a refund, not a clean slate. And some actions have no clean compensation at all: you can’t un-send a confirmation email, you can only send a correction. Designing a saga is largely the work of figuring out, for each step, what “undo” actually means in the real world.</p><p>What you get in return is everything 2PC gives up. No global locks, so no blocking and no single coordinator holding the system hostage. Each service commits independently, so availability and throughput stay high. And because steps communicate through ordinary messages or events, a saga happily spans heterogeneous databases and third-party services — the payment API doesn’t need to know it’s part of a saga, it just needs to support a charge and a refund. The price is that you trade isolation for <em>eventual</em> consistency: while the saga is mid-flight, the system is in a visibly partial state. The money is charged but the order isn’t confirmed yet. You have to design for that intermediate reality rather than pretend it doesn’t exist.</p><h3>The fork in the road: choreography vs orchestration</h3><p>Once you’ve decided on sagas, you face a second decision that shapes your whole architecture: how do the steps know to run? There are two answers, and the difference is essentially <em>who’s in charge</em>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*G0S27QTzYd5WYTzNyCQr_w.png" /><figcaption>Choreography vs Orchestration</figcaption></figure><p>The appeal is loose coupling. No service depends on a central brain; each one just minds its own business and announces what it did. For a short flow with two or three steps, this is clean and pleasingly decentralized. The trouble shows up as the flow grows. The overall process lives nowhere — to understand “what happens when an order is placed,” you have to trace events across five codebases and hold the sequence in your head. Add a step and you risk subtle cyclic dependencies between services listening to each other. Debugging becomes archaeology. Nobody owns the workflow because the workflow isn’t a <em>thing</em>; it’s a behavior the system happens to exhibit.</p><p><strong>Orchestration</strong> puts one component explicitly in charge: a saga orchestrator. The orchestrator is a state machine that knows the whole sequence. It tells the payment service “charge this card,” waits for the reply, then tells the inventory service “reserve this item,” and so on — issuing commands and reacting to results. If a step fails, the orchestrator knows exactly which compensations to fire and in what order, because the entire flow is encoded in one place.</p><p>The win is clarity. The business process is a real, named, testable object you can point at, monitor, and reason about. Complex flows with branching and conditional compensation are far more manageable when one component owns the logic. The cost is that you’ve reintroduced a central component — one more service to build and operate — and you have to resist the temptation to let it swell into a god object that hoards business logic the individual services should own. The orchestrator should coordinate the dance; it shouldn’t <em>be</em> the dancers.</p><p>The rough rule: reach for choreography when the flow is short and the services are genuinely independent, and reach for orchestration the moment the process has more than a handful of steps, branches, or compensations you need to actually see and trace.</p><h3>So which do you use? Don’t reach — reason</h3><p>Here’s the failure mode this whole article is really about: an engineer reads that sagas are “the modern pattern,” and reaches for one before understanding what it costs. Or reads that 2PC is “old” and rules it out without noticing it’s already running underneath their database. The patterns aren’t the answer. The <em>picture</em> is the answer — and you build the picture before you pick.</p><p>Before you choose anything, get clear on four things about your specific flow. How strong does the isolation need to be — can other parts of the system tolerate seeing a half-finished state for a few seconds, or absolutely not? Do you control every participant, or is one of them a third-party API that will never speak your protocol? How long does the operation take — milliseconds, or minutes spanning human approvals? And what does “undo” mean for each step in the real world — is it a clean reversal, or something irreversible like a sent email or a shipped package? Those four answers point at the pattern far more reliably than any rule of thumb.</p><p>With that picture in hand, the guidance falls out naturally. Two-phase commit earns its place when you need strict isolation, you control all the participants, they all speak a protocol like XA, and the transactions are short — a couple of databases and a message broker inside one trust boundary, where a half-second of held locks is acceptable and a lost order is not. And remember it’s likely already working for you one layer down, inside your distributed database, whether you chose it or not.</p><p>Sagas fit almost everything that looks like a modern distributed system: long-lived business processes, microservices that each own their data, flows that touch services you don’t control, and systems where availability and scale matter more than perfect isolation. You pay for it in design effort — every step needs a compensation, and the whole thing needs to tolerate being half-done — but you get a system that bends instead of blocking. And once you’re on sagas, the same kind of picture decides choreography versus orchestration: short flow with independent services leans choreography; complex flow with branches and compensations you need to actually see leans orchestration.</p><p>The point isn’t to memorize which pattern wins. It’s that the moment you can describe your isolation needs, your participants, your timescale, and your undos out loud, you’ve stopped guessing — and the design review stops being a debate about fashion and starts being a conversation about requirements.</p><h3>The traps that bite everyone</h3><p>A few mistakes recur often enough to name. Treating a compensation as if it were a rollback is the big one — it’s a new, forward transaction with its own failure modes, and it can itself fail, which means compensations need retries too. Forgetting idempotency is the other: in a saga, messages get redelivered and steps get retried, so every operation and every compensation must produce the same result whether it runs once or five times, or you’ll refund the same charge three times. Closely related is the dual-write problem — updating your database and publishing the triggering event as two separate actions, so a crash between them leaves a committed change that nobody downstream ever hears about (the outbox pattern exists precisely to fix this). And don’t ignore the intermediate state: while a saga is in flight, other parts of the system can read data that’s about to be compensated away, so you may need semantic locks or status flags to keep a half-finished order from being treated as a real one.</p><h3>The shift in mindset</h3><p>The hardest part of distributed transactions isn’t any one protocol — it’s giving up the fantasy that you can make a distributed system behave like a single database. Two-phase commit chases that fantasy and pays for it in availability. Sagas abandon it and ask a more useful question instead: not “how do I make this atomic,” but “what does it mean to undo each step, and can I live with the world seeing this half-finished for a moment?”</p><p>Answer that honestly for your own system and the choice between blocking and compensating mostly makes itself. The card got charged and the item sold out — and the difference between a refund that fires automatically and a customer-service ticket is whether you designed the undo before you needed it.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4592565f408a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The Engineer’s Guide to Idempotency: Why Your Payment API Should Be Boring]]></title>
            <link>https://medium.com/@atish.rhabar14/the-engineers-guide-to-idempotency-why-your-payment-api-should-be-boring-e03a42977cf9?source=rss-e55cdc59ce66------2</link>
            <guid isPermaLink="false">https://medium.com/p/e03a42977cf9</guid>
            <category><![CDATA[idempotency]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[system-design-concepts]]></category>
            <category><![CDATA[backend-engineering]]></category>
            <category><![CDATA[distributed-systems]]></category>
            <dc:creator><![CDATA[Atish Rhabar]]></dc:creator>
            <pubDate>Tue, 02 Jun 2026 15:55:29 GMT</pubDate>
            <atom:updated>2026-06-02T15:55:29.032Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*49HP80Jxk9vZ-mWrAKNy4Q.png" /></figure><p>There’s a particular kind of bug that doesn’t show up in your tests, doesn’t trip your linter, and doesn’t surface until a customer emails support to ask why they were charged twice for the same order. It’s not a typo or an off-by-one error. It’s something more architectural: your system did exactly what it was told, twice, because it had no way of knowing it had already done it once.</p><p>This is the problem idempotency solves. And if you build backends — especially anything that touches money — it’s one of the few concepts worth getting genuinely comfortable with rather than nodding along to.</p><h3>What idempotency actually means</h3><p>An operation is <em>idempotent</em> if running it multiple times produces the same result as running it once. Press it again, nothing new happens.</p><p>The classic mental model is an elevator button. Pressing “5” once calls the elevator. Pressing it forty times in a fit of impatience doesn’t summon forty elevators — the system has already registered your intent, and repeating it changes nothing. Compare that to a vending machine, where every coin you insert is counted separately. The elevator is idempotent. The vending machine is not.</p><p>In software, some operations have this property naturally and others don’t. Setting a user’s email to alice@example.com is idempotent — whether it runs once or ten times, the email ends up as alice@example.com either way, because each call <em>overwrites</em> the value. Incrementing a counter is the opposite: every call <em>adds one more</em>, so ten calls leave the counter nine higher than a single call would. The first kind is safe to repeat by its nature; the second isn&#39;t. And that&#39;s the whole game — the work of &quot;making retries safe&quot; is really the work of taking operations that <em>aren&#39;t</em> naturally idempotent, like charging a card, and giving them that same overwrite-don&#39;t-accumulate behavior.</p><h3>Why this matters more than it looks</h3><p>If networks were reliable, idempotency would be a footnote. They aren’t, and that’s the whole story.</p><p>Picture the lifecycle of a single API request. A client sends “charge this card $50.” Your server receives it, charges the card successfully, and starts sending back a 200 OK. Somewhere in transit, the response is lost — a dropped connection, a timeout, a load balancer hiccup. From the client&#39;s perspective, the request simply failed. It has no idea the charge went through.</p><p>So the client does the sensible thing: it retries. And now you’ve charged the card twice for one purchase.</p><p>This is not a rare edge case. At any meaningful scale, retries are constant and unavoidable. Mobile clients drop connections. Message queues redeliver. Service meshes retry transparently on your behalf. In distributed systems we live by a hard rule: <strong>the network can fail at any point, and you can never be sure whether a request that timed out actually completed.</strong> Once you internalize that, idempotency stops being a nice-to-have and becomes the only safe way to let clients retry without fear.</p><p>The stakes scale with the domain. A duplicated “mark as read” is annoying. A duplicated payment, a double-minted token, or a double-spend in a financial ledger is the kind of mistake that ends up in incident postmortems and, occasionally, regulatory filings.</p><h3>The idempotency key pattern</h3><p>The standard solution, used by Stripe, PayPal, and essentially every serious payments API, is the <strong>idempotency key</strong>.</p><p>The idea is simple. The client generates a unique identifier — typically a UUID — for each <em>logical</em> operation it wants to perform, and sends it along with the request, usually in a header:</p><pre>POST /v1/charges<br>Idempotency-Key: 9f8a3c2e-1b4d-4e6f-8a9b-7c6d5e4f3a2b</pre><pre>{ &quot;amount&quot;: 5000, &quot;currency&quot;: &quot;usd&quot;, &quot;source&quot;: &quot;tok_visa&quot; }</pre><p>Crucially, this key stays the same across retries. The first attempt and the fifth attempt of the <em>same</em> operation carry the <em>same</em> key. A genuinely new purchase gets a new key.</p><p>On the server side, the flow looks like this:</p><ol><li>A request arrives with an idempotency key.</li><li>The server checks whether it has seen that key before.</li><li>If not, it processes the request, then stores the key alongside the result.</li><li>If it <em>has</em> seen the key, it skips the work entirely and returns the stored result.</li></ol><p>The client gets the same response whether it’s the first attempt or the tenth, and the card is charged exactly once. The retry becomes safe.</p><h3>Implementing it without lying to yourself</h3><p>The pattern is easy to describe and surprisingly easy to get subtly wrong. A few details separate a real implementation from a demo.</p><p><strong>Store the response, not just the key.</strong> When a retry comes in, the client expects an actual answer — the charge ID, the confirmation. If you only recorded “yes, I’ve seen this key,” you can tell the client it’s a duplicate, but you can’t give it the original result. Cache the full response body and status code keyed by the idempotency key.</p><p><strong>Handle concurrency, not just sequence.</strong> The naive “check if exists, then insert” has a race condition baked in. Two retries can arrive milliseconds apart, both check the store, both find nothing, and both proceed to charge the card — the exact failure you were trying to prevent. The fix is to make the key reservation atomic. Lean on the database: a unique constraint on the idempotency key means the second concurrent insert fails loudly instead of silently double-processing. Many implementations insert a “pending” record first, holding a lock, and only mark it complete once the operation finishes.</p><pre>CREATE TABLE idempotency_keys (<br>    key           UUID PRIMARY KEY,  -- use TEXT if clients may send arbitrary strings<br>    response_body JSONB,<br>    status_code   INT,<br>    created_at    TIMESTAMPTZ DEFAULT now()<br>);</pre><p>That PRIMARY KEY constraint is doing real work — it&#39;s the difference between correctness and a heisenbug. A quick note on the column type: if you control the clients and can guarantee every key is a UUID, the native uuid type stores in 16 bytes instead of 36 and indexes faster. If this is a public API where clients send arbitrary unique strings — as Stripe&#39;s keys are — use TEXT instead, so a perfectly valid non-UUID key doesn&#39;t get rejected at the database layer.</p><p><strong>Fingerprint the request.</strong> What happens if a client reuses an idempotency key but changes the payload — same key, but now charging $5,000 instead of $50? That’s a client bug, and the safe response is to reject it rather than guess. Storing a hash of the original request body lets you detect the mismatch and return an error instead of quietly doing something the client may not intend.</p><p><strong>Expire keys deliberately.</strong> You don’t need to remember every key forever. A retention window — 24 hours is common — covers the realistic retry horizon while keeping the table from growing without bound. Just make the window long enough that legitimate retries after a long outage still land.</p><h3>What HTTP already gives you for free</h3><p>Worth noting: the HTTP spec already classifies methods by idempotency, and the design isn’t accidental.</p><p>GET, PUT, and DELETE are defined as idempotent. Fetching a resource, replacing it wholesale, or deleting it can all be repeated safely — DELETE twice still leaves the resource gone. POST is the odd one out: it&#39;s <em>not</em> idempotent by design, because it typically means &quot;create something new,&quot; and repeating it means creating it again.</p><p>This is precisely why the idempotency-key pattern shows up most often on POST endpoints. You&#39;re retrofitting safe-retry semantics onto the one method that doesn&#39;t have them natively. If you find yourself reaching for an idempotency key on a PUT, it&#39;s worth pausing to ask whether the operation could be expressed as a true replacement instead.</p><h3>The traps people fall into</h3><p>A handful of mistakes recur often enough to name:</p><p>Generating the idempotency key on the <em>server</em> defeats the entire purpose — every retry gets a fresh key and looks like a new request. The key has to originate from the client and survive across attempts.</p><p>Treating idempotency as purely an API-layer concern while the underlying database operation remains unguarded just moves the race condition one layer down. Correctness has to reach all the way to the write.</p><p>Confusing idempotency with deduplication is subtle but real. Idempotency is about an <em>operation</em> being safe to repeat; deduplication is about discarding <em>duplicate messages</em>. They overlap, but a system can dedupe messages and still mishandle a retry that arrives after the dedup window closes.</p><p>And finally: assuming your retry path is rare and therefore not worth hardening. At scale, the unlikely happens constantly. The retry path is a production path.</p><h3>The goal is boredom</h3><p>The best compliment you can pay a payment system is that it’s boring. No surprise charges, no frantic reconciliation, no support tickets about phantom transactions. Idempotency is one of the quiet foundations of that boringness — the thing that lets a client retry a failed request with total confidence that the worst case is simply getting the right answer a second time.</p><p>It’s not glamorous. It won’t impress anyone in a demo. But the next time a connection drops mid-charge and the customer never notices, that silence is the feature working exactly as intended.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e03a42977cf9" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>