Skip to main content
Home/Engineering Blog/Why Your Node.js MVP Double-Se...
ARCHITECTURE // DEEP-DIVE

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.

ROOT CAUSECheck, then ActReading state, awaiting, then writing it
SYMPTOMDouble SalesTwo buyers, one item, two charges
COMMON TRAPTTL LocksRedis locks that expire mid-checkout
BEST FIXAtomic WritesLet one database statement decide
HawkInspect Pro Engineering
•15 min read

"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.

Race condition
checkout.ts
app.post('/checkout', async (req, res) => {
  const { ticketId, userId } = req.body;

  const ticket = await db.ticket.findUnique({ where: { id: ticketId } });  // 1. check
  if (ticket.status !== 'AVAILABLE') return res.status(409).send('Sold out');

  await stripe.paymentIntents.create({ /* ... */ });                      // 2. slow await

  await db.ticket.update({                                                 // 3. act
    where: { id: ticketId },
    data: { status: 'SOLD', ownerId: userId },
  });
  res.send('Success');
});

With one ticket left and two buyers clicking at the same time:

TimeAlice's requestBob's request
0 msReads ticket: AVAILABLE
3 msReads ticket: AVAILABLE
5 msCharges Alice (waits ~1 s)
6 msCharges Bob (waits ~1 s)
1.0 sWrites SOLD, owner = Alice
1.1 sWrites 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:

Run locally
race-test.mjs
// Fire 20 purchases of the last ticket at the same moment
const results = await Promise.all(
  Array.from({ length: 20 }, (_, i) =>
    fetch('http://localhost:3000/api/checkout', {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ ticketId: 'vip-1', userId: 'user-' + i }),
    }).then((r) => r.status)
  )
);

const ok = results.filter((s) => s === 200).length;
console.log(ok, 'successful purchases');   // anything above 1 is a race condition

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 rule behind all three

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.

Atomic
reserve-ticket.ts
const { count } = await prisma.ticket.updateMany({
  where: { id: ticketId, status: 'AVAILABLE' },   // the check...
  data: {                                          // ...and the write, in one statement
    status: 'RESERVED',
    reservedBy: userId,
    reservedUntil: new Date(Date.now() + 10 * 60_000),
  },
});

if (count === 0) return res.status(409).json({ error: 'Sold out' });

The same idea works for counters and balances: put the condition in the WHERE clause.

stock.sql
-- Never sells below zero, no matter how many requests arrive at once
UPDATE products
SET stock = stock - 1
WHERE id = $1 AND stock >= 1
RETURNING stock;   -- no row returned = out of stock

-- Never overdraws a wallet
UPDATE wallets
SET balance = balance - $2
WHERE id = $1 AND balance >= $2
RETURNING balance;
Why we reach for this first

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.

schema.prisma
model CouponRedemption {
  id       String @id @default(cuid())
  couponId String
  userId   String
  @@unique([couponId, userId])     // a second redemption fails at the database
}

model Booking {
  id     String @id @default(cuid())
  slotId String @unique            // one booking per slot, ever
  userId String
}

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.

Double-click safe
checkout.ts
// Client: one key per attempt, reused if the user clicks again or the request retries
const idempotencyKey = crypto.randomUUID();

// Server: claim the key first; a duplicate fails here instead of charging twice
await prisma.checkoutAttempt.create({ data: { key: idempotencyKey, userId } });

await stripe.paymentIntents.create(
  { amount, currency: 'usd', customer: customerId },
  { idempotencyKey },                // Stripe returns the same PaymentIntent on retries
);

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.

Row lock
withdraw.ts
await prisma.$transaction(async (tx) => {
  // Lock this wallet row until the transaction ends
  const [wallet] = await tx.$queryRaw<{ id: string; balance: number }[]>`
    SELECT id, balance FROM "Wallet" WHERE id = ${walletId} FOR UPDATE`;

  if (wallet.balance < amount) throw new Error('Insufficient funds');

  await tx.wallet.update({ where: { id: walletId }, data: { balance: { decrement: amount } } });
  await tx.ledgerEntry.create({ data: { walletId, amount: -amount, reason: 'withdrawal' } });
});   // keep it short: no HTTP calls in here
  • 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.
  • SERIALIZABLE isolation is the heavy-duty option: Postgres aborts one of two conflicting transactions. It's only safe if you retry on serialization failures (error code 40001); 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:

Production pattern
checkout.ts
// 1. Reserve atomically (Fix #1): short, no external calls
const reserved = await reserveTicket(ticketId, userId);
if (!reserved) return res.status(409).json({ error: 'Sold out' });

// 2. Charge outside any lock or transaction, with an idempotency key
try {
  await stripe.paymentIntents.create(
    { amount, currency: 'usd', customer: customerId, payment_method, confirm: true },
    { idempotencyKey: `ticket-${ticketId}-${userId}` },
  );
} catch (err) {
  await releaseTicket(ticketId, userId);   // payment failed: give the ticket back
  throw err;
}

// 3. Confirm the sale
await prisma.ticket.update({ where: { id: ticketId }, data: { status: 'SOLD', ownerId: userId } });
  • The reservation has an expiry (reservedUntil). A small scheduled job returns expired reservations to AVAILABLE, 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:

Correct pattern
redis-lock.ts
const lockKey = 'lock:report:' + reportId;
const token = crypto.randomUUID();   // proves ownership when releasing

// Acquire only if nobody holds it; expire automatically if we crash
const acquired = await redis.set(lockKey, token, 'PX', 30_000, 'NX');
if (!acquired) return res.status(429).json({ error: 'Already in progress' });

try {
  await generateReport(reportId);
} finally {
  // Release only if it's still OUR lock (compare-and-delete in one atomic step).
  // A plain DEL could delete a lock another request acquired after ours expired.
  await redis.eval(
    "if redis.call('get', KEYS[1]) == ARGV[1] then return redis.call('del', KEYS[1]) else return 0 end",
    1, lockKey, token,
  );
}
A lock with a TTL is a performance tool, not a guarantee

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.