DEV Community

JavaScript Mastery
JavaScript Mastery

Posted on

What actually happens when 10,000 people click "Buy" at the same time

Black Friday just ended. Every checkout you used last week had to survive the same handful of problems, and most of them never show up on localhost.

Your code works when you test it. You click Buy, the order goes through, the email arrives. Then a launch goes well, a few thousand people hit the same endpoint in the same minute, and you find out what your code actually does.

Here are the four things that break first, and the boring, reliable fix for each. The examples use Node.js (Express 5), Postgres (node-postgres) and Stripe, but the ideas carry over to any stack.

1. Two people buy the last ticket

Most first-version checkouts look like this:

const { rows } = await pool.query(
  'SELECT stock FROM products WHERE id = $1',
  [productId]
);

if (rows[0].stock > 0) {
  await pool.query(
    'UPDATE products SET stock = stock - 1 WHERE id = $1',
    [productId]
  );
  // create order...
}
Enter fullscreen mode Exit fullscreen mode

Read, check, write. Looks fine. Now send two requests at the same moment with one item left:

  1. Request A reads stock = 1.
  2. Request B reads stock = 1.
  3. Both pass the check.
  4. Both decrement. Stock is now -1, and you've sold something you don't have.

That's a race condition, and you'll never see it in testing because you never send two requests in the same millisecond.

The fix: make the check and the write one atomic operation.

const { rowCount } = await pool.query(
  `UPDATE products
   SET stock = stock - 1
   WHERE id = $1 AND stock > 0`,
  [productId]
);

if (rowCount === 0) {
  throw new Error('Sold out');
}
Enter fullscreen mode Exit fullscreen mode

Postgres locks the row while it updates it. The second request waits, re-checks stock > 0 against the new value, finds 0, and updates nothing. rowCount tells you who won.

Add a constraint as a safety net, so even a future bug can't push stock below zero:

ALTER TABLE products
  ADD CONSTRAINT stock_non_negative CHECK (stock >= 0);
Enter fullscreen mode Exit fullscreen mode

2. The double charge

User clicks Pay. Spinner. Nothing happens for four seconds, so they click again. Or their phone drops from Wi-Fi to mobile data and the client retries. Your server gets two identical checkout requests and happily processes both.

The fix: idempotency keys. The client generates one unique key per checkout attempt and sends it with every retry of that attempt. The server processes each key once and replays the saved result for repeats.

Client:

// Generate once when the checkout page loads, not on every click
const idempotencyKey = crypto.randomUUID();

await fetch('/api/checkout', {
  method: 'POST',
  headers: {
    'Content-Type': 'application/json',
    'Idempotency-Key': idempotencyKey,
  },
  body: JSON.stringify({ productId }),
});
Enter fullscreen mode Exit fullscreen mode

Server table:

CREATE TABLE idempotency_keys (
  key        TEXT PRIMARY KEY,
  user_id    TEXT NOT NULL,
  response   JSONB,
  created_at TIMESTAMPTZ NOT NULL DEFAULT now()
);
Enter fullscreen mode Exit fullscreen mode

Server route:

app.post('/api/checkout', async (req, res) => {
  const key = req.get('Idempotency-Key');
  if (!key) return res.status(400).json({ error: 'Missing Idempotency-Key' });

  // Claim the key. Only one request can insert it.
  const claim = await pool.query(
    `INSERT INTO idempotency_keys (key, user_id)
     VALUES ($1, $2)
     ON CONFLICT (key) DO NOTHING`,
    [key, req.user.id]
  );

  if (claim.rowCount === 0) {
    // Seen this key before: return the saved result
    const { rows } = await pool.query(
      'SELECT user_id, response FROM idempotency_keys WHERE key = $1',
      [key]
    );
    if (rows[0].user_id !== req.user.id) {
      return res.status(422).json({ error: 'Invalid key' });
    }
    if (!rows[0].response) {
      return res.status(409).json({ error: 'Still processing' });
    }
    return res.json(rows[0].response);
  }

  try {
    const order = await createOrder(req.user.id, req.body.productId);
    await pool.query(
      'UPDATE idempotency_keys SET response = $2 WHERE key = $1',
      [key, order]
    );
    return res.json(order);
  } catch (err) {
    // Release the key so the user can retry after a real failure
    await pool.query('DELETE FROM idempotency_keys WHERE key = $1', [key]);
    throw err; // Express 5 passes this to your error handler
  }
});
Enter fullscreen mode Exit fullscreen mode

Pass a key further down too. Stripe accepts its own idempotency key, so a retry between your server and Stripe can't create a second payment:

