Let’s talk

The coupon the AI wrote

You ask an AI for a coupon API: WELCOME500, ₹500 off, valid for the first 10 uses. It works in every test. Then the sale starts and 50 people apply it in the same second. How many get ₹500 off?

In 30 seconds

The problem
A coupon limited to 10 uses gets used 50 times during a sale.
Why it happens
The AI-written endpoint reads the usage count, checks it, then increments in a second statement. Concurrent requests all read the same old count, so they all pass.
The fix
One conditional UPDATE that checks and increments together. Zero rows back means expired.
In an interview
A limit check and the write that uses it must be one statement. UPDATE … SET used = used + 1 WHERE used < max_uses RETURNING …: zero rows back means the coupon is gone.

Why it matters

The code is clean and the test the AI writes with it passes: apply the coupon 11 times in a row and the 11th is rejected.

In our run, 50 users applied WELCOME500 at the same moment against real Postgres. All 50 got ₹500 off: ₹20,000 of discount nobody meant to give, the same result on every run. With the conditional UPDATE, exactly 10 got it and 40 were told it expired.

Words you need

Race condition
A bug that only appears when two requests overlap in an unlucky order. Each request is correct on its own.
Read, then write
Read a value, change it in your code, write it back. Another request can read the same old value in between.
Atomic
Done as one step that nothing can interrupt. Another request sees it either not started or fully finished.
Row lock
While one transaction updates a row, the database makes every other update to that row wait its turn.

Picture it

WELCOME500 has 10 uses. The sale starts and 50 people tap Apply together.

The AI's version: read, check, write

  1. All 50 run SELECT → used = 0
  2. All 50 pass used < 10
  3. All 50 run UPDATE used = used + 1
  4. Counter ends at 50

50 discounts for a 10-use coupon, and no error anywhere.

One conditional UPDATE

  1. Each request: UPDATE … WHERE used < max_uses
  2. Row lock makes them take turns
  3. Requests 1–10 match and increment
  4. Request 11 sees used = 10, matches nothing

Exactly 10 discounts. 40 people told it expired.

The fixes people try

  • The AI's version

    Fails
    SELECT used; if (used < max) UPDATE

    Every concurrent request reads the same count before anyone writes.

  • Ask the AI to "make it safe"

    Fails
    wrap it in a transaction

    At the default isolation level, both transactions still read used = 0. A transaction alone doesn't lock what you SELECT.

  • SELECT … FOR UPDATE

    Works
    BEGIN; SELECT … FOR UPDATE; UPDATE; COMMIT

    Locks the row while you decide. More code and a longer lock than you need here.

  • CHECK (used <= max_uses)

    Half a fix
    ALTER TABLE coupons ADD CHECK …

    A good backstop: the extra increment errors. You still need to handle that error cleanly.

  • Conditional UPDATE

    Works
    UPDATE … WHERE used < max_uses RETURNING

    The check is part of the write. One statement, and Postgres serialises it on the row.

The fix and its cost

Move the check into the write. UPDATE coupons SET used = used + 1 WHERE code = $1 AND used < max_uses RETURNING discount. Postgres takes a row lock for each UPDATE, so concurrent requests queue: the 11th one re-checks used = 10, the WHERE fails, and it gets zero rows back.

It's the same check-then-act race as a double-booked seat, just written by an AI. Nothing in the prompt says concurrent, and nothing in a one-user test shows the gap, so the generated code looks finished.

What it costs

Nothing extra. One statement instead of two, and a second lookup only on the rejection path to tell expired from invalid.

Interviewers also listen for: how to review AI code

For any endpoint that spends something limited (stock, seats, coupons, quota), ask what happens if 50 of these arrive at once. If the answer depends on a value read earlier, it's a race.

Check yourself

  1. 1Why does the counter end at exactly 50 if the code is broken?Show answer

    used = used + 1 is atomic, so no increment is lost. The bug is the check before it, which every request passed with a stale count.

  2. 2Why doesn't the AI's own test catch it?Show answer

    It applies the coupon one request at a time. The race needs requests that overlap.

  3. 3What does zero rows from the conditional UPDATE mean?Show answer

    Either the coupon is used up or the code doesn't exist. A quick lookup tells which one to report.

The code

GitHub

coupon.bug.ts

import type { Pool } from "pg";

// Prompt: "Write an Express + Postgres endpoint to apply a coupon code.
// Each coupon has max_uses. Reject it when it's used up."
// The answer AI assistants typically give:
export async function applyCoupon(db: Pool, code: string, userId: string) {
  const { rows } = await db.query(
    "SELECT discount, max_uses, used FROM coupons WHERE code = $1",
    [code],
  );
  const coupon = rows[0];
  if (!coupon) return { status: 404, error: "Invalid coupon" };
  if (coupon.used >= coupon.max_uses) return { status: 410, error: "Coupon expired" };

  // 50 requests at once all got here with used = 0.
  await db.query("UPDATE coupons SET used = used + 1 WHERE code = $1", [code]);
  await db.query("INSERT INTO redemptions (code, user_id) VALUES ($1, $2)", [code, userId]);
  return { status: 200, discount: coupon.discount };
}

Example code. The tested version, with a proof test against real Postgres, lands in the repo.

Star the repo for the runnable version

Each trap in this world ships with the bug, the fix and a proof test that fires concurrent requests at a real database.

Remember

If AI code reads a count, decides, then writes, ask what 50 requests at once would do. Put the check inside the write.