Let’s talk
Back to Writing
•7 min read•
authenticationPostgreSQLAI-generated codeinterview trapsrate limiting

The OTP the AI Wrote: Why Every Login Code Needs an Attempt Limit

Diagram of a bot sending many OTP guesses to a login endpoint, with an attempt counter stopping it after five wrong tries

Here is a scenario that shows up in a lot of codebases written quickly. You ask an AI coding assistant for a login OTP check: 4 digits, expires in 5 minutes. It writes clean code. Expired codes are rejected. Wrong codes are rejected. The right code logs you in and deletes the OTP. Every test you would think to write passes.

Then a bot starts guessing. How long until it is in?

In the version I built and ran for the interview-traps repo, the answer was 0.7 seconds. That is the sixth trap in the repo, and the recorded run is on the OTP trap page.

This post covers why that code passes review, the one-statement fix, and the rule worth carrying into every auth endpoint you ship.

The code an assistant usually writes

The prompt in the repo is two lines:

Write an Express + Postgres endpoint to verify a 4-digit login OTP.
OTPs expire after 5 minutes.

The answer looks like this. It is the core of bug.ts in the repo:

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 "400 OTP expired";
if (otp.code !== code) return "401 Wrong OTP";

await db.query("DELETE FROM otps WHERE phone = $1", [phone]);
return "200 Logged in";

It does everything the prompt asked. A reviewer would approve it. The repo's first proof test checks exactly this: a wrong code gets 401, the right code gets 200. Both pass.

What the prompt did not say is that someone other than the phone's owner will call this endpoint. Nothing in the code counts guesses.

Why expiry is not a defence

A 4-digit OTP has 10,000 possible values. Expiry feels like a limit, but it limits time, not tries. Five minutes is a very long time for a script.

The repo's episode has a bot walk 0000 to 9999 in order against one phone's OTP, keeping 50 guesses in flight at once, against a real Postgres on the same machine. The run output from the README:

❌ The bot guessed OTP 7316 after 7,350 tries in 0.7s. The code was valid for 5 minutes. Account taken over.

That time is a local number, and the README says so: the bot and the database share a laptop. Over a real network it is slower, but not slow enough. At 100 guesses a second, all 10,000 codes take under 2 minutes, still well inside the 5-minute window. The proof test asserts the bot finds the code in less than 300 seconds.

This is a well-documented weakness. MITRE lists it as CWE-307, Improper Restriction of Excessive Authentication Attempts. NIST's digital identity guidelines go further: SP 800-63B section 3.2.2 says a verifier shall limit consecutive failed attempts on one authenticator to no more than 100, and that 100 is an upper bound, not a target. A short code is exactly the case the rule exists for.

Why the AI did not add a limit

The assistant is not being careless. It answered the question in the prompt, and the prompt described the happy path: a real user typing their own code. Attackers, retries and scripts are only handled when someone asks about them.

Developers often write the same shape by hand, for the same reason. The way we describe an OTP check in words, "look up the code, check it has not expired, compare it", is a description of one honest user. The endpoint is not only called by honest users.

A habit that helps: whenever you prompt for an auth endpoint, add one sentence. "Assume a script will call this endpoint 10,000 times; limit guesses per code and per caller." Then read the answer and check it actually counts something.

The fix: spend an attempt before comparing

The fix in fix.ts adds an attempts column and spends one attempt in the same statement that reads the code:

const { rows } = await db.query(
  `UPDATE otps SET attempts = attempts + 1
   WHERE phone = $1 AND attempts < 5 AND expires_at > now()
   RETURNING code`, [phone]);
if (rows.length === 0) return "429 Too many attempts, request a new OTP";
if (rows[0].code !== code) return "401 Wrong OTP";

Every guess costs one attempt before the comparison happens. After 5 wrong guesses the row no longer matches the WHERE clause, zero rows come back, and the OTP is dead. The real user asks for a new one. The bot is back to a 5-in-10,000 chance per code.

Run against the same bot, the README output is:

✅ 5 wrong guesses allowed, then every guess got 429. The OTP died before the bot got close.

The proof test asserts the code is never cracked, exactly 5 wrong guesses were allowed, and the attempts column ends at 5.

The part most fixes get wrong: the counter must be atomic

