Try
↑ ↓ move↵ openesc close

Interview prep / Idempotency and the outbox

Senior · Idempotency and the outbox · System design interview question

Two requests with the same idempotency key arrive at the same time. How do you make sure only one runs?

Sketch your own answer first, then compare it with the one below.

A strong answer

A check and then an insert is a race. Both can see no key and both proceed. Make the database enforce it. Insert the key with a unique constraint as the first step of the transaction. The loser gets a conflict.

Then decide what the loser does. It can wait and return the winner's stored result, or return a conflict status that tells the client to retry later. Store a state with the key: in progress or done, along with the result. A crashed winner leaves a key stuck in progress, so give it a lease or a timeout after which another request may take over.

Also store a hash of the request. The same key with a different body is a client bug, and should be rejected rather than answered with the old result.

Sources

Learn it by running it

The idempotency keys and the outbox lesson explains the mechanism behind this question, and its lab lets you change the parameters and watch the effect.

Your progress is saved in this browser. Sign in to keep it on every device. Privacy · Terms