Video in progress

Strong Junior 🏗️ System design

What is wrong with the following retry code, and what could it cause in production?

public Response callInventory(Request req) {
    while (true) {
        try {
            return inventoryClient.reserve(req);
        } catch (Exception e) {
            log.warn("Retry...", e);
        }
    }
}

The code retries without waiting, without limit and on any error. When the service slows down, all clients pile on at once and multiply the load several times over, taking it down completely (a retry storm). You need a capped number of attempts, exponential backoff + jitter, and retries only on transient errors.

📖 Answer

Several mistakes reinforce each other here:

  • while (true) — if the service is down for an hour, the thread spins for an hour;
  • no waiting — thousands of requests per second go out, and the log fills up too;
  • catch (Exception e) — it retries even on 400 Bad Request or a validation error, which will never succeed;
  • if reserve isn't idempotent, a retry after a timeout can reserve the item twice.

How a retry storm happens: the inventory service slows down a little → timeouts on the clients → everyone retries immediately → load goes up 3–5 times → the service goes down completely → when it tries to come back up, another wave hits.

The fixed version with Resilience4j:

RetryConfig config = RetryConfig.custom()
        .maxAttempts(3)
        .intervalFunction(IntervalFunction
                .ofExponentialRandomBackoff(Duration.ofMillis(200), 2.0))
        .retryExceptions(IOException.class, TimeoutException.class)
        .build();

Be careful with chains too: if A, B and C each retry 3 times, D gets 27 requests. Usually retries are done at only one layer.