Interview: two people book the same room at noon, both get a confirmation

Write skew in a booking system. Step two transactions through six guards: plain snapshot, FOR UPDATE on nothing, slot lock, unique key, SERIALIZABLE +…

More on Ticket interviews

Keep learning

Overview

10:00 Design review 11:00 Standup 13:00 Interview loop A paper sign-up sheet on a meeting room door. The noon line is empty. Ana and Ben both look at it, then each writes a name on a different new line, so noon ends up with two names. Room 123 · sign-up 12:00 (looks free) 12:00 Ana 12:00 Ben two names, one noon Three panels. One: the check finds rows, so FOR UPDATE can lock them. Two: the check finds no rows, so there is nothing to lock and a new row can slip in. Three: pre-made slot rows exist, so everyone locks the same slot row. 1 · Check finds rows FOR UPDATE locks them Ben waits for Ana e.g. a counter row 2 · Check finds nothing new row (phantom) nothing to lock both INSERTs go through 3 · Pre-made slot rows room 123 · 11:00 12:00 13:00 14:00 everyone locks 12:00 a lock cell, not a booking "materialising the conflict" reads: 0 bookings inserts a row Two transactions on a timeline. Both read zero bookings from the same snapshot, each inserts its own new row, and both commit successfully. The room ends with two bookings. both are looking at the same photo: noon is free 12:00 has 2 bookings different rows, so no conflict seen time → Two transactions under serializable snapshot isolation. Each reads the bookings for room 123 and then inserts one. Each insert lands in a range the other transaction read, which trips a wire. The first to commit succeeds and the second is aborted and must retry. read: bookings for room 123, 12–13 insert a booking Nobody waits. The check happens at COMMIT: first one wins, the other retries. Booking requests from many app servers go through a router that hashes the room id. Each room has its own queue and one worker, so requests for the same room run one at a time while different rooms run in parallel. Ana · 123 Ben · 123 queue · room 123 queue · room 456 worker 123 one request at a time worker 456 runs in parallel Same room, same queue, same worker: a clash cannot happen. Different rooms never wait for each other. Plain check, then insert snapshot isolation SELECT count(*) … overlap → 0 Same empty answer. Neither can see the other. INSERT booking 12:00–13:00 A different new row, so there is no write-write conflict. Nothing blocks. Both commits succeed. Two bookings for one room. Each check was true when it ran. The database never saw a conflict: this is write skew. Nothing. That is the problem. FOR UPDATE on the check the doctors trick SELECT … overlap FOR UPDATE → 0 rows Zero rows came back, so there is nothing to lock. Not blocked. Still two bookings. Still double-booked. FOR UPDATE locks rows the check found. When the check finds nothing, there is nothing to lock. It looks safe in code review, which is the dangerous part. Lock a pre-made slot row materialise the conflict SELECT … FROM slots WHERE room=123 AND start=12:00 FOR UPDATE The slot row exists, so Ana gets the lock. SELECT … FROM slots … FOR UPDATE Ben asks for the same row and waits. check count → 0, INSERT booking The lock is released. lock granted · check count → 1 Re-read after you get the lock. A snapshot taken before it could still say 0. ROLLBACK · “room taken” One booking. Ben had to wait, then saw Ana’s row and stopped. You pre-create a row for every room and time, every code path must remember the lock, and writers queue up on it. UNIQUE (room, slot_start) SELECT count(*) → 0 INSERT (room 123, slot 12:00) Same key as Ana’s uncommitted row, so Ben waits. ERROR: duplicate key · “room taken” The constraint did the check. One booking. The unique key is the cheapest guard there is, and it holds even at weak isolation. Only works if a booking is whole slots. A free-form 12:10–12:50 request has no single key to collide on. SERIALIZABLE + retry SSI, as in Postgres The database notes who read which range. Each insert lands in a range the other one read. Tripwire. COMMIT → ERROR 40001 serialization failure The database aborts Ben at commit. retry: SELECT count → 1 · “room taken” One booking. Ben did his work twice, and your code had to catch the error and try again. A retry loop in every write path, short transactions, and more aborts as the room gets busier. One writer per room serial execution send book(123, 12:00) Both land in room 123’s queue, in arrival order. worker: check → 0, insert, commit Only one request runs at a time. No overlap is possible. worker: check → 1, reply “room taken” One booking. There was never a second transaction to race with, so no lock and no retry were needed. All writes for a room must go through the queue. Throughput is one core per shard, and the work must be short. Ana and Ben both ask for room 123 at 12:00. Pick a guard, then step through. Protection strategy bookings · committed rows for room 123, 12:00–13:00 no rows: nobody has booked yet ⚠ double booked ✓ booked Play step 1 Next step Show all Slot lock: waiting SERIALIZABLE: aborted and redone One writer: waiting in line Clashes are rare. SERIALIZABLE is the cheapest: almost nobody is aborted, and nobody waits. A mix. Locks and queues pay a steady waiting cost. SERIALIZABLE starts to abort real work. A hot room. Retries pile on top of the load, so SERIALIZABLE gets worst. The queue stays calm because nothing is redone. How many requests fight for the same room at the same moment? Contention percent cost you feel (relative) more contention You gain It costs Pick when Avoid when Unique key per slot Database refuses the second row, at any isolation level. Bookings must be whole slots. Fixed slots, seats, usernames. Free-form time ranges. Pre-made slot rows + SELECT FOR UPDATE Safe at snapshot isolation. The phantom gets a real row to lock. No SERIALIZABLE, no unique key. SERIALIZABLE is available. SERIALIZABLE + retry loop Catches write skew for any rule. Readers never block. Mixed rules, moderate contention. Very hot rows or long transactions. One writer per room (serial execution) No conflicts at all: no locks, no aborts. Every booking is for one room. Bookings span many rooms or shards. Explain simply: why does snapshot isolation not stop the double booking? explain simply It only catches two writes to the same row, and these are different rows. Each transaction reads a frozen photo. Both photos show noon empty. “Noon is free” went stale when the other committed. The database never knew the app relied on it. premise went stale different rows, no write conflict database cannot see app logic What breaks if we just add FOR UPDATE to the availability check? what breaks if Nothing gets locked: a free room returns zero rows. It works for on-call doctors, because those rows already exist. The missing row is a phantom (a row that appears later). Lock a slot row, or use SERIALIZABLE. phantom named rows exist vs rows absent materialise or serialise You turned on SERIALIZABLE and 8% of bookings now fail with 40001. What do you do? Retry: up to 3 times, with a short random pause. 40001 means “try again”. Cut aborts: short transactions, and an index on the check. Without an index, reads are tracked per table, so false conflicts rise. A hot room? Move it to a unique key or a per-room queue. retry with a limit short transactions + index hot key needs a different tool What would you do instead of fighting isolation levels? what would you do instead Reshape the data so the rule becomes a unique key. One row per room per slot. The database says no for you. Or route a room’s writes to one queue and one worker. Never hold a transaction open while a human clicks. rule as a constraint route by key no user wait inside a transaction When is “one writer, run in order” the right answer, and when is it not? Right for small, single-shard, in-memory work. Wrong for cross-shard or very busy keys. Throughput caps at one core per shard. Cross-shard requests are slow, and more machines do not fix that. Send check + insert as one request, never back-and-forth. short, in-memory no interactive transactions Curveball: a booking must reserve a room (service A) and catering (service B), each with its own database. Now what? staff level No isolation level spans two databases. Guard each one, then sequence. Each service gets its own guard, plus a request id so retries are safe. Room, then catering. If catering fails, release the room. Or 2PC (two-phase commit), which holds locks while it waits. request id for retries compensate or 2PC, with the cost “Repeatable read is safe enough.” It is a snapshot. It misses write skew. FOR UPDATE on an empty result No retry on 40001 Users see random errors. Check in app code, insert later The gap is where the race lives. Named it: write skew via a phantom Why snapshot + empty FOR UPDATE miss it Three fixes, with costs Rule as a unique key, where possible SERIALIZABLE needs retries + short txns Two databases share no isolation level No row was written twice, so snapshot isolation sees no clash. The clash is in the meaning. The database watches who read what. The second one to commit is told its photo went stale, and must retry. On-call doctors Rows exist. FOR UPDATE locks them. Second doctor waits. Free room Zero rows. Nothing to lock. Both inserts pass. Route by room. Inside one room, requests run one by one. Good fit Short work · in memory · one room per request Poor fit Cross-shard work · above one core of writes · chatty transactions Reserve room service A, request id Reserve catering service B, request id release the room Sequence plus undo, since no transaction spans both.

