Video in progress

What should a client do when the server returns 429 or 503?

It shouldn't retry immediately. If there is a Retry-After header, it waits that long; if not, it retries with a growing wait on each attempt (exponential backoff) plus random jitter, and caps the number of attempts.

📖 Answer

429 means "you're asking too much", 503 means "I'm busy or down right now". In both cases, retrying instantly makes things worse.

int attempt = 0;
while (true) {
    HttpResponse<String> r = client.send(request, BodyHandlers.ofString());
    if (r.statusCode() != 429 && r.statusCode() != 503) return r;
    if (++attempt == 5) throw new IllegalStateException("Servis javob bermadi");

    long waitMs = r.headers().firstValue("Retry-After")
            .map(s -> Long.parseLong(s) * 1000)        // comes in seconds
            .orElse((long) (200 * Math.pow(2, attempt))); // 400, 800, 1600...
    waitMs += ThreadLocalRandom.current().nextLong(100);  // jitter
    Thread.sleep(waitMs);
}

Why jitter: if 1000 clients get an error at the same moment and all retry exactly 1 second later, the server gets 1000 requests at once again. The random addition spreads them out in time.

In practice you don't write this by hand; you use Resilience4j Retry or Spring Retry. Retry-After can also come as a date — the libraries handle that.