Let’s talk

The OTP the AI wrote

You ask an AI for a login OTP check: 4 digits, expires in 5 minutes. It rejects wrong codes and expired codes. A bot starts guessing. How long until it's in?

In 30 seconds

The problem
A bot logs into someone else's account by guessing their OTP.
Why it happens
The AI-written check handles expiry and wrong codes but never counts guesses. A 4-digit code has 10,000 values, and a script can try them all inside the 5-minute window.
The fix
Spend one of 5 attempts on every guess, in the same atomic UPDATE that reads the code. After 5 wrong guesses the OTP is dead.
In an interview
Every secret a human can type needs an attempt limit, counted atomically: UPDATE … SET attempts = attempts + 1 WHERE attempts < 5 RETURNING code. Five wrong guesses kill the code.

Why it matters

The code does everything the prompt asked: expired codes are rejected, wrong codes are rejected, the right code logs in. Every test passes.

In our run, a bot walked 0000 to 9999 with 50 guesses in flight and found the code after about 7,300 tries, in under 2 seconds on one machine. Over a real network at 100 guesses a second, 10,000 codes still take under 2 minutes. With the attempt limit, exactly 5 wrong guesses got through and everything after that got 429.

Words you need

Rate limit
A cap on how many requests one user can make in a period. Past it, the API answers 429 Too Many Requests.
Atomic
Done as one step that nothing can interrupt. Another request sees it either not started or fully finished.
Read, then write
Read a value, change it in your code, write it back. Another request can read the same old value in between.
Race condition
A bug that only appears when two requests overlap in an unlucky order. Each request is correct on its own.

Picture it

Priya requests an OTP. A bot that knows her phone number starts guessing.

The AI's version: no attempt limit

  1. Bot sends 0000, 0001, 0002…
  2. Each wrong guess: 401, try the next
  3. 50 guesses in flight at a time
  4. Guess 7316 matches: 200 Logged in

Account taken over in seconds, inside the 5-minute window.

5 attempts, spent atomically

  1. Every guess spends an attempt first
  2. Guesses 1–5: 401 Wrong OTP
  3. attempts = 5, the row stops matching
  4. Every later guess: 429, request a new OTP

A 5-in-10,000 chance, and the real user just asks for a new code.

The fixes people try

  • The AI's version

    Fails
    check expiry; compare code

    Nothing counts guesses. 10,000 values is a for-loop.

  • 6 digits instead of 4

    Half a fix
    1,000,000 possible codes

    Slows the bot down, doesn't stop it. Still needs a limit.

  • SELECT attempts, then UPDATE

    Fails
    if (attempts < 5) attempts++

    50 parallel guesses all read attempts = 0 and all get through. The same race as the coupon.

  • Atomic attempt counter

    Works
    UPDATE … WHERE attempts < 5 RETURNING code

    The check and the spend are one statement, so exactly 5 guesses get through even in parallel.

  • Rate-limit sends and verifies

    Works
    per phone and per IP

    On top of the counter. Stops a bot requesting a fresh OTP every 5 tries.

The fix and its cost

Spend an attempt before comparing. UPDATE otps SET attempts = attempts + 1 WHERE phone = $1 AND attempts < 5 AND expires_at > now() RETURNING code. Zero rows back means the code is used up or expired: answer 429 and make the user request a new one.

The counter has to be in the same statement. A separate SELECT and UPDATE lets 50 parallel guesses all read attempts = 0. Then rate-limit OTP sends per phone, or the bot just requests a new code every 5 tries.

What it costs

One column and one statement. Real users who mistype 5 times have to request a new code, which is the point.

Interviewers also listen for: who calls this endpoint

Not just the phone's owner. Any endpoint that checks a secret will be called by a script, so ask: what happens if this runs 10,000 times?

Check yourself

  1. 1Why doesn't the 5-minute expiry protect the account?Show answer

    10,000 guesses take seconds locally and a couple of minutes over a network. The expiry is far longer than the attack.

  2. 2Why must the attempt counter be atomic?Show answer

    With a separate read and write, parallel guesses all see the same old count and all pass. One UPDATE with the condition lets exactly 5 through.

  3. 3Why also limit how often OTPs are sent?Show answer

    Otherwise the bot requests a fresh code every 5 guesses, and you pay for every SMS.

The code

GitHub

otp.bug.ts

import type { Pool } from "pg";

// Prompt: "Write an Express + Postgres endpoint to verify a 4-digit login OTP.
// OTPs expire after 5 minutes."
export async function verifyOtp(db: Pool, phone: string, code: string) {
  const { rows } = await db.query(
    "SELECT code, expires_at FROM otps WHERE phone = $1",
    [phone],
  );
  const otp = rows[0];
  if (!otp || otp.expires_at < new Date()) return { status: 400, error: "OTP expired" };

  // Wrong guess? Rejected... and the caller can simply try the next one.
  if (otp.code !== code) return { status: 401, error: "Wrong OTP" };

  await db.query("DELETE FROM otps WHERE phone = $1", [phone]);
  return { status: 200, loggedIn: true };
}

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

Every secret a human can type needs an attempt limit. Spend the attempt in the same statement that reads the code.