Interview: the same job runs twice

A check-then-insert race. Fix it with a UNIQUE index, then explain the B+tree, gap locks, the change buffer and an online migration on 80M rows.

More on Ticket interviews

Keep learning

Overview

SELECT … WHERE user_id=7 → 0 rows Request A checks: nothing queued. Request B checks at the same moment: also nothing. INSERT job (user 7) ✓ A inserts. B inserts too. Nothing in the database says this is wrong. Two welcome emails. INSERT job (user 7) No pre-check. A goes straight to INSERT. B descends the same B+tree and waits on A’s lock for key (7, welcome). COMMIT ✓ A commits. Key (7, welcome) now exists. ERROR 1062 Duplicate entry B’s uniqueness check finds the key. catch 1062 → “already queued” The app treats the error as success. One email. Two clicks, 3 ms apart UNIQUE (user_id, type) Request A Request B Play step 1 Next step Show all = beats.length ? ( The database is now the referee. The check and the write happen in one atomic step inside the index. A check in application code is not atomic with the insert. Any gap between them is a race window.

The same job runs twice

UNIQUE index B+tree insert gap locks online DDL Some users get two welcome emails. Check and insert are separate steps, so two requests both pass. A UNIQUE index lets the database reject the second insert.

Some users get two welcome emails

About 1% of new users get the welcome email twice. The code checks for a queued job first. Still, two pending rows appear. Mostly on mobile, where people double-tap Sign up. duplicate rate jobs table 80M rows enqueue p95 Restated: two near-simultaneous signups for one user both pass the “already queued?” check.

Read the code yourself

Highlighted lines are the ones worth saying out loud. Check, then act, in two separate statements, with no transaction and no constraint. An index on status only. Nothing unique except the id. A second race: two workers can read the same pending job before either marks it running. SELECT, then INSERT. Two requests can slip between them. No UNIQUE key. The database accepts both rows. Same race: two workers can grab one job. Check-then-act (check, then write later) without a lock. Three files, one shape of bug.

Find the root cause one question at a time

Does a duplicate check exist? read enqueue.ts Yes. It looks for a pending job first. Is it correct for one request? trace a single signup Yes. A later signup finds the row and skips. Is it correct for two requests at once? interleave two calls on paper No. Both SELECTs run before either INSERT. Classic check-then-act race. Does the database enforce it anyway? read schema.sql No. There is no unique key on (user_id, type). Anything else with the same shape? read worker.ts Yes. Two workers can pick one job. Note it for later.

Decide the fix, let the AI type it

Moves the rule into the database, where it is atomic. Names the exact error to catch, so real failures still surface. Asks for a parallel test, not just a happy-path test. Check in app code SELECT, then INSERT. Two steps, with a gap between them. UNIQUE index Check and insert happen in one atomic step inside the index.

The interviewer turns the AI off and digs in

Answer out loud, then open the card. How does the database actually enforce UNIQUE? A unique B+tree index (sorted search tree) checks and inserts the key in one locked step. InnoDB walks down the tree to where the key belongs. That is 3–4 pages, usually cached. It holds a lock on that spot while checking. The second insert waits, then gets error 1062. B+tree, not a scan check + insert are atomic loser gets 1062 Walk the tree 3–4 page reads Lock the slot key (7, welcome) Key exists? Insert or 1062 One atomic step inside the index. Does the new index slow writes down? Could it become a bottleneck? A little: each insert writes one more B+tree. Cheap compared with duplicate emails. It costs extra CPU, disk I/O, redo log and buffer-pool memory. Unique indexes skip the change buffer (deferred index writes). The engine must read the page to check. It only hurts at very high insert rates when the index does not fit in memory. write amplification no change buffer for unique memory pressure cost vs correctness B+tree written per insert change buffer for unique keys duplicate emails Why not SELECT … FOR UPDATE before the insert instead? It deadlocks under REPEATABLE READ and races under READ COMMITTED. With no row yet, FOR UPDATE locks the gap (empty range) where it would go. Gap locks do not block each other. Both sessions get one, then both inserts wait on each other. Under READ COMMITTED there is no gap lock, so the race returns. UNIQUE works at every level. gap locks are shared isolation level matters Session A Session B SELECT … FOR UPDATE gap lock ✓ gap lock ✓ (shared) waits for B waits for A → deadlock Can the duplicate-key error itself cause problems under load? locks · deep Yes. A duplicate-key hit takes a shared lock, which can feed a deadlock. With several sessions inserting one key and one rolling back, those locks can deadlock. MySQL documents this. Keep the transaction tiny, retry once on error 1213, or use INSERT … ON DUPLICATE KEY UPDATE. 1062 path takes a lock short transactions retry on 1213 Some job types may run again later. A UNIQUE on (user_id, type) forbids that. Now what? Make it unique only while pending: one pending job per user and type. MySQL has no partial index, but UNIQUE allows many NULLs. partial uniqueness NULLs in unique indexes idempotency keys Counts for UNIQUE? NULLs never collide, so finished jobs are free. Fix worker.ts: two workers grab the same job. Claim jobs in one transaction with FOR UPDATE SKIP LOCKED. SKIP LOCKED (MySQL 8+, PostgreSQL) skips rows another worker holds. No blocking. Add an index on (status, id). Without it, FOR UPDATE locks far more than 10 rows. SKIP LOCKED claim in one transaction index limits locked rows Worker 1 Worker 2 FOR UPDATE SKIP LOCKED locks jobs 1–10 skips 1–10, takes 11–20

The jobs table has 80M rows and already contains duplicates

small batches Ship app change catch 1062 Online ALTER INPLACE, LOCK=NONE Watch replicas they replay the DDL The safe rollout order. How do you ship the unique index? ALTER TABLE … ADD UNIQUE right now Fails after reading 80M rows, because duplicates already exist. Its metadata lock can also stall every query. Outage risk Dedupe first, then online ALTER at low traffic Clean duplicates in batches, ship the 1062 handling, then add the index online. Watch replica lag. Use gh-ost / pt-online-schema-change Builds a shadow table and swaps it in. Safest at scale, but extra tooling and double disk. Works most of the time. But locks expire, Redis fails over, and other insert paths stay unprotected.

Have one ready

Tell me about a time duplicates or a race condition reached production. System, traffic, what the duplicate cost. Alert, ticket or reconciliation job. Root cause The exact interleaving, drawn as two timelines. Fix + guard Constraint or idempotency key, plus a parallel test. What you now check in every review.

Did you show these?

Restated the ticket first Read the code before prompting Named the check-then-act race Put the rule in the database (UNIQUE) Caught only error 1062 Explained the unique B+tree check Priced the index: writes, change buffer, memory Fixed the worker race with SKIP LOCKED Planned around existing duplicates and metadata locks

More courses

  • Jobs, linked to lessons — Browse jobs where every requirement links to the chapter that teaches it. See how ready you are, how long the gap takes to close, and which listings look stale.
  • Match a job post to courses — Paste a job post. Each skill is matched to a track here and put in learning order, foundations first.
  • React patterns from open source — Patterns extracted from Material UI, Radix, React Aria, React Hook Form, Redux Toolkit, TanStack, and Next.js — not slides about hooks.
  • System Design — Core concepts first (SQL vs NoSQL, CAP, indexing, replication, sharding), then designs grouped by what carries them: the database, Redis, Kafka, or many services.
  • NestJS: build a real API — One ticket-booking API, built in order: a plain Node server first, then NestJS modules, validation, a real database, and the features real clients lean on.
  • Microservices — Microservice patterns one diagram at a time: how to split a monolith, how services talk, and how data stays consistent without distributed transactions.
  • Kafka — A beginner-to-senior path through event logs, reliable delivery, production operations, and disaster recovery.
  • AI engineering for software engineers — Eight free reads, in order, for software engineers moving into AI: when to build an agent, how to build one, how to test it, and how the model works underneath.
  • Frontend system design — How a UI is sliced when it is a product, not a page: ownership of state, cache, routes, and what happens when the network lies.
  • TypeScript in depth — The type system as a design tool. Inference, narrowing, generics, and the errors that mean the model is wrong — not a catalog of utility types.
  • CSS in depth — See the box, then the page. Visual chapters from the box model through Flexbox surprises, Grid, selectors, and units, then backgrounds, shapes, and visual effects, each with a playground.
  • Accessibility — Foundations first (WCAG in plain words, semantic HTML, lists, alt text), then hands-on HTML labs, a full pass of WAI-ARIA 1.3, and a final fix-the-page challenge.
  • Docker — What an image is, why layers cache, and how containers find each other on a network.
  • Redis — Fifteen Redis patterns, one picture each: cache, session, lock, counter, rate limiter, queue, and when Redis is the wrong tool.
  • Kubernetes — Kubernetes from zero to operators: why it exists, Pods, Deployments and Services, then configuration, networking, storage, scheduling, scaling and security.
  • AWS — AWS networking in plain English. A VPC is a gated housing society: streets are subnets, the Internet Gateway is the main gate, and a route table is the signboard.
  • Networking: the NetRoute game — NetRoute is a packet logistics game. You wire up computers, switches, routers, firewalls and gateways, set each device, and watch glowing packets travel. If a packet gets dropped, the game shows you which header field was wrong.