Try
↑ ↓ move↵ openesc close

Interview prep / Retries and circuit breakers

Mid · Retries and circuit breakers · System design interview question

A mobile app places orders over flaky networks, and some customers end up with two identical orders. How would you fix it on the server?

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

A strong answer

The app times out, does not know whether the order went through, and sends it again. Both copies reach the server and both are accepted. The server cannot tell a duplicate from a second real order, because nothing links them.

Link them. The app makes a unique key once for each order the user submits, before the first attempt, and sends the same key on every retry. On the server, a unique constraint on that key, in the same table or transaction as the order, makes the second insert fail. The server catches that and returns the original order instead of an error.

Care is needed in three places. If two copies arrive at the same moment, the unique constraint makes one lose, and it should return the winner's result. If the key arrives with a different body, refuse it, as that is a client bug. And keep keys long enough to cover the slowest realistic retry, such as a day.

Return the same status for the repeat as for the first call, so the app does not have to know which attempt succeeded. The server should store the response, not only the fact that the key was used.

Keys are not needed where the operation repeats safely already, such as setting an address to a value.

Sources

Learn it by running it

The retries, timeouts and circuit breakers 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