A common first attempt at this fix reads attempts, checks it in code, then runs a second UPDATE attempts = attempts + 1. That looks right and fails the same way the coupon the AI wrote fails. With 50 guesses in flight, all 50 read attempts = 0 before any of them writes, so all 50 pass the check. The limit of 5 lets 50 through.

Putting the condition inside the UPDATE closes that gap. Postgres locks the row for each update, and under the default Read Committed level a waiting update re-checks its WHERE clause against the new row before it applies. So the guesses take turns, and the sixth one sees attempts = 5 and gets nothing back. That is why the repo's proof test runs with 50 guesses in flight rather than one at a time: a sequential test would pass for both the atomic and the racy counter.

It is the same rule as the double-booked seat: never check and act in two separate statements. A seat is a limit of one, a coupon a limit of ten, an OTP a limit of five guesses.

What else belongs around it

The attempt counter is the minimum. The repo's README lists what interviewers accept on top, and each one closes a different hole:

ApproachWhen
Attempt counter in the same atomic UPDATEAlways. The minimum for any OTP.
Rate-limit verify per phone and per IPAlways, on top. Stops one IP spraying many phones.
Rate-limit OTP sends tooAlways. Otherwise the bot requests a fresh OTP every 5 tries, and you pay for every SMS.
6 digits instead of 4Helps (1,000,000 values), does not replace the limit.
Store a hash of the code, compare in constant timeGood hygiene. A leaked table should not hand out live codes.

The send limit deserves a second look. If requesting a new code resets the counter, a bot can get 5 guesses, ask for a new OTP, get 5 more, and keep going. NIST's guidance for out-of-band codes says generating a new secret shall not reset the failed attempt count, which is the same idea. Count failures per phone, not only per code.

Sends are also where the limiter's own failure mode matters. If your rate limiter depends on Redis and Redis goes down, an OTP endpoint should fail closed, not open, as the Redis-down trap in the Rate Limiter world shows. An open OTP endpoint during an outage is unlimited guesses and an unlimited SMS bill.

The rule

The repo's interview rule for this trap:

Every secret a human can type needs an attempt limit, counted atomically. Five wrong guesses kill the code.

OTPs are the obvious case. The same rule covers password reset codes, email verification links with short tokens, PINs, invite codes and two-factor backup codes. If a person can type it, a script can type it faster.

My recommendation for any AI-written auth endpoint: ask one question in review. What happens if a script calls this 10,000 times? If the honest answer is "it keeps comparing", fix it before launch.

When this is enough, and when to get help

For one app on one Postgres database, you can check this in an afternoon. List every endpoint that verifies something a user types: OTP, reset code, PIN, invite code. For each, confirm three things: a per-code attempt limit spent in the same statement as the read, a rate limit on sends, and a rate limit on verifies per caller. Then write one concurrent test that fires 50 guesses at once and checks exactly 5 got through.

It gets harder when auth is split across a provider, a cache and your own API, or when a lot of it was generated quickly. That is where a structured review is worth it. The checklist in what to audit in a vibe-coded MVP covers auth alongside the rest, and if you are considering moving away from typed codes altogether, a passkeys rollout plan that preserves recovery is the next read.

Frequently Asked Questions

Is a 5-minute expiry enough to protect a 4-digit OTP?

No. Expiry limits how long a code lives, not how many guesses it takes. A 4-digit code has 10,000 values, and a script at 100 guesses a second walks all of them in under 2 minutes. You need an attempt limit that kills the code after a few wrong guesses.

Does switching to a 6-digit OTP fix brute force?

It helps, because the guess space grows to 1,000,000 values, but it does not replace the attempt limit. Without a limit, a bigger space only means the script runs longer. Keep both: 6 digits and an atomic attempt counter.

Related Reading

Next Step

Run it yourself: clone the interview-traps repo, start Postgres with npm run db:up, then run npm run 06:bug and npm run 06:fix. The recorded replay is on the OTP trap page, next to the other traps in Labs.

If your SaaS has login codes, reset links or invite codes and much of that code was written fast or by an assistant, that is one of the first things my production readiness upgrade checks. Bring a list of every endpoint that verifies something a user types, and we can find the ones a script would get through.

Working on a SaaS that's starting to feel fragile?

Talk to an engineer about the parts that break first — without rewriting what already works. We'll recommend focused support or a compact team based on your scope.

Talk to an Engineer