Backing Off

What is worth retrying. Something that might succeed if you try again: a 429, a 5xx, a timeout, a dropped connection.

What is not. A 400, 401, 403 or 404. Nothing about the request will improve by repeating it, and retrying a 401 in a loop looks exactly like an attack.

Exponential backoff. Wait one second, then two, then four, then eight. Doubling gives a struggling server room to recover instead of a steady stream of new requests.

Add a little randomness, called jitter, so that many clients recovering from the same outage do not all retry in perfect unison and knock the server over again.

And cap the attempts. Retrying forever turns someone else's brief outage into your own contribution to it.

◈ Graded Challenge

Write plan(statuses, max_attempts) deciding what a retrying client would do. statuses is the list of status codes returned by successive attempts. Work through them in order. Stop and return "ok" as soon as one is below 400. Stop and return "gave up" on a 400, 401, 403 or 404, since retrying cannot help. Retry on 429 and on any 5xx, up to max_attempts attempts in total; if every attempt is used without success, return "exhausted". Return a list of the waits used between attempts as the second element, doubling from 1: so return an array of two items, the outcome and the list of waits.

Name it exactly: plan(statuses, max_attempts)

3 visible + 5 hidden
loading editor…

Mark this lesson complete

Signed in, your progress follows you to every device.

Next: Practice Test →
← Back