Cancellation and concurrency control · senior
Retry with exponential backoff and timeouts
A retry helper re-runs a failing async function a limited number of times, waiting longer each time (base × 2^attempt plus random jitter), retries only errors that can succeed later (network errors, 5xx, 429), and gives each attempt its own timeout.
Explain it out loud
Explain it out loud to an AI interviewer that follows up, and see where your answer is thin.
Practise by voiceThe notes
What you must know
- Loop: try and return on success; on failure, if attempts are left and the error is retryable, wait and try again; otherwise rethrow the last error.
- Exponential backoff: 100, 200, 400 ms and so on, with a maximum cap. Add jitter (for example a random delay between 0 and the backoff) so many clients don't retry at the same moment (thundering herd).
- Retry only idempotent operations, or send an idempotency key with POSTs such as payments.
- fetch resolves on 4xx and 5xx, so check res.ok. Don't retry 400, 401, 403 or 404; do retry 408, 429 and 5xx, and respect a Retry-After header.
- Per-attempt timeout with AbortSignal.timeout(ms); cancel the whole operation with an outer signal combined via AbortSignal.any.
- Make sleep and random injectable so tests can use fake timers.
The red pen
Common traps: mistake → fix
Mistake: Retry every error
Fix: retrying 4xx or non-idempotent writes causes duplicates and wasted load.
Mistake: A Promise.race timeout cancels the request
Fix: it only stops waiting; abort the request too.
Mistake: No jitter
Fix: synchronised retries can overload a recovering server.
Easy to hard
Questions interviewers ask, easy to hard
- Write retry(fn, retries).
- Add exponential backoff and jitter. Why jitter?
- Which errors should you retry and which not?
- Add a per-attempt timeout and a way to cancel everything.
- Retries for a payment: idempotency keys, user feedback and server-confirmed results.
Practise
Practise with these questions
Explain it out loud
Explain it out loud to an AI interviewer that follows up, and see where your answer is thin.
Practise by voiceYour first interview is free
Sign up and start with a 15-minute interview with the full report, and an English conversation. No card needed.