Interview: the order is saved, the message to search and email never left

The dual-write bug. Pick dual write, outbox + relay, log-based CDC or 2PC, break something, and see what survives. Idempotent consumers included.

More on Ticket interviews

Keep learning

Overview

A shop ledger page holds the sale and a to-tell-the-warehouse note on the same page. A runner reads the note and tells the warehouse. The warehouse checks its list of slip numbers and ignores a slip it has already seen. Shop ledger · page 9 Sale #17 · 2 kettles To tell: ship #17 written in one go slips seen: "#17 again? skip." Phone first, write later? A power cut in between loses the call. Two clients set the same item X, one to A and one to B, writing to the database and to the search index separately. The database receives A then B and ends at B. The search index receives B then A and ends at A. The two stay different forever and no error appears.

Client 2

Database receives ends as B Search index receives ends as A Different forever. Nothing failed, nothing logged.

Broker

translate(0 24) Two routes out of the database. Top: the app writes the order and an outbox row in one transaction, and a relay reads the unsent outbox rows and publishes them. Bottom: the app writes only the order, and a change data capture tool reads the database log and publishes each change in commit order. Both end at a broker and consumers that skip duplicates. A · Outbox + relay same commit polls unsent B · Log-based CDC already there CDC tool reads the log Two-phase commit. The coordinator asks the database and the broker to prepare, and both vote yes. The coordinator crashes before saying commit. Both participants are now in doubt: they cannot commit or abort alone, so they wait and keep their locks. crashed after the yes votes 1 prepare? · 2 yes 3 "commit" never sent in doubt · row locks held in doubt · message held Voting yes was a promise. They cannot decide alone, so they wait. Dual write commit, then publish Outbox + relay note saved with the order Log-based CDC read the database log Two-phase commit one vote across both Good day App crashes after the commit Broker is down for a minute Worker dies before saying “done” order saved 1 message search updated 1 COMMIT order 2 publish “order paid” 3 consumer updates search Works on a good day. The two writes are separate, so nothing ties them together. 0 messages never updated — crash — 2 publish never runs The order is real and nobody was told. No error, no retry, no trace. This is the dual-write bug. publish fails 2 publish → broker unreachable 3 too late to undo. A retry loop dies with the process You cannot un-commit. Either the user sees an error for a paid order, or the event is dropped. message twice email sent twice 1 COMMIT order · 2 publish 3 worker sends email, dies before ack 4 broker redelivers → email again Delivery is at-least-once. The same message can arrive twice, so the consumer must cope. order + outbox row, one commit 1 message, a moment later 1 BEGIN · INSERT order · INSERT outbox row · COMMIT 2 relay reads unsent outbox rows 3 relay publishes, marks row sent Both writes are in the same database, so they succeed or fail together. order + outbox row saved 0 now, 1 after restart updated late 1 COMMIT order + outbox row 2 restart: relay finds the unsent row 3 publishes it Nothing lost. The “to tell” note was saved with the order. The price is a short delay. rows wait in the outbox late, not lost 2 relay: publish fails, row stays unsent 3 broker returns, relay sends the backlog The outbox is a buffer. Alert on the age of the oldest unsent row. same message twice once, if consumer dedupes 1 relay publishes row #17 — crash before marking it sent — 2 restart: row #17 still unsent 3 publishes #17 again Still at-least-once. The consumer keeps the ids it has handled and skips repeats. order committed 1 change event 1 COMMIT order (app code unchanged) 2 CDC tool reads the database log 3 publishes the change, in commit order Every committed change reaches the broker, in the order the database committed it. 1 event, still arrives — app crashes — 2 the commit is already in the log 3 CDC tool publishes it The app is not in the path at all, so its crash cannot lose the event. paused, then catches up 2 CDC tool cannot publish, remembers its log position 3 broker back: resumes from that position Nothing lost, but the database must keep log files while the tool is behind. A long outage costs disk. same event twice 1 tool publishes event at position 900 — crash before saving position — 2 restart: re-reads from 880 3 events 880–900 go out again At-least-once again. Dedupe by event id, or by key plus version. prepared, then committed committed together 1 coordinator: prepare to DB and broker 2 both save to disk and vote yes 3 coordinator logs “commit”, tells both All or nothing, at the price of extra disk syncs and network round trips. in doubt · locks held in doubt 1 both prepared and voted yes — coordinator crashes — 2 they cannot decide alone 3 locks stay held until it recovers Atomic, but blocking. If the coordinator’s log is lost, a human must decide. order rolled back nothing happened 2 broker does not answer 3 coordinator aborts both Consistent, but now a broker outage blocks every order. You traded availability for atomicity. effect + ack in one commit redelivered safely exactly once 1 worker: begin distributed transaction 2 write effect + ack in one 2PC 3 crash before commit → both abort, retry is safe Works, but only if every system speaks the same commit protocol. An email server does not. Search / email An order is paid. Search and email must hear about it. Choose a design, then break something. 1 · the design 2 · what goes wrong Message #17, “email the receipt”, is delivered. Then the broker delivers it again. Naive consumer on message: send_email(order) Idempotent consumer Deliver #17 Deliver #17 again You gain It costs Pick when Avoid when Dual write (commit, then publish) Simplest code. Crash between writes loses the event. Races reorder silently. Self-healing extras, like a short-lived cache entry. Anything that must agree: search, billing, stock. Transactional outbox + relay Event saved in the same commit. Crashes cannot lose it. Extra table and writes, poll delay, duplicates, cleanup. One main database, few consumers, small team. Write volume so high the extra row hurts. Almost no app change. Commit order kept. Many consumers or legacy apps. No log access, or schemas change with no contract. Two-phase commit (XA) All or nothing across both systems. Extra syncs and trips. Coordinator crash blocks with locks held. Both support it, one datacenter, modest load. Mixed tech, high throughput, availability first. Explain simply: why is “commit, then publish” a bug? explain simply Two writes to two systems, and nothing makes them succeed together. If the app dies between them, the order exists but the broker never hears. No error appears anywhere. Fix: one write. Save the “to tell” note in the same commit as the order. two systems, no shared commit silent failure one atomic write What breaks if two clients update the same item with a dual write, even with no crash? what breaks if Order breaks: the two systems can apply the writes in different orders. Database sees A then B. Search sees B then A. Final: database says B, index says A. Nothing warns you. race, not just crash no single leader followers apply the same order The outbox gets about 2,000 events a second and the relay polls every second. What delay do you expect, and what do you watch? Up to about one second, plus publish time. Fine for search. Watch the age of the oldest unsent row, and the backlog size. Index unsent rows, send in batches, and delete old rows. The outbox adds writes to your main database. cleanup and index What would you do instead of a polling relay? what would you do instead Let a CDC tool (change data capture) read the database log. No polling, and events leave in commit order. Combine them: CDC reads only the outbox table, a stable contract. Cost: run and watch a connector, plus an initial snapshot. log as the source outbox as a stable contract ops cost of the connector Delivery is at-least-once. How do you make the consumer safe? Record the message id with a unique key, in the same transaction as the work. A repeat hits the unique key and does nothing. A crash before commit rolls back both, so a retry is safe. message id + unique key same transaction as the work set, not increment Curveball: why not use 2PC between Postgres and the broker and skip all this? staff level A coordinator crash after the yes votes leaves both sides stuck, holding locks. 2PC (two-phase commit) also adds disk syncs and round trips. Many cloud services skip it for these reasons. Use retry plus idempotence. For “I just paid”, read from the database. cost of fsync and round trips Publish inside the transaction If the commit fails, you announced an order that does not exist. Assuming “exactly once” Brokers and relays retry. Expect duplicates. An outbox that only grows Without index and cleanup, it becomes the slow query. Expecting search to be instant Derived systems lag. Read your own writes from the database. Named dual write and the crash gap Mentioned the ordering race Outbox: same transaction, then a relay Outbox vs CDC, and when to combine Idempotent consumer: id + unique key Honest cost of 2PC COMMIT order publish never runs nobody told No crash needed. Two orders of arrival are enough. poll delay extra outbox inserts Top: poll a table. Bottom: read the log. Both end at the same place. INSERT processed(id) UNIQUE key Do the work A repeat fails at step 2 and changes nothing. After a yes vote, a participant has given up the right to say no.

