Amateur code answers one question: what happens when everything goes right? Production code has to answer the rest. What if the database dies mid-transaction? What if the API neither fails nor responds, but just hangs for 45 seconds? A network call is “a coin flip you don’t get to see the result of.”

Three habits cover most cases. First, idempotency: doing it twice has the same effect as doing it once. The usual way is an idempotency key, the pattern Stripe’s API uses: the client sends a unique key, the server stores it with the result and returns the stored result on a repeat. It’s needed because a request can succeed while its response is lost. The Coding Gopher shipped a payment endpoint without one, with a mobile client that retried on timeout, and one customer was charged twice for one order.

Second, exponential backoff with jitter. Without the random offset, every client that failed at the same moment retries at the same moment. Third, an explicit timeout on every network call. Python’s requests, Go’s default http.Client and Axios have none unless you set one, which is how one slow dependency eats a whole thread pool.

Caveat: idempotency keys move the problem rather than remove it. The key store has to be durable and checked atomically with the work, or the double charge comes back under a race. Retries also need a budget, or backoff only delays the pile-up.

Key Quotes

  • “Every network call is a coin flip you don’t get to see the result of. Write the code that assumes it landed wrong.” (06:01)
  • “A thousand clients retrying in perfect lockstep aren’t recovering from the outage. They are the outage.” (07:25)

Related: