Video in progress
When is automatic retry on error dangerous, and how do you do it properly?
If the operation isn't idempotent (a payment, say), a retry can charge the money twice. Retries also add load: if everyone retries at once, a service that's just recovering goes down again. The right way is to retry only on transient errors, with exponential backoff, jitter and an idempotency key.
📖 Answer
Here's the dangerous version:
@Retryable(maxAttempts = 3)
public PaymentResult charge(Order o) { return client.charge(o); }
A read timeout happened — but the provider had already taken the money, the response was just late. The retry charges again.
How to do it:
- Idempotency key — send a fixed key per order so the provider recognizes the repeat request and returns the earlier result:
client.charge(o, "Idempotency-Key", "order-" + o.getId()); - Only on transient errors — 503, 429, connection errors. Retrying on 400, 401, 409 gets you nothing.
- Backoff + jitter — 200 ms, 400 ms, 800 ms ± a random part. Without jitter, thousands of clients retry at the same moment ("thundering herd").
- Cap both the number of attempts and the total time.
- Don't repeat it in every layer: if the client retries 3 times, the service 3 and the gateway 3, one request turns into 27.
With Resilience4j:
resilience4j.retry.instances.payment:
max-attempts: 3
wait-duration: 200ms
enable-exponential-backoff: true
enable-randomized-wait: true
retry-exceptions: [java.net.ConnectException]
Keep in mind: @Retryable also works through a proxy, so it stays silent on self-invocation too.
Sign up to mark studied questions and save your progress.