Retries and idempotency
What you will learn
A retry repeats a failed attempt, not necessarily a failed business operation. Bound the total time and number of attempts, retry only transient failures, and use a stable operation key where repeated effects must be prevented.
- Calculate retries within a time budget.
- Model idempotent replay and conflicting payload rejection.
- Distinguish retry, circuit breaker and bulkhead.
Plain Java examples: save as Main.java in a fresh directory, then run javac --release 21 Main.java and java Main. Standalone Java 21 models; the companion Spring Cloud configuration is source-reviewed, not executed.
Bound attempts and delay within a simulated deadline
public class Main { static java.util.List<Integer> plan(int budget) { var attempts = new java.util.ArrayList<Integer>(); int elapsed = 0; for (int i=0;i<3;i++) { if (budget-elapsed < 40) break; attempts.add(elapsed); elapsed += 40; if (i < 2) elapsed += 20 * (1 << i); } return attempts; } public static void main(String[] args) { System.out.println(plan(150)); System.out.println(plan(50)); }}Expected output:
[0, 60][0]Each modeled attempt consumes 40 ms. A 150 ms budget permits attempts at 0 and 60, not at 140. This is an arithmetic simulation, not real timing or jitter.
Retry budget
Set an end-to-end deadline, subtract elapsed monotonic time, and cap each attempt to the remaining budget. Retry only classified transient errors when the operation can be safely retried. Exponential backoff increases delays; jitter randomizes them to reduce synchronized retry bursts. Respect server retry advice only within the remaining deadline. Avoid independent retries at every layer: three attempts at each of three layers can create 27 downstream calls. Do not retry validation failures.
Idempotency
Scope an operation key to the authenticated tenant and operation. Store the request fingerprint and outcome atomically with the local effect. Replay the same outcome for the same key and request; reject a different payload with the same key. Define key retention, concurrent duplicate handling and what pending means. A local map is not durable and cannot guarantee correctness after restart.
Isolation and failure
A circuit breaker opens after a configured failure policy and permits limited probes after a cooldown; a bulkhead limits concurrent work or queue capacity independently per dependency. Neither ensures business success. Use a fallback only if its semantics are explicit (for example stale read with age, not invented payment success). The example breaker is a simplified deterministic state model, not a production library.
Replay an operation key without repeating the effect
public class Main { record Result(int quantity, int remaining) {} static class Store { int stock=5; final java.util.Map<String,Result> done=new java.util.HashMap<>(); synchronized Result reserve(String key,int n) { if(n<=0) throw new IllegalArgumentException("quantity"); var old=done.get(key); if(old!=null) { if(old.quantity()!=n) throw new IllegalArgumentException("key conflict"); return old; } if(n>stock) throw new IllegalStateException("insufficient stock"); stock-=n; var result=new Result(n,stock); done.put(key,result); return result; } } public static void main(String[] args) { var s = new Store(); System.out.println(s.reserve("tenant:A:K1", 2)); System.out.println(s.reserve("tenant:A:K1", 2)); System.out.println(s.stock); }}Expected output:
Result[quantity=2, remaining=3]Result[quantity=2, remaining=3]3The synchronized section keeps check, effect and replay in one local critical section. Production needs durable transactional storage and a complete request fingerprint.
Fail fast when a dependency circuit is open
public class Main { static class Breaker { int failures; boolean probe; void failed() { failures++; } boolean allow(int elapsed) { if(failures<2) return true; if(elapsed<10 || probe) return false; probe=true; return true; } } public static void main(String[] args) { var b=new Breaker(); b.failed(); b.failed(); System.out.println(b.allow(9)); System.out.println(b.allow(10)); System.out.println(b.allow(10)); }}Expected output:
falsetruefalseThe simplified breaker permits one probe after the modeled cooldown. Real implementations also reset or reopen on probe outcomes and use a clock and synchronization.
Common mistakes
Never retry a write solely because a timeout occurred. Do not use unlimited queues, reset the entire deadline for each retry, or count idempotency keys without tenant scoping.
Practice
Given two attempt costs of 30 ms and 20 ms backoff, determine whether a second attempt fits budgets 79 and 80 ms. Print false then true. Reject negative budgets in your implementation.
Expected output:
falsetrueCompare with the manual review criteria.
Further reading: Retry · Idempotency. Independent editorial review remains pending.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Retries and idempotency — knowledge check
Distributed systems and resilience reasoning.
What bounds an entire retry workflow?
Why add jitter?
What if a key is reused with a different payload?
What does a bulkhead limit?
What does an open breaker normally do?