Why Your Node.js MVP Double-Sells Under Load (and the Locking Patterns That Actually Fix It)
Node.js being single-threaded doesn't protect you from race conditions. Here's how double-bookings, reused coupons and overdrawn wallets really happen, how to reproduce them in five minutes, and the fixes we apply, starting with the ones that need no extra infrastructure at all.
"Node.js is single-threaded, so race conditions can't happen." We hear this in almost every technical due-diligence audit. It's the most expensive misconception in backend engineering, and it usually surfaces the first time two customers buy the last item at the same moment.
Race conditions don't crash your server or fill your logs with errors. Everything returns 200. The damage shows up later: an item sold twice, a one-time coupon used five times, a wallet that went negative, a chargeback from a customer you couldn't deliver to. By then it looks like a data mystery rather than a bug.
This guide shows exactly how these bugs happen in Node.js, how to prove whether your app has one, and the fixes we apply in rescue projects. The good news: the best fix usually isn't a fancy distributed lock. It's one well-written database statement.
1.Why "Single-Threaded" Doesn't Save You
It's true that Node.js runs your JavaScript on one thread. But every await is a pause: while your function waits for the database or Stripe, the event loop happily runs other requests, including another request for the very same item. Your code is single-threaded; your business logic is not.
And in production you rarely have one process anyway. Two serverless instances, a PM2 cluster or three containers behind a load balancer are completely separate programs sharing one database. Anything that relies on "only one request at a time" inside a single process is already broken the moment you scale past one instance.
2.Anatomy of a Double-Sale
Here's the pattern behind most race conditions we find. It's called check-then-act: read the state, decide, then write, with awaits in between.
With one ticket left and two buyers clicking at the same time:
| Time | Alice's request | Bob's request |
|---|---|---|
| 0 ms | Reads ticket: AVAILABLE | |
| 3 ms | Reads ticket: AVAILABLE | |
| 5 ms | Charges Alice (waits ~1 s) | |
| 6 ms | Charges Bob (waits ~1 s) | |
| 1.0 s | Writes SOLD, owner = Alice | |
| 1.1 s | Writes SOLD, owner = Bob ✗ |
Both passed the check, both were charged, and Bob's write silently overwrote Alice's. Alice paid for a ticket she no longer owns. The slow Stripe call in the middle makes the window a full second wide, but even a 2 ms database round trip is enough under real traffic.
The same shape hides in many places:
- Inventory: "if stock > 0, decrement" sells more units than you have.
- Coupons: "if not redeemed, apply" lets a one-time code be used several times in parallel.
- Wallets and credits: "if balance ≥ amount, deduct" lets parallel withdrawals overdraw the account.
- Bookings: "if the slot is free, book it" double-books a doctor, a room or a seat.
- Double-clicks: an impatient user on a slow connection triggers the whole flow twice.
3.Reproduce It in 5 Minutes
Clicking twice in your browser won't reliably trigger it. A tiny script will. Point it at a local or staging copy, never at production, with one item in stock:
If more than one request succeeds, you've found it, and you now have a test that proves the fix works. Keep the script: run it against every endpoint that moves money, stock or credits.
4.Three Fixes That Look Right and Aren't
An in-memory mutex
Libraries like async-mutex serialise requests inside one Node.js process. Your race test passes locally, then production runs two instances and each has its own mutex that knows nothing about the other. On serverless, every instance is a separate process. In-memory locks only protect a single process, which is almost never what you deploy.
"Just wrap it in a transaction"
A transaction makes writes all-or-nothing. It doesn't make a read-then-write safe. Under Postgres's default isolation level (READ COMMITTED), two transactions can both read AVAILABLE and both write SOLD, exactly like the timeline above. And if the Stripe call sits inside the transaction, every checkout holds a database connection for a second or more, which drains your connection pool during a spike (we cover that failure in our Prisma serverless guide).
A Redis lock that expires mid-checkout
The popular fix: take a Redis lock with a time-to-live (say 5 seconds), do the checkout, release it. The TTL exists so a crashed process doesn't hold the lock forever. But if the work inside takes longer than the TTL (a slow Stripe response, a GC pause, a cold start), the lock quietly expires, a second request acquires it, and you're back to two buyers inside the critical section. The lock feels safe while losing exactly the guarantee you needed.
The database is the one place every instance shares and the one place that writes for certain. The most reliable fixes make the database itself refuse the second sale, instead of trying to stop the second request from arriving.
5.Fix #1: Let One Statement Decide
Collapse the check and the write into a single conditional update. The database runs it atomically: only one request can flip the row from AVAILABLE, and the rest simply match nothing.
The same idea works for counters and balances: put the condition in the WHERE clause.
No Redis, no lock to forget to release, nothing that expires, and it works identically on one instance or a hundred. Run the race test again: exactly one request succeeds and the other nineteen get a clean "sold out".
6.Fix #2: Unique Constraints and Idempotency Keys
Some rules are really "this combination may only exist once": one redemption per coupon per user, one booking per slot, one order per checkout attempt. Encode them as unique constraints, and the database rejects every duplicate for you, race or no race.
Double-clicks and network retries need an idempotency key: the client generates one ID per checkout attempt and sends it with every retry. The server stores it uniquely before doing any work, and passes it to Stripe so the payment itself is also only created once.
7.Fix #3: Row Locks and Advisory Locks
When the decision needs more than a WHERE clause (several reads, some logic, then writes to multiple tables), lock the row you're deciding about with SELECT … FOR UPDATE. Other transactions touching that row wait until yours commits, then see the new state.
- Advisory locks protect things that aren't a single row, like "only one payout job at a time":
SELECT pg_advisory_xact_lock(hashtext('nightly-payouts'))inside a transaction, released automatically on commit. SERIALIZABLEisolation is the heavy-duty option: Postgres aborts one of two conflicting transactions. It's only safe if you retry on serialization failures (error code40001); without retries it just turns races into random errors.- Always lock in a consistent order (for example by ID) when a transaction touches several rows, or two transactions can wait on each other forever: a deadlock.
8.Fix #4: Reserve, Charge, Confirm
The original bug had a second problem: it charged the card before securing the ticket. When a slow external call is part of the flow, split it into three steps so nothing is held open while you wait on the network:
- The reservation has an expiry (
reservedUntil). A small scheduled job returns expired reservations toAVAILABLE, so abandoned checkouts don't lock stock forever. - With Stripe Checkout or anything asynchronous, step 3 happens in the webhook instead, and that webhook has its own race conditions. We break those down in 7 Stripe webhook mistakes that leak revenue.
9.When a Redis Lock Is the Right Tool
Distributed locks are useful when the thing you're protecting isn't in your database: making sure a slow report is generated only once, stopping two workers from calling the same third-party API for one user, de-duplicating a cron job across instances. In those cases, implement it correctly:
If the work can outlive the TTL, two holders can still overlap. That's fine for "avoid doing expensive work twice", and not fine for "never sell the same seat twice". For anything involving money or inventory, keep the database rule (conditional update, unique constraint or row lock) as the final guard, and treat any Redis lock as an extra layer on top.
10.The Pre-Launch Checklist
Go through every endpoint that touches money, stock, credits or bookings:
- No check-then-act across an
await: the condition lives in the write itself. - Counters and balances update with a guarded
WHERE(stock >= 1,balance >= amount). - "Only once" rules are unique constraints in the schema, not if-statements in code.
- Checkout requests carry an idempotency key, and Stripe calls pass it on.
- No HTTP calls inside database transactions; slow work happens between reserve and confirm.
- Reservations expire and get cleaned up.
- No in-memory mutex relied on in a multi-instance or serverless deployment.
- Any Redis lock uses a unique token, compare-and-delete release, and a database guard behind it.
- A concurrency test (like the 20-request script) runs against each critical endpoint.
Race conditions are the silent killers of early SaaS products: no crash, no error, just numbers that stop adding up until a customer, an accountant or an investor notices. Fixing them is rarely a rewrite. It's usually a handful of carefully placed constraints and atomic writes, and it's much cheaper before launch than after the first double-sale.
Note on Organization Security:We never require full GitHub/GitLab organization admin access. A read-only invite to the specific repository and branch being audited is all that is required, keeping your broader infrastructure completely isolated.
Not sure which methodology fits your application?
We'll analyze your stack, endpoints, and repo requirements in a quick 10-minute triage.