The order is saved. The message to search and email never left.

The service commits the order, then publishes an event. Some events never leave. dual write transactional outbox change data capture idempotent consumer Paid orders never reach search or email.

Write the phone call on the same page

A shop writes each sale in a ledger, then phones the warehouse to ship it. A power cut between the two steps: the sale is written, the call never happens. Better: write “tell the warehouse: ship #17” on the same ledger page as the sale. A runner reads the page and makes the calls. After a crash, the note is still there. The runner may call twice. The warehouse keeps slip numbers and ignores repeats.

Paid orders missing from search, and no confirmation email

Code: db.commit(), then queue.publish(order_paid). Some orders are in Postgres but never reach search. Clusters around deploys and broker restarts. No errors logged. orders missing downstream ≈ 0.2% (illustrative) deploys, broker blips search · email · analytics errors logged The question: keep “order saved” and “event sent” in agreement. Compare three designs and their costs.

Pick a design. Break something. Watch what survives.

What to notice: only dual write loses data silently. Every other design turns a crash into a delay or a duplicate, and a duplicate is a problem you can solve. What to notice: in both routes the app makes one write. The database, not the app, carries the news to the broker. What to notice: the fix for a duplicate is not to prevent the second delivery. It is to make the second one harmless.

Four ways to keep two systems in step

Keeps order No new parts Never blocks Dual write Outbox + relay Log-based CDC Two-phase commit All three safe designs still deliver duplicates. Postgres, a broker, three consumers, a team of five. What do you ship for “order paid”? Outbox table in the same transaction, a relay, idempotent consumers Lost events Parts to run CDC straight off the orders table No app change, order kept. But consumers now depend on your internal table layout. Keep dual write, add retries in the app Retries die with the crashed process. The gap shrinks but never closes.

A model spoken answer

Orders are saved but events go missing. How do you fix it? Name it One write Outbox row in the same transaction as the order. Ship it A relay or CDC tool publishes it later. Why not 2PC Coordinator crash blocks with locks held.

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.