When is it safe to retry a failed request, and when is it not?
Sketch your own answer first, then compare it with the one below.
A strong answer
It is safe when repeating the request has the same effect as doing it once. Reads are naturally safe. Writes are safe only if they are idempotent: setting a value to X is, adding 10 to a balance is not.
A request that timed out is the hard case. The client does not know whether the server did the work. If the server did, a retry of a non-idempotent write does it twice, for example by charging a card twice. The usual fix is an idempotency key that the client generates and sends with the request. The server stores the result under the key and returns it for a repeat.
Also look at the error. Retry on failures that may clear up: a timeout, a dropped connection, a 503. Do not retry on errors that will not change, such as a bad request or a failed authorisation.
The unknown outcome after a timeout is the case that bites. Idempotency keys exist for exactly that.
Sources
- Roy Fielding, Mark Nottingham, Julian Reschke (2022). HTTP Semantics.