Idempotency, retries, and duplicate handling
What you will learn on this page
Section titled “What you will learn on this page”- Why a call that times out leaves you not knowing whether it happened, and why that makes “just try again” dangerous.
- How an idempotency key makes a repeated request safe, and what the caller and the service each have to do for it.
- Which failures to retry, how many times, and how long to wait between tries: capped exponential backoff with jitter.
- How to test retry logic without sleeping and without randomness.
- How to ignore repeated messages when a sender delivers “at least once”, with bounded memory.
- When retrying is unsafe, even with all of the above.
The problem: a timeout is not a “no”
Section titled “The problem: a timeout is not a “no””A shop charges a customer’s card through a payment provider. The shop sends “charge 42.00 to Bob’s card” and waits. After five seconds, nothing has come back. What happened?
- The request never arrived. No money moved.
- The request arrived and the provider charged the card, but the reply was lost on the way back.
- The provider is still working on it.
From the shop’s side, the three look the same: no answer. If the shop tries again and the truth was 2, Bob pays twice. If it does not try again and the truth was 1, the shop has lost a sale, and Bob may think they have paid. Neither “always retry” nor “never retry” is right, because the shop does not know the outcome.
// A naive "retry on timeout" loop. It returns the first receipt that comes// back, retries a timeout up to 3 tries in all, and then gives up by// rethrowing the last timeout. The flaw: nothing tells the gateway that// try 2 is the same payment as try 1.Receipt pay_for_order(PaymentGateway& gateway, const Order& order) { // a request with only an account and an amount: no key yet. (In this // sketch ChargeRequest has just those two fields; the real one, shown // later, starts with the key.) const ChargeRequest request{order.account, order.total_cents}; // No loop condition: the loop ends only by `return` or `throw`. for (int attempt = 1; ; ++attempt) { try { // If try 1 charged the card but its reply was lost, this line // runs again on try 2 and the provider, seeing an ordinary new // request, charges the card a second time. This is where it goes // wrong. return gateway.charge(request); } catch (const TimeoutError&) { if (attempt == 3) throw; // give up: rethrow the third timeout // "it timed out, try again" } }}This code is illustrative and was not compiled.
This loop looks careful: it gives up after three tries. But every try is, to the provider, a new payment. If the first reply was lost, the second try charges the card again. The example’s first line of output shows exactly that against a stub provider that loses one reply: the card is charged twice.
The fix is not on the shop’s side alone. The provider must be able to recognize “this is the same payment again”, and the shop must tell it which payment each request is. That is what an idempotency key does.
The requirements
Section titled “The requirements”- R1. A payment for an order is made at most once, however many times the shop tries.
- R2. A failure whose outcome is unknown is retried automatically, a few times.
- R3. A decline (“insufficient funds”) is shown to the customer at once. It is an answer, not a failure, and is not retried.
- R4. Retries must not pile onto a provider that is already struggling: the waits grow, are capped, and are spread out between clients.
- R5. The retry logic is tested without real waiting and without randomness.
- R6. The provider tells the shop “payment succeeded” by a notification that may arrive more than once. The receipt email is sent once.
Step 1: classify the failures and the operations
Section titled “Step 1: classify the failures and the operations”The first decision is not about code. It is which failures may be retried, and that depends on two questions: is the outcome known? and could another try give a different answer?
| What came back | Outcome known? | Can a retry help? | What to do |
|---|---|---|---|
| A receipt: charged | yes | no need | done |
| A receipt: declined | yes | no | tell the customer (R3) |
| “This key was used for a different request” | yes, a bug | no | fix the caller; never retry |
| “Unavailable, try later”, before doing anything | yes: not done | yes | retry after a wait |
| A timeout, or the connection dropped mid-request | no | yes | retry, only if repeating is safe (an idempotency key) |
The example models the last two as one exception type,
TransientFailure: “no answer; a later try may succeed”. It does not
need to know which of the two happened, because with an idempotency
key, both are safe to retry.
The second decision is about the operation itself. An operation is idempotent when doing it twice has the same effect as doing it once:
- Naturally idempotent: “set the order’s status to paid”, “store this file under this name”, “delete item 7”. Repeating them changes nothing more.
- Not idempotent: “charge 42.00”, “add 50 points”, “send an email”, “append a line to the log”. Each repeat does it again.
A naturally idempotent operation can be retried without a key. One that is not needs something extra to become safe to repeat: a key that lets the receiver recognize the repeat.
Idempotent is not the same as safe to repeat late. If “set the status to paid” is repeated after someone else has set it to “refunded”, the repeat undoes their change. Repeats that can arrive late need a condition (“set it to paid only if it is still pending”) or a version number.
The idempotency key: the caller’s half
Section titled “The idempotency key: the caller’s half”VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// One payment the shop wants to make. The idempotency key names the// intent ("pay for order 1042"), not one attempt: every retry of this// payment sends the same key, and no other payment ever uses it.struct ChargeRequest { std::string idempotency_key; // empty: the provider treats every call as new std::string account; // Money as a whole number of cents (4200 is 42.00), never a double: // integers add and compare exactly, with no rounding surprises. long long amount_cents = 0;
// `= default` asks the compiler to write ==, comparing the members in // order: two requests are equal when key, account, and amount all are. // The provider uses it to tell "the same request again" from "the same // key with a different request". `friend` lets it be written inside the // struct while still being an ordinary two-argument function. friend bool operator==(const ChargeRequest&, const ChargeRequest&) = default;};
// The two normal answers a provider can give.enum class Outcome { charged, declined };
// The provider's answer. A decline is an answer, not a failure.// charge_id names the charge the provider made ("ch-3"); a repeat of the// same key gets back the same charge_id, which is how a caller can see that// no second charge happened.struct Receipt { std::string charge_id; Outcome outcome = Outcome::charged;
friend bool operator==(const Receipt&, const Receipt&) = default;};
// No answer arrived: a timeout, a dropped connection, "try again later".// The charge may or may not have happened, and a later try may succeed.// It derives from std::runtime_error, the standard base for failures that// come from the world outside the program. The `using` line inherits the// base's constructors, so TransientFailure("timed out") works with no// constructor written here; what() then returns that message.struct TransientFailure : std::runtime_error { using std::runtime_error::runtime_error;};
// The key was already used for a different request: a bug in the caller,// which trying again cannot fix. std::logic_error is the standard base for// "the program broke a rule", which is why it is a different family from// TransientFailure: code that retries catches only TransientFailure.struct KeyReused : std::logic_error { using std::logic_error::logic_error;};VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// What the shop needs from a payment provider, from the shop's side.// It is an interface: an abstract class with one pure virtual function.// The retrying charger talks only to this type, so the demo and the tests// can plug in a stub (FakeProvider) where a real program would plug in a// network client.class PaymentGateway {public: // Virtual, so that destroying a provider through a PaymentGateway // pointer or reference runs the derived class's destructor too. virtual ~PaymentGateway() = default;
// Returns a receipt, for a decline too. Throws TransientFailure when // the outcome is unknown, and KeyReused when the key was sent before // with a different request. // `= 0` makes it pure virtual: every concrete provider must write it, // and no plain PaymentGateway object can be made. [[nodiscard]] virtual Receipt charge(const ChargeRequest& request) = 0;
protected: // Protected, not public: only derived classes can construct, copy, or // assign the base part. Outside code cannot copy a provider through a // PaymentGateway reference, which would copy only the base part (the // "slicing" mistake). PaymentGateway() = default; PaymentGateway(const PaymentGateway&) = default; PaymentGateway& operator=(const PaymentGateway&) = default;};- The key names the intent, not the attempt. “Pay for order 1042” is one intent. Every retry of it sends the same key; a second order gets a different key. A key made fresh for each attempt would make every attempt look new, which is the bug the key exists to prevent.
- The key is made before the first attempt, and kept with the order. Deriving it from the order’s ID, as the example does, is one way: the shop can rebuild it after a restart. A random key (such as a UUID) also works, but it must then be saved with the order before the first try, or a shop that crashes and restarts will make a new one.
- A decline is a
Receipt, not an exception. It is one of the two normal answers. Exceptions are for the cases where there is no answer (TransientFailure) or the caller broke the rules (KeyReused). That follows the three kinds of failure in Errors and contracts: a decline is an expected failure, reported as a value the caller must look at; a lost reply is an unexpected failure, reported as an exception; a reused key is a bug in the caller, which is whyKeyReusedderives fromstd::logic_error. - The gateway’s comment is its contract. It lists which exceptions mean what, so the retry code can decide without guessing.
The idempotency key: the service’s half
Section titled “The idempotency key: the service’s half”The caller’s key does nothing unless the receiver remembers it. The example’s stub provider does what a real one must:
VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// A stand-in for a payment provider, for the demo and the tests. It does// the provider's half of idempotency: the first request with a key is// carried out and its receipt stored under the key; a repeat with the same// key gets the stored receipt, and no money moves. Faults can be scripted// to imitate the network. Thread safety: not safe; one thread at a time.// `final` means no class can derive from it in turn; `public PaymentGateway`// means a FakeProvider can be passed wherever a PaymentGateway& is wanted.class FakeProvider final : public PaymentGateway {public: // What goes wrong on one call. The two faults differ in *when* they // strike, and that is the whole point: one before the work, one after. enum class Fault { none, unavailable, // refuses the call before doing anything lose_response, // does the work, then the reply is lost };
// Charges above the limit are declined. // `explicit` stops a bare number from turning into a FakeProvider by // accident, for example when passed to a function that wants one. explicit FakeProvider(long long decline_above_cents);
// Faults for the next calls, in order; calls after them succeed. // A new script replaces whatever was left of the old one. Written as // provider.script({Fault::lose_response, Fault::none}): the braces make // the std::initializer_list. void script(std::initializer_list<Fault> faults);
// `override` asks the compiler to check that this really replaces // PaymentGateway::charge; a typo in the signature becomes an error. [[nodiscard]] Receipt charge(const ChargeRequest& request) override;
// Every call counts, including ones that failed or were repeats. [[nodiscard]] int calls() const noexcept { return calls_; } // How many times money was really taken from the account. [[nodiscard]] int charges_to(std::string_view account) const;
private: // One idempotency record: what was asked, and what was answered. The // request is kept so a later call with the same key can be compared // with it. struct Stored { ChargeRequest request; Receipt receipt; };
// Hands back the receipt, or throws TransientFailure if this call's // fault is lose_response: the work is done, but the caller never hears. Receipt reply(Receipt receipt, Fault fault) const;
// Scripted faults, used from the front: one per call, until empty. std::deque<Fault> faults_; // std::less<> (with empty angle brackets) is a "transparent" comparison: // find() can then take a std::string_view directly, without first // building a std::string from it. std::map<std::string, Stored, std::less<>> by_key_; // the idempotency records // Per account, the amount of every real charge, so charges_to can // count them. std::map<std::string, std::vector<long long>, std::less<>> taken_; long long decline_above_; int calls_ = 0; int next_id_ = 1; // the number for the next charge id: "ch-1", "ch-2", ...};VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// The provider's side of one call, in four stages:// 1. take this call's scripted fault, if any, and fail at once if it is// "unavailable" (nothing is done or recorded);// 2. with a key, look for a record: the same request gets the stored// receipt again, a different request is refused with KeyReused;// 3. otherwise do the work: make a new receipt, take the money if it is// not declined, and record the receipt under the key;// 4. reply, unless the fault is "lose_response", which throws after the// work is done.// Throws TransientFailure for either fault and KeyReused for a reused key.Receipt FakeProvider::charge(const ChargeRequest& request) { ++calls_; // counted first, so failed and repeated calls are counted too Fault fault = Fault::none; if (!faults_.empty()) { // Use up the next scripted fault: each call takes exactly one. fault = faults_.front(); faults_.pop_front(); } if (fault == Fault::unavailable) { throw TransientFailure("provider unavailable"); // before any work }
// An empty key means "no idempotency": the call is always treated as new. const bool keyed = !request.idempotency_key.empty(); if (keyed) { // find returns an iterator to the record, or end() if there is none. // found->second is the Stored value (found->first would be the key). const auto found = by_key_.find(request.idempotency_key); if (found != by_key_.end()) { // != uses the defaulted ==: any field differing means a // different request under an old key. if (found->second.request != request) { throw KeyReused("idempotency key already used for a different request"); } // The stored receipt is answered again, a decline as much as a // charge. A lose_response fault still loses this reply. return reply(found->second.receipt, fault); // a repeat: no money moves } }
// A new charge. next_id_++ uses the current number, then adds one, so // the ids run "ch-1", "ch-2", ... in call order. An amount exactly at // the limit is still charged; only one above it is declined. Receipt receipt{"ch-" + std::to_string(next_id_++), request.amount_cents > decline_above_ ? Outcome::declined : Outcome::charged}; if (receipt.outcome == Outcome::charged) { // [] creates an empty list for an account seen for the first time. taken_[request.account].push_back(request.amount_cents); } if (keyed) { // A real provider stores this record in the same transaction as // the charge, so a crash cannot keep one without the other. // The record holds copies of the request and the receipt. by_key_.emplace(request.idempotency_key, Stored{request, receipt}); } return reply(receipt, fault);}
// The last step of every successful-so-far call. With lose_response, the// money (if any) has moved and the record exists, but the caller gets an// exception instead of the receipt: exactly the "did it happen?" case.Receipt FakeProvider::reply(Receipt receipt, Fault fault) const { if (fault == Fault::lose_response) { throw TransientFailure("timed out waiting for the reply"); } return receipt;}How this code works: FakeProvider::charge
Every call goes through the same four stages, and the order of the stages is what makes the two faults behave differently.
- Count the call and take its fault.
calls_goes up first, so failed calls and repeats are counted too. If a fault is scripted, the front one is taken off thedeque: each call uses exactly one. - “Unavailable” fails at once. It throws before any record is looked at or made, so nothing has happened, and a retry will be a first try.
- A key with a record is answered from the record. If the stored
request equals this one (the defaulted
==compares key, account, and amount), the stored receipt is handed toreply. No money moves. If they differ,KeyReusedis thrown. - Otherwise, do the work. A new receipt gets the next number, the
money is taken unless the amount is above the limit, and, with a key,
the request and receipt are stored under it. Then
replyhands back the receipt, or, forlose_response, throws after the work.
A worked example: the demo’s calls. The limit is 500.00. Scene 1
sends no key, scene 2 the key order-1042, and the 11th call is scene
5’s order-1042 for 99.00.
| Call | Request | Fault | Record found? | What happens | Caller sees |
|---|---|---|---|---|---|
| 1 | no key, alice, 42.00 | lose_response |
no key, not looked up | ch-1, alice charged |
TransientFailure |
| 2 | no key, alice, 42.00 | none | no key, not looked up | ch-2, alice charged again |
receipt ch-2 |
| 3 | order-1042, bob, 42.00 |
lose_response |
no | ch-3, bob charged, stored |
TransientFailure |
| 4 | order-1042, bob, 42.00 |
none | yes, same request | nothing new | receipt ch-3 again |
| 11 | order-1042, bob, 99.00 |
none | yes, different amount | nothing | KeyReused |
Calls 1 and 2 are the double charge; calls 3 and 4 are the same situation made safe by the key.
- The first request with a key is carried out and its result
stored under the key. A repeat gets the stored result, and no money
moves. The repeat’s reply is the same receipt, with the same
charge_id, so the shop cannot tell whether its first try or its fifth was the one that worked, and does not need to. - The stored result includes declines. Asking again with the same key gets the same decline, even if the customer has since added money. That is correct: a new attempt after the customer fixes the problem is a new intent, with a new key.
- The same key with a different request is refused. It means the caller has a bug, such as a key built from the wrong field. Answering with the old receipt would hide it, and charging anew would break the promise of the key.
- “Unavailable” fails before anything is recorded, so a retry is a first try. “Lose the response” fails after the record is made, so a retry is a repeat. The stub lets the tests produce both.
Retrying: which, how often, how long to wait
Section titled “Retrying: which, how often, how long to wait”The charger waits between tries using capped exponential backoff with jitter. The policy and the limit come first:
VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// How hard to try. A plain struct with defaults, so RetryPolicy{} means// "4 attempts, waits starting at 100 ms and capped at 2 seconds", and// RetryPolicy{4, 5ms, 40ms} fills the three fields in order.// std::chrono::milliseconds is a duration type: the unit is part of the// type, so a number of seconds cannot be passed by mistake as milliseconds.struct RetryPolicy { int max_attempts = 4; // including the first std::chrono::milliseconds first_delay{100}; std::chrono::milliseconds max_delay{2000};};
// The longest wait before retry number `retry` (1 for the first retry):// first_delay, doubled for each retry before it, but never above max_delay.// With the defaults: 100, 200, 400, 800, 1600, 2000, 2000, ... ms.[[nodiscard]] std::chrono::milliseconds backoff_limit(const RetryPolicy& policy, int retry);VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// Starts at first_delay and doubles once for each earlier retry, stopping// at max_delay. For retry 1 the loop does not run at all (i = 1 is not// below 1), so the answer is first_delay. The loop also stops as soon as// the cap is reached, so a huge retry number costs no extra work.std::chrono::milliseconds backoff_limit(const RetryPolicy& policy, int retry) { std::chrono::milliseconds limit = policy.first_delay; for (int i = 1; i < retry && limit < policy.max_delay; ++i) { // never doubles past max_delay, so it cannot overflow // If limit is already more than half the cap, doubling would pass // the cap (or, for a huge cap, overflow), so jump to the cap instead. // Otherwise limit * 2 is at most max_delay, which always fits. limit = limit > policy.max_delay / 2 ? policy.max_delay : limit * 2; } // Normally limit is already at most max_delay. This also covers a policy // whose first_delay is above its max_delay, which this free function // can be given even though the charger's constructor refuses one. return std::min(limit, policy.max_delay);}How this code works: backoff_limit
The loop doubles limit once for each retry before this one, and stops
early once the cap is reached. Each time round, it asks one question:
is limit already more than half the cap? If so, doubling would pass
the cap, so it jumps straight to the cap; otherwise it doubles. Because
limit * 2 is only computed when limit is at most half the cap, the
result always fits, even when the cap is the largest number a
milliseconds can hold.
A worked example, with the test’s policy: first delay 100 ms, cap 1000 ms, so half the cap is 500 ms.
retry |
Times round the loop | limit after each time |
Returned |
|---|---|---|---|
| 1 | 0 | (stays 100) | 100 ms |
| 2 | 1 | 200 | 200 ms |
| 3 | 2 | 200, 400 | 400 ms |
| 4 | 3 | 200, 400, 800 | 800 ms |
| 5 | 4 | 200, 400, 800, 1000 | 1000 ms |
| 60 | 4, then the cap stops it | 200, 400, 800, 1000 | 1000 ms |
On the fourth time round, 800 is more than 500, so the limit becomes
the cap, 1000, instead of 1600. For retry 60 the loop’s condition
limit < policy.max_delay is then false, so it stops there instead of
running 59 times.
- The wait grows. With a first delay of 100 milliseconds, the limits are 100, 200, 400, 800, … milliseconds. A failure that is over in a moment is retried quickly; a provider that is down for a minute is not hit ten times a second (R4).
- The wait is capped. Without
max_delay, the limit for the tenth retry would be 51 seconds (100 ms × 2⁹). The cap keeps the worst wait known. - The attempts are counted, and limited.
max_attemptsincludes the first try, so the default of 4 means at most 3 retries.
VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// Waiting, behind an interface, so that tests can record the waits// instead of sleeping through them.// The program passes a Sleeper that really sleeps; the tests pass one// that only writes each delay down. The charger cannot tell the// difference, which is what makes it testable without waiting.class Sleeper {public: virtual ~Sleeper() = default; virtual void sleep_for(std::chrono::milliseconds delay) = 0;
protected: // Protected, as in PaymentGateway: only derived classes may construct // or copy the base part, so a Sleeper cannot be sliced by a copy. Sleeper() = default; Sleeper(const Sleeper&) = default; Sleeper& operator=(const Sleeper&) = default;};VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// Charges through a gateway, and retries only failures whose outcome is// unknown, always with the same request, so with the same idempotency key.// Between attempts it waits a random time between zero and the backoff// limit ("full jitter"), so that many clients that failed together do not// all retry at the same moment.//// Thread safety: not safe. Lifetime: the gateway and the sleeper must// outlive the charger.class RetryingCharger {public: // random_fraction returns a value in [0, 1]. Throws std::invalid_argument // for a policy with no attempts or with delays that make no sense // (negative, out of order, or over a day), and for an empty // random_fraction. // std::function<double()> holds any callable that takes nothing and // returns a double: a lambda over a random engine in the program, or a // plain function that always returns 0.5 in the tests. The policy is // taken by value: the charger keeps its own copy. RetryingCharger(PaymentGateway& gateway, RetryPolicy policy, Sleeper& sleeper, std::function<double()> random_fraction);
// Throws std::invalid_argument for a request without an idempotency // key: retrying such a request could charge twice. Rethrows the last // TransientFailure when every attempt has failed; the outcome is then // unknown, and the caller may ask again later with the same request. // KeyReused, and any other exception from the gateway, passes straight // through on the attempt that throws it, with no retry after it. [[nodiscard]] Receipt charge(const ChargeRequest& request);
private: // Not owned: these point at objects that the caller keeps alive. They // are pointers rather than references so that the charger can still be // assigned; the constructor takes references, so neither is ever null. PaymentGateway* gateway_; RetryPolicy policy_; Sleeper* sleeper_; std::function<double()> random_fraction_;};VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// Try, and if the outcome is unknown, wait and try again with the very// same request, up to max_attempts tries in all. Returns the first answer// (charged or declined). Throws std::invalid_argument for a request with// no key, before any call; rethrows the last TransientFailure when every// attempt failed; lets KeyReused and anything else through at once.Receipt RetryingCharger::charge(const ChargeRequest& request) { if (request.idempotency_key.empty()) { throw std::invalid_argument("a charge that may be retried needs an idempotency key"); } // No condition between the two semicolons: the loop runs until a // `return` (an answer) or a `throw` (give up) leaves the function. for (int attempt = 1;; ++attempt) { // Only TransientFailure is caught; KeyReused and every other // exception leave the loop unretried. try { return gateway_->charge(request); // a decline is an answer: not retried } catch (const TransientFailure&) { if (attempt >= policy_.max_attempts) { // A bare `throw;` rethrows the exception being handled, the // gateway's own TransientFailure with its message. throw; // still unknown; the caller must not assume either outcome } } // Only reached after a TransientFailure with attempts left. The // attempt that just failed has the same number as the retry about to // happen: after attempt 1 fails, retry 1 waits up to first_delay. const std::chrono::milliseconds limit = backoff_limit(policy_, attempt); const double raw = random_fraction_(); // Clamp to [0, 1]: below 0 becomes 0, above 1 becomes 1. Any // comparison with NaN is false, so NaN takes the `: 0.0` branch. const double fraction = raw >= 0.0 ? std::min(raw, 1.0) : 0.0; // a NaN becomes 0 // limit * fraction is a duration counted in fractional milliseconds; // duration_cast turns it back into whole milliseconds, dropping the // fraction (it rounds toward zero). The constructor's one-day cap // keeps the numbers far from any overflow. sleeper_->sleep_for(std::chrono::duration_cast<std::chrono::milliseconds>(limit * fraction)); }}How this code works: RetryingCharger::charge
- Refuse a request with no key, before calling anything. Without a key, a retry could charge twice.
- Try.
return gateway_->charge(request)leaves the function with the first answer that comes back, a charge or a decline. - If the outcome is unknown, the
catchruns. On the last allowed attempt,throw;rethrows the sameTransientFailureand the function ends. Any other exception, such asKeyReused, is not caught here at all, so it leaves the function at once, from whichever attempt threw it, with no retry. - Otherwise wait, then loop. The
catchblock ends, the limit for this retry is worked out, a random fraction from 0 to 1 is drawn and kept in range, and the sleeper is asked to wait that fraction of the limit. Then++attemptand back to step 2, with the samerequest.
A worked example, from the test
the_charger_waits_a_jittered_fraction_of_each_limit: a policy of 4
attempts, 100 ms first delay, 1000 ms cap; a “random” source that
always returns 0.5; and the provider scripted to be unavailable three
times.
attempt |
Gateway | Limit for this retry | Wait (half the limit) |
|---|---|---|---|
| 1 | unavailable | 100 ms | 50 ms |
| 2 | unavailable | 200 ms | 100 ms |
| 3 | unavailable | 400 ms | 200 ms |
| 4 | no fault: charged, ch-1 |
(none) | (none): returns |
The recorded waits are 50, 100, and 200 ms, which is what the test
checks. In the demo’s third scene every reply is lost: the same thing
happens for attempts 1 to 3, with random waits of up to 5, 10, and 20
ms, and on attempt 4 attempt >= policy_.max_attempts is true, so the
failure is rethrown with no fourth wait.
- Only
TransientFailureis retried. A decline returns as a receipt;KeyReusedand any other exception leave the loop on the first try. Thecatchnames exactly the one type that means “a later try may succeed”. - The same request is sent every time, so the key is the same
every time. The charger takes the request as
const&and never builds a new one. - A request without a key is refused. Retrying it is exactly the double-charge of the first section, so the charger makes that impossible rather than documenting it.
- No wait after the last attempt. The loop rethrows the last failure at once. The caller then knows that the outcome is still unknown, and must not show the customer either “paid” or “failed”; it can ask again later with the same request, as the demo does.
- The wait happens after the
catchblock ends. Nothing slow runs while the exception is being handled, and the code reads as “try; if it failed, wait; loop”. - The
Sleeperand the random source are injected, as in Dependency direction and dependency injection. The program passes a sleeper that really sleeps and a random number engine; the tests pass a sleeper that records the waits and a “random” source that always returns one half (R5). gateway_andsleeper_are pointers, set from references. The constructor takes references, so neither can be null, and storing pointers keeps the class assignable. The objects are not owned; the header states that they must outlive the charger.
Why jitter?
Section titled “Why jitter?”Suppose the provider has a short outage, and 1,000 shops’ requests fail at the same moment. Without jitter, all 1,000 retry exactly 100 milliseconds later, and fail again together, because the provider has just been hit by 1,000 requests at once. Then all 1,000 retry at 200 milliseconds, and so on. The backoff spaces the retries out in time, but they all stay together.
Jitter picks a random wait instead. With “full jitter”, as here, each client waits a random time between zero and the limit. The 1,000 first retries are spread over the whole 100 milliseconds, roughly 10 per millisecond instead of 1,000 at once. The average wait is half the limit, so jitter also makes the typical retry sooner.
Text description of the diagram
The shop’s retrying charger sends “charge order-1042, 42.00” to the provider. The provider finds no record for the key order-1042, charges the card, creates receipt ch-3, and stores the key with the request and the receipt. Its reply is lost, so the shop sees a transient failure. The shop waits a random time up to the first backoff limit, then sends exactly the same request again. This time the provider finds the record for order-1042, checks that the request is the same, and replies with the stored receipt ch-3 without charging again. The card has been charged once, and the shop has the receipt of that one charge.
Diagram source (Mermaid)
sequenceDiagram
participant S as Shop, RetryingCharger
participant P as Provider
participant R as Key records
S->>P: charge order-1042, 42.00
P->>R: no record for order-1042
P->>P: charge the card, receipt ch-3
P->>R: store order-1042, request, ch-3
P--xS: reply lost, TransientFailure
Note over S: wait a random time up to 5 ms
S->>P: charge order-1042, 42.00, same request
P->>R: record found, same request
P-->>S: receipt ch-3, no new charge
Note over S: charged once, as ch-3Duplicates on the receiving side
Section titled “Duplicates on the receiving side”R6 is the same problem from the other direction. The provider sends “payment ch-3 succeeded” to the shop and retries until the shop says it received it. If the shop’s acknowledgement is lost, the notification comes again. This is at-least-once delivery: nothing is lost, but repeats are possible. The receiver must make the repeat harmless.
The first tool is the one from Step 1: make the handler’s effect naturally idempotent where you can. “Mark order 1042 as paid” can run twice. “Send the receipt email” cannot, so for that effect, the receiver remembers which notifications it has handled:
VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// Remembers the last `capacity` message ids, to ignore repeats of// messages that are delivered "at least once". Memory stays bounded; the// price is that a repeat arriving after `capacity` newer messages is not// recognized. Thread safety: not safe.class RecentIds {public: // Throws std::invalid_argument for a capacity of 0, which could // remember nothing. explicit RecentIds(std::size_t capacity);
// True the first time an id is seen, and remembers it; false for a // repeat. Strong guarantee: if it throws, nothing was remembered. [[nodiscard]] bool first_time(const std::string& id);
private: // Invariant: both containers hold exactly the same ids, at most // capacity_ of them. The set answers "seen before?" quickly (on average // in constant time); the deque knows which id is the oldest. std::unordered_set<std::string> seen_; std::deque<std::string> order_; // the same ids, oldest first, for forgetting std::size_t capacity_;};VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// Three steps: try to add the id to the set (which also says whether it is// new), add it to the end of the deque, then forget the oldest id if the// window is now over capacity. Only the first two steps can throw (both// copy the string, which can run out of memory), and each leaves things as// they were if it does, so the whole call gives the strong guarantee.bool RecentIds::first_time(const std::string& id) { // insert returns a pair: an iterator, and a bool that is true only if // the id was not there and has now been added. If insert throws, the // set is unchanged: the standard promises that for a one-element insert. if (!seen_.insert(id).second) { return false; // a repeat } try { // If push_back throws, the deque is unchanged (a standard promise // for adding at either end), but the set already has the id. order_.push_back(id); } catch (...) { // catch (...) catches any exception. Erasing by key does not throw // here, so the undo itself cannot fail; then `throw;` passes the // original exception on to the caller. seen_.erase(id); // undo, so the two containers still agree throw; } // At most one id over the limit, since each call adds at most one. The // oldest is never the new id: the capacity is at least 1, so being over // it means the deque holds at least two ids, and the new one, pushed at // the back, appears only once (it was not in the set, so not here). if (order_.size() > capacity_) { // front() is the deque's copy of the oldest id; the set's copy is // erased first, while that reference is still valid, then the // deque's copy goes. Neither step can throw. seen_.erase(order_.front()); // forget the oldest order_.pop_front(); } return true;}How this code works: RecentIds::first_time
- Ask and add in one step.
seen_.insert(id)adds the id if it is new and says so in.second. If it was already there, the function returnsfalseand changes nothing. - Add the id to the back of the queue. If that throws, the
catchremoves the id from the set again and rethrows, so the set and the queue still hold the same ids. That undo is what gives the strong guarantee: either the id is fully remembered, or nothing changed. - Forget the oldest if there are too many. Each call adds at most one id, so at most one has to go: the one at the front of the queue, removed from the set and then from the queue. Neither step can throw.
A worked example, from the test with room for 2 ids:
| Call | New? | seen_ after |
order_ after (oldest first) |
Returns |
|---|---|---|---|---|
first_time("a") |
yes | a |
a |
true |
first_time("b") |
yes | a, b |
a, b |
true |
first_time("c") |
yes | b, c |
b, c (a is forgotten) |
true |
first_time("c") |
no | b, c |
b, c |
false |
first_time("a") |
yes | c, a |
c, a (b is forgotten) |
true |
The last row is the window’s known limit: "a" was a repeat, but it
came after two newer ids, so it is taken as new.
- Two containers, one for each question. The
unordered_setanswers “have I seen this id?” quickly. Thedequeremembers the order in which ids arrived, so the oldest can be forgotten. - Bounded memory, at a price. Like the bounded queue in
Backpressure and bounded queues, the window
has a fixed size. A repeat that arrives after
capacitynewer notifications is not recognized. Choose the capacity from how late a repeat can come: if the provider retries for at most an hour, the window must hold at least an hour of notifications. - The strong guarantee.
first_timeinserts into the set first, because that also tells it whether the id is new. If thedequethen fails to grow, it removes the id from the set again, so the two containers never disagree: the technique from Exception safety. - In memory only. The window is lost when the program restarts, and the first repeats after a restart get through. Where that matters, the handled ids are stored with the effect, in the same transaction: the idempotent receiver in Transaction and persistence boundaries.
Running it
Section titled “Running it”VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// Six short scenes against one stub provider. Amounts are in cents, and// the ' in 500'00 or 42'00 is only a digit separator for the reader:// 500'00 is 50000 cents, 500.00. ThreadSleeper (really sleeps) and// describe (an Outcome as text) are small helpers defined above main.int main() { using Fault = FakeProvider::Fault; // a short name for the nested enum FakeProvider provider(500'00); // declines anything above 500.00
// 1. Retrying without a key: the first reply is lost, so the shop tries // again, and the provider, which cannot tell, charges a second time. provider.script({Fault::lose_response}); const ChargeRequest unkeyed{"", "alice", 42'00}; // key, account, amount try { // charge is [[nodiscard]]; static_cast<void> says "result ignored on // purpose". The first call charges and then throws: reply lost. static_cast<void>(provider.charge(unkeyed)); } catch (const pay::TransientFailure&) { static_cast<void>(provider.charge(unkeyed)); // "it timed out, try again" } std::cout << "no key, retried once: alice charged " << provider.charges_to("alice") << " times\n";
// 2. The same failure with a key and the retrying charger. ThreadSleeper sleeper; // A random number engine, seeded from std::random_device so each run // differs, and a distribution that turns its output into a double from // 0.0 up to (not including) 1.0: the jitter fraction. std::mt19937 engine{std::random_device{}()}; std::uniform_real_distribution<double> fraction(0.0, 1.0); // 4 attempts, waits capped at 5, 10, 20 ms (5ms is a chrono literal). // The lambda [&] uses `fraction` and `engine` by reference. Those two, // the provider, and the sleeper were all made before the charger, so // they are destroyed after it and outlive it, as the charger requires. pay::RetryingCharger charger(provider, pay::RetryPolicy{4, 5ms, 40ms}, sleeper, [&] { return fraction(engine); });
// One lost reply: attempt 1 charges as ch-3 but throws; attempt 2 is a // repeat of the key and gets ch-3 back, with no second charge. provider.script({Fault::lose_response}); const ChargeRequest order_1042{"order-1042", "bob", 42'00}; const Receipt paid = charger.charge(order_1042); std::cout << "key order-1042: " << describe(paid.outcome) << " as " << paid.charge_id << ", bob charged " << provider.charges_to("bob") << " time\n";
// 3. Every reply lost: the charger gives up, and the outcome is unknown. // Asking again later with the same key gets the original answer. provider.script({Fault::lose_response, Fault::lose_response, Fault::lose_response, Fault::lose_response}); const ChargeRequest order_1043{"order-1043", "carol", 18'50}; // Counting calls before and after shows how many the charger made. const int calls_before_1043 = provider.calls(); try { // Attempt 1 charges as ch-4 and loses the reply; attempts 2 to 4 are // answered from the record but lose the reply too. Then it gives up. static_cast<void>(charger.charge(order_1043)); } catch (const pay::TransientFailure& failure) { std::cout << "key order-1043: gave up after " << provider.calls() - calls_before_1043 << " attempts (" << failure.what() << ")\n"; } const Receipt later = charger.charge(order_1043); // script used up: no fault now std::cout << "key order-1043, asked again later: " << describe(later.outcome) << " as " << later.charge_id << ", carol charged " << provider.charges_to("carol") << " time\n";
// 4. A decline is an answer: it is not retried. const int calls_before = provider.calls(); // The braces build a temporary ChargeRequest that lives until the end // of this statement. 900.00 is above the 500.00 limit: declined. const Receipt declined = charger.charge({"order-1044", "dave", 900'00}); std::cout << "key order-1044: " << describe(declined.outcome) << " after " << provider.calls() - calls_before << " call\n";
// 5. The same key for a different payment is a bug, and is refused. // The charger does not catch KeyReused, so it reaches this catch after // a single call. try { static_cast<void>(charger.charge({"order-1042", "bob", 99'00})); } catch (const pay::KeyReused& error) { std::cout << "key order-1042 for 99.00: refused, " << error.what() << '\n'; }
// 6. Notifications delivered at least once: repeats are ignored. pay::RecentIds seen(1000); // The loop walks a brace list of three ids; each is copied into the // std::string `event`. The ?: picks the message: the first evt-7 and // evt-8 are new, the second evt-7 is a repeat. for (const std::string event : {"evt-7", "evt-8", "evt-7"}) { std::cout << "notification " << event << ": " << (seen.first_time(event) ? "receipt email sent" : "repeat, ignored") << '\n'; }}no key, retried once: alice charged 2 timeskey order-1042: charged as ch-3, bob charged 1 timekey order-1043: gave up after 4 attempts (timed out waiting for the reply)key order-1043, asked again later: charged as ch-4, carol charged 1 timekey order-1044: declined after 1 callkey order-1042 for 99.00: refused, idempotency key already used for a different requestnotification evt-7: receipt email sentnotification evt-8: receipt email sentnotification evt-7: repeat, ignored- No key: charged twice. The stub loses the first reply, the naive retry tries again, and the provider has no way to know it is a repeat. This is the bug from the first section, really happening.
- With a key: charged once, and the receipt is
ch-3, the charge made by the first attempt, whose reply was lost. - Every reply lost. The charger gives up after four attempts and
rethrows. The program does not know the outcome, so it says so. When
it asks again later with the same key, the provider answers from its
record: the first attempt had charged the card, as
ch-4, and no second charge is made. - A decline comes back after one call: no retry, no wait (R3).
- The same key for a different amount is refused, which exposes the bug in the caller.
- A repeated notification is ignored, so the receipt email is sent once (R6).
- The program’s waits are real but short: the demo uses a policy of 4 attempts starting at 5 milliseconds, and a real random engine. The output does not depend on how long each wait was.
Testing
Section titled “Testing”VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// Records each wait instead of sleeping, so the tests are fast and can// check the delays exactly. `waits` is public on purpose: a test reads it// afterwards to see every delay the charger asked for, in order.class RecordingSleeper final : public pay::Sleeper {public: void sleep_for(std::chrono::milliseconds delay) override { waits.push_back(delay); } std::vector<std::chrono::milliseconds> waits;};
// Jitter fixed at one half, so every delay is half its backoff limit.// A plain function can be passed where the charger wants a// std::function<double()>: it takes nothing and returns a double.double half() { return 0.5; }VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// LLD_TEST(name) defines one test. LLD_CHECK(condition) records a failure// if the condition is false; LLD_CHECK_EQ(actual, expected) does the same// for actual == expected and also prints both values when they differ;// LLD_CHECK_THROWS(expr, type) fails unless the expression throws that// type. They come from the site's small test header, lld_test.hpp.// 100ms and 1000ms are chrono literals, made available by// `using namespace std::chrono_literals` at the top of the file.
// The pure function on its own: limits 100, 200, 400, 800, then the cap.// Retry 5 would be 1600 without the cap; retry 60 checks that the loop// stops at the cap instead of doubling on.LLD_TEST(backoff_doubles_and_stops_at_the_cap) { const RetryPolicy policy{10, 100ms, 1000ms}; LLD_CHECK(pay::backoff_limit(policy, 1) == 100ms); LLD_CHECK(pay::backoff_limit(policy, 2) == 200ms); LLD_CHECK(pay::backoff_limit(policy, 3) == 400ms); LLD_CHECK(pay::backoff_limit(policy, 4) == 800ms); LLD_CHECK(pay::backoff_limit(policy, 5) == 1000ms); LLD_CHECK(pay::backoff_limit(policy, 60) == 1000ms);}
// The largest possible cap. Plain doubling from 1 ms would overflow the// count (a signed 64-bit number with GCC and Clang) on its 63rd doubling,// long before retry 100; the "more than half// the cap? then jump to the cap" rule reaches the cap without that. The// constructor would refuse this policy (over a day), but the free function// accepts it, which is what this test exercises.LLD_TEST(backoff_reaches_a_huge_cap_without_overflowing) { const RetryPolicy policy{100, 1ms, std::chrono::milliseconds::max()}; LLD_CHECK(pay::backoff_limit(policy, 100) == std::chrono::milliseconds::max());}
// Three "unavailable" faults, then success on attempt 4. After attempts 1,// 2, and 3 the limits are 100, 200, and 400 ms, and half of each is waited.LLD_TEST(the_charger_waits_a_jittered_fraction_of_each_limit) { FakeProvider provider(1'000'00); // declines only above 1000.00 RecordingSleeper sleeper; RetryingCharger charger(provider, RetryPolicy{4, 100ms, 1000ms}, sleeper, half); provider.script({Fault::unavailable, Fault::unavailable, Fault::unavailable}); static_cast<void>(charger.charge({"k1", "acct", 10'00})); // The extra parentheses matter: without them the preprocessor would // split the macro's argument at the commas inside the braces. // std::vector{...} works out the element type from the values. LLD_CHECK(sleeper.waits == (std::vector{50ms, 100ms, 200ms}));}backoff_limitis a pure function, so its test needs no fakes: given a policy and a retry number, check the limit, including the cap and a retry number far past it.- The charger’s waits are checked exactly. Three failures, a fixed jitter of one half, and the recorded waits must be 50, 100, and 200 milliseconds. No test sleeps, and none depends on chance (R5).
VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// Two lost replies with the default policy (4 attempts). Attempt 1 charges// and records the key; attempt 2 is a repeat whose reply is lost too;// attempt 3 gets the stored receipt. Three calls, one charge.LLD_TEST(a_lost_reply_is_retried_with_the_same_key_and_charges_once) { FakeProvider provider(1'000'00); RecordingSleeper sleeper; RetryingCharger charger(provider, RetryPolicy{}, sleeper, half); provider.script({Fault::lose_response, Fault::lose_response}); const pay::Receipt receipt = charger.charge({"order-1", "acct", 10'00}); LLD_CHECK(receipt.outcome == Outcome::charged); LLD_CHECK_EQ(provider.calls(), 3); LLD_CHECK_EQ(provider.charges_to("acct"), 1);}
// 10.00 against a 5.00 limit: declined on the first call, and that answer// comes back as a Receipt, so there is no retry and no wait.LLD_TEST(a_decline_is_not_retried) { FakeProvider provider(5'00); RecordingSleeper sleeper; RetryingCharger charger(provider, RetryPolicy{}, sleeper, half); LLD_CHECK(charger.charge({"order-1", "acct", 10'00}).outcome == Outcome::declined); LLD_CHECK_EQ(provider.calls(), 1); LLD_CHECK(sleeper.waits.empty());}
// Three attempts allowed, three replies lost: the third failure is// rethrown. Waits come only between attempts, so there are two. A later// call (the script is now empty) finds the record from attempt 1.LLD_TEST(after_the_last_attempt_the_failure_reaches_the_caller) { FakeProvider provider(1'000'00); RecordingSleeper sleeper; RetryingCharger charger(provider, RetryPolicy{3, 10ms, 100ms}, sleeper, half); provider.script({Fault::lose_response, Fault::lose_response, Fault::lose_response}); LLD_CHECK_THROWS(charger.charge({"order-1", "acct", 10'00}), pay::TransientFailure); LLD_CHECK_EQ(provider.calls(), 3); // 2u is an unsigned 2, to match the unsigned type size() returns. LLD_CHECK_EQ(sleeper.waits.size(), 2u); // no wait after the last attempt // The first attempt did charge; asking again finds that answer. LLD_CHECK(charger.charge({"order-1", "acct", 10'00}).outcome == Outcome::charged); LLD_CHECK_EQ(provider.charges_to("acct"), 1);}
// The same key with a different amount: one call for the first charge,// one for the refused request. A retry would have made it three.LLD_TEST(a_reused_key_is_refused_and_not_retried) { FakeProvider provider(1'000'00); RecordingSleeper sleeper; RetryingCharger charger(provider, RetryPolicy{}, sleeper, half); static_cast<void>(charger.charge({"order-1", "acct", 10'00})); LLD_CHECK_THROWS(charger.charge({"order-1", "acct", 20'00}), pay::KeyReused); LLD_CHECK_EQ(provider.calls(), 2);}
// An empty key is refused before the gateway is called at all.LLD_TEST(the_charger_refuses_a_request_without_a_key) { FakeProvider provider(1'000'00); RecordingSleeper sleeper; RetryingCharger charger(provider, RetryPolicy{}, sleeper, half); LLD_CHECK_THROWS(charger.charge({"", "acct", 10'00}), std::invalid_argument); LLD_CHECK_EQ(provider.calls(), 0);}
// Each line builds a temporary charger whose constructor throws: no// attempts, a cap below the first delay, and a cap over a day (25h is a// chrono literal for 25 hours, converted to milliseconds).LLD_TEST(a_policy_without_attempts_is_refused) { FakeProvider provider(1'000'00); RecordingSleeper sleeper; LLD_CHECK_THROWS(RetryingCharger(provider, RetryPolicy{0, 10ms, 100ms}, sleeper, half), std::invalid_argument); LLD_CHECK_THROWS(RetryingCharger(provider, RetryPolicy{3, 100ms, 10ms}, sleeper, half), std::invalid_argument); LLD_CHECK_THROWS(RetryingCharger(provider, RetryPolicy{3, 100ms, 25h}, sleeper, half), std::invalid_argument);}- Each rule of the charger has its own test: a lost reply is retried and charges once; a decline is not retried; after the last attempt the failure reaches the caller, with no wait after it; a reused key is not retried; a request without a key never reaches the gateway; a policy without attempts is refused.
- The tests count calls and charges separately. Three calls and one charge is the whole point of the key, and the stub can report both.
VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// The stub's own two rules, without the charger. Same keyed request twice:// the second receipt is the stored one (same charge id), and one charge.LLD_TEST(the_provider_answers_a_repeated_key_from_its_record) { FakeProvider provider(1'000'00); const ChargeRequest request{"order-1", "acct", 10'00}; const pay::Receipt first = provider.charge(request); const pay::Receipt again = provider.charge(request); LLD_CHECK(first == again); LLD_CHECK_EQ(provider.charges_to("acct"), 1);}
// No key, so no record: the same request twice is two charges.LLD_TEST(without_a_key_every_call_is_a_new_charge) { FakeProvider provider(1'000'00); const ChargeRequest request{"", "acct", 10'00}; static_cast<void>(provider.charge(request)); static_cast<void>(provider.charge(request)); LLD_CHECK_EQ(provider.charges_to("acct"), 2);}VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// Room for 10, so nothing is forgotten: the second "a" is a repeat.LLD_TEST(recent_ids_recognize_a_repeat) { pay::RecentIds seen(10); LLD_CHECK(seen.first_time("a")); LLD_CHECK(seen.first_time("b")); LLD_CHECK(!seen.first_time("a"));}
// Room for 2. After "c" the window holds "b" and "c"; "c" again is a// repeat; "a" is taken as new, the known limit of a bounded window.// Adding "a" then pushes out "b", leaving "c" and "a".LLD_TEST(recent_ids_forget_the_oldest_beyond_their_capacity) { pay::RecentIds seen(2); LLD_CHECK(seen.first_time("a")); LLD_CHECK(seen.first_time("b")); LLD_CHECK(seen.first_time("c")); // "a" is forgotten LLD_CHECK(!seen.first_time("c")); LLD_CHECK(seen.first_time("a")); // a repeat that came too late}- The stub provider is tested too. The retry tests trust it to behave like a provider with idempotency keys, so its own two rules are checked directly.
- The window’s limit is tested, including the case it gets wrong
on purpose: a repeat of
"a"after two newer ids is taken as new. A test that shows a known limit documents it.
These tests run the code on one thread. Nothing in this example is
thread safe, and the headers say so. A charger shared by several
threads would need its random engine guarded, or one engine per
thread, as Thread safety describes for
other shared state; and the gateway and sleeper it calls would have to
be safe to call from several threads, which FakeProvider is not.
The design at a glance
Section titled “The design at a glance”struct pay::ChargeRequest
a value; the key names the intent
Member functions
std::string idempotency_key;std::string account;long long amount_cents;
interface (abstract class) pay::PaymentGateway
Member functions
virtual Receipt charge(const ChargeRequest& request) = 0;nodiscard; throws TransientFailure or KeyReused
class pay::RetryingCharger
not thread safe; does not own its gateway or sleeper
Data members
PaymentGateway* gateway_;RetryPolicy policy_;Sleeper* sleeper_;std::function<double()> random_fraction_;
Member functions
RetryingCharger(PaymentGateway& gateway, RetryPolicy policy, Sleeper& sleeper, std::function<double()> random_fraction);Receipt charge(const ChargeRequest& request);nodiscard; retries TransientFailure only; refuses an empty key
class pay::FakeProvider
a stub; implements PaymentGateway
Data members
std::map<std::string, Stored, std::less<>> by_key_;the idempotency records
Member functions
void script(std::initializer_list<Fault> faults);Receipt charge(const ChargeRequest& request) override;a repeated key returns the stored receiptint calls() const noexcept;int charges_to(std::string_view account) const;
class pay::RecentIds
not thread safe; bounded memory
Data members
std::unordered_set<std::string> seen_;std::deque<std::string> order_;oldest first
Member functions
explicit RecentIds(std::size_t capacity);bool first_time(const std::string& id);nodiscard; strong guarantee
When retrying is unsafe
Section titled “When retrying is unsafe”Even with backoff and jitter, some calls must not be retried automatically:
- The operation is not idempotent, and the receiver has no key. Many services, including many email, SMS, and printing services, offer no idempotency key. A retry after a timeout may repeat the effect. Then either accept a rare duplicate, or do not retry and report the unknown outcome to a person.
- The failure is not transient. A decline, a validation error, or “permission denied” will give the same answer every time. Retrying only adds load and delay.
- Someone is waiting. A user who clicked “pay” should not watch a spinner through a minute of backoff. Keep the total retry time shorter than the user’s patience, and then say “we are checking your payment” rather than “failed”.
- The request has a deadline. If the caller will give up after two seconds, a retry scheduled for the third second does nothing useful.
- The service is overloaded, and everyone is retrying. Retries are extra load at the worst moment. Limit them (the warning above about layers) and spread them out (jitter).
- The effect happened elsewhere first. If the call failed after a local change, such as reserving stock, retrying the call is not enough; decide what happens to the local change, as Invariants and failure scenarios asks for every failure.
When this design fits, and when it does not
Section titled “When this design fits, and when it does not”Idempotency keys with a retrying caller fit when:
- A call crosses a boundary that can fail silently: a network, a queue, another process.
- The effect is valuable and not easily undone, such as money, stock, or messages to customers.
- The receiver can store a record per key, in the same transaction as the effect.
Something simpler fits when:
- The call is in the same process and either returns or throws. There is no unknown outcome, and no reason to retry.
- The operation is naturally idempotent. Retry it without keys, as long as a late repeat cannot overwrite a newer change.
- A duplicate is cheap. A repeated “the page was viewed” counter update may not be worth a key store; count it as noise.
- The receiver cannot store keys. Then the caller cannot make the retry safe, and must decide, per operation, between a possible duplicate and a possible loss.
Common mistakes
Section titled “Common mistakes”- Retrying every exception, including declines and bugs.
- A new key for each attempt, which makes the key useless.
- One key for two intents, which returns the first intent’s result to the second.
- Treating a timeout as a failure and telling the customer “your payment failed” when it may have succeeded.
- Retrying without a delay, or without a limit, which turns a short outage into a long one.
- Backoff without jitter, so that every client retries at the same moment.
- Retrying in several layers at once.
- Sleeping in tests, which makes them slow, and using real randomness, which makes them unrepeatable.
- An unbounded set of handled ids, which grows for the life of the program.
When the requirements change
Section titled “When the requirements change”- “The provider sometimes says ‘slow down, retry after 30
seconds’.” Add the suggested wait to
TransientFailure, and let the charger wait at least that long. It is still the same rule: retry only what may pass, after a wait. - “Checkout must answer within 3 seconds.” Give the charger a deadline as well as a number of attempts, through an injected clock so that tests stay deterministic, and stop retrying when the next wait would pass it.
- “Several threads share one charger.” Its own state is the policy, which never changes, and the random source, which does. Give each thread its own random engine, or guard the shared one with a mutex; and the gateway and sleeper it calls must themselves be safe to call from several threads.
- “Notifications must not be handled twice, even across restarts.” The in-memory window is not enough. Store each handled id with the effect, as the idempotent receiver in Transaction and persistence boundaries does.
- “A customer may retry a declined payment with another card.” It is a new intent: give it a new key, such as the order ID with a payment number.
Exercise
Section titled “Exercise”Exercise: Make an operation idempotent
A loyalty program gives points when an order is delivered. A message “order delivered” is sent to the loyalty service at least once, and its handler calls:
// Adds `points` to the customer's balance. Every call adds again, so a// repeated message adds the points twice.void add_points(const std::string& customer, int points);This code is illustrative and was not compiled.
- Explain why a repeated message gives the customer too many points.
- Change the design so that a repeat has no effect. Write the new function, and say what it must remember.
- What should happen if a message for the same order arrives with a different number of points?
- Which guarantee does your function give if it throws, and why does that matter here?
Show the explained answer
1. “Add 50 points” is not idempotent: each call adds again. With at-least-once delivery, a repeat is normal, so the handler will sometimes run twice for one order.
2. Make the operation about the order, not just the customer, and remember which orders have been awarded. The order’s ID is the idempotency key; it names the intent “points for order 1042”.
// Thread safety: not safe. Points for one order are awarded once, however// many times the "order delivered" message arrives.class LoyaltyLedger {public: // True if the points were added now; false for a repeat. Throws // std::logic_error if the order was already awarded to a different // customer or amount. // Strong guarantee: every step that can throw comes before the one // change a reader can see (adding to the balance). bool award_for_order(const std::string& order_id, const std::string& customer, int points) { // [] finds the customer's balance, or creates it at 0 first. `total` // is a reference to the int inside the map, so += below changes the // stored balance. A std::map element never moves, so the reference // stays valid while awarded_ changes. int& total = balance_[customer]; // may throw; an empty balance changes nothing // try_emplace adds the order only if its id is not there yet, and // returns a pair: an iterator to the entry for order_id (new or // old), and true if it was just added. The structured binding // [found, inserted] names the two halves. const auto [found, inserted] = awarded_.try_emplace(order_id, Award{customer, points}); if (!inserted) { // A repeat. found->second is what that order earned the first time. if (found->second.customer != customer || found->second.points != points) { throw std::logic_error("order " + order_id + " was already awarded differently"); } return false; // a repeat: nothing changes } total += points; // cannot throw, so the award and the points stay together return true; }
[[nodiscard]] int balance(const std::string& customer) const { const auto found = balance_.find(customer); return found == balance_.end() ? 0 : found->second; }
private: struct Award { std::string customer; int points; }; std::map<std::string, Award> awarded_; // order id -> what it earned std::map<std::string, int> balance_;};This class, with the needed includes and a main that awards the
points for one order three times and then once with a different
amount, was compiled with GCC 11.4 and Clang 14 with warnings as
errors, and run, also under AddressSanitizer and
UndefinedBehaviorSanitizer. It printed bob has 50 points, then the
std::logic_error message.
Unlike the notification window on this page, the record of awarded
orders is never forgotten: points are money-like, and a late repeat
must still be recognized. In a real service, awarded_ and balance_
would be stored together, in one transaction.
3. Refuse it, loudly. The same key with a different request means
something upstream is wrong, such as an order whose total changed after
delivery. Silently keeping the first amount hides the problem, and
adding the second amount breaks the guarantee. This is what KeyReused
does in the example.
4. The strong guarantee: if it throws, nothing changed. The only
steps that can throw come first: looking up or creating the balance
(an empty balance changes nothing a reader can see, because
balance() returns 0 either way) and inserting the award record. The
one step after the insert, adding to an int, cannot throw. If the
order were reversed, an exception after the points were added but
before the award was recorded would let the next repeat add the points
again, which is the bug the function exists to prevent.
Summary
Section titled “Summary”- A timeout leaves the outcome unknown. Retrying may repeat the effect; not retrying may lose it.
- An idempotency key names one intent. The caller sends the same key on every try; the receiver stores the result under the key and answers repeats from that record.
- Retry only failures that may pass, a limited number of times, waiting longer each time up to a cap, with jitter so that clients do not retry together. Retry in one layer only.
- Inject the waiting and the randomness, so tests check every delay exactly without sleeping.
- With at-least-once delivery, make handlers naturally idempotent where possible, and otherwise remember the handled ids, in a bounded window or, when it must survive restarts, with the effect.
- Some calls must not be retried automatically: those without a key, those that will fail the same way again, and those whose caller can no longer use the answer.