const paymentIntent = await stripe.paymentIntents.create(
  {
    amount: order.amountInCents,
    currency: 'usd',
    metadata: { orderId: order.id },
  },
  { idempotencyKey: `order_${order.id}` }
);
Enter fullscreen mode Exit fullscreen mode

Delete old keys on a schedule; keeping them for a day or so is common.

Yes, also disable the Pay button after the first click. It helps, but it's UX, not a guarantee. The server is the only place you can actually enforce "once".

3. The webhook that arrives twice

Payment succeeds. Stripe sends payment_intent.succeeded to your webhook. Your handler grants access, sends the receipt, adds the Discord role. Then the same event arrives again.

That's normal. Stripe's webhook docs say your endpoint can receive the same event more than once, and events aren't guaranteed to arrive in order. If your handler isn't ready for that, users get two receipts, or two of something that costs you money.

The fix: record the event ID and skip anything you've already handled.

app.post(
  '/webhooks/stripe',
  express.raw({ type: 'application/json' }),
  async (req, res) => {
    let event;
    try {
      event = stripe.webhooks.constructEvent(
        req.body,
        req.get('stripe-signature'),
        process.env.STRIPE_WEBHOOK_SECRET
      );
    } catch {
      return res.sendStatus(400); // bad signature
    }

    const client = await pool.connect();
    try {
      await client.query('BEGIN');

      const { rowCount } = await client.query(
        'INSERT INTO processed_events (id) VALUES ($1) ON CONFLICT (id) DO NOTHING',
        [event.id]
      );

      if (rowCount === 1) {
        await handleEvent(client, event); // DB writes use the same transaction
      }

      await client.query('COMMIT');
      res.sendStatus(200);
    } catch (err) {
      await client.query('ROLLBACK');
      res.sendStatus(500); // Stripe will retry
    } finally {
      client.release();
    }
  }
);
Enter fullscreen mode Exit fullscreen mode

The insert and the work share one transaction. If the handler fails, the event ID rolls back too, so Stripe's retry gets processed instead of skipped.

One catch: emails and other outside calls can't be rolled back. Which brings us to the last problem.

4. Doing everything inside the request

A checkout that also generates a PDF invoice, sends two emails, calls the Discord API and updates your CRM is slow on a normal day. Under load it's slow, then it times out, then the client retries, and you're back at problem 2.

The fix: do the minimum in the request, queue the rest. The request (or webhook) does only what must be correct right now: reserve stock, record the payment, grant access. Everything else becomes a job.

With BullMQ and Redis:

import { Queue } from 'bullmq';

const connection = { host: process.env.REDIS_HOST, port: 6379 };
const postPurchase = new Queue('post-purchase', { connection });

// After the order is marked paid:
await postPurchase.add(
  'send-receipt',
  { orderId },
  {
    jobId: `receipt-${orderId}`,
    attempts: 5,
    backoff: { type: 'exponential', delay: 2000 },
  }
);
Enter fullscreen mode Exit fullscreen mode
// worker.js runs as a separate process
import { Worker } from 'bullmq';

const connection = { host: process.env.REDIS_HOST, port: 6379 };

new Worker(
  'post-purchase',
  async (job) => {
    if (job.name === 'send-receipt') {
      await sendReceiptEmail(job.data.orderId);
    }
  },
  { connection }
);
Enter fullscreen mode Exit fullscreen mode

A custom jobId stops the same receipt from being queued twice while that job still exists. Retries with backoff mean a flaky email provider delays a receipt instead of failing a checkout. And you can scale workers separately from your API.

If you need a hard guarantee that the database write and the job happen together, look up the transactional outbox pattern. That's the next step up.

The pre-launch checklist

  • Stock and seat changes are atomic (UPDATE ... WHERE stock > 0), with a CHECK constraint behind them
  • Checkout accepts an idempotency key, and you pass one to your payment provider
  • Webhook handlers dedupe by event ID inside a transaction
  • Anything slow or external runs in a queue with retries
  • The checkout endpoint is rate limited, so bots and retry storms can't take everyone else down with them
  • You've load-tested with real concurrency (k6 or autocannon), not by clicking twice

None of this is clever. It's the boring backend work that decides whether a good launch feels like a win or a weekend of refunds.

We're building a full backend course around this kind of work: databases, APIs and backend architecture, with interactive demos, code sandboxes and a project you build and deploy. If you want in when it opens, join the Ultimate Backend Course waitlist.

What's the worst bug you've shipped that only showed up in production? Tell me in the comments.

Adrian

Top comments (0)