Two people book the same room at noon. Both get a confirmation.

Each request checks the room is free, then inserts. Both checks pass, and the room gets two meetings. write skew SELECT FOR UPDATE SERIALIZABLE + retry serial execution unique key Two people get confirmed for the same room at noon. Both read “free”, then insert different rows. Nothing clashes. Unique slot key, SERIALIZABLE with retries, or one writer per room.

A sign-up sheet on the door

A paper sheet hangs on the meeting-room door. Ana looks. Noon is empty. Ben looks at the same moment. Empty too. Ana writes her name on a new line. Ben writes his on another line. Nobody wrote on the same line, so nobody noticed. Noon now has two names. Each check was true when it was made. Together they broke the rule.

Room 123 has two meetings at 12:00

The API runs SELECT (is it free?), then INSERT, in one transaction. It fails when two people book at nearly the same moment. No unique index: bookings can start at any minute. snapshot (default) double bookings ≈ 3 a day (illustrative) peak load ≈ 40 bookings/s (illustrative) unique key The question: make double booking impossible. Compare three ways and their costs.

Move the timeline. Watch the room.

Slot lock, unique key Error + retry One writer per room What to notice: both red guards fail the same way. Every green guard pays one of these three prices. What to notice: a lock needs a row to hold. Panel 3 gives it one. What to notice: no line wins everywhere. Ask how hot the room is first.

Four ways to say no to the second booking

Postgres SERIALIZABLE (SSI) InnoDB / SQL Server (2PL) Same word, two machines. Two-phase locking is not two-phase commit. Free-form bookings (12:10 to 12:50) on one Postgres, a few hundred rooms. What do you ship? SERIALIZABLE with a retry loop (3 tries) Double bookings Code you must get right Pre-made slot rows + FOR UPDATE Safe, but 12:10 spans slots. Lock them in a fixed order or risk deadlocks. Lock waits Keep snapshot isolation, check in app code first This is the ticket’s bug with extra steps. The race lives in the gap.

A model spoken answer

How do you stop two people booking the same room? Name it Write skew via a phantom row. Cheapest first Whole slots? Unique key on room + slot. General fix SERIALIZABLE + retries + index. If I cannot Lock a slot row, or one queue per room. Waits, retries, or one core per shard.

Four traps and a scorecard

Related: write anomalies, serializability, isolation levels, lost update.

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.