Requests get repeated. A client sends a batch, the connection drops before the reply arrives, and the client cannot tell whether the batch was applied. The only safe thing it can do is send it again. If the ledger applies every arrival, that retry receives the same five widgets twice. The usual fix is an idempotency key: the client attaches an ID to each request, and the server remembers which IDs it has accepted so a repeat can be recognized instead of applied.
An ID alone is not enough of a contract, though. What if the same ID arrives with a different payload? That is almost always a client bug, such as a counter that restarted, and silently treating it as a replay would lose a real request. So the ledger stores the accepted payload under its ID. A repeated ID with an identical payload returns replayed and changes nothing. The same ID with a different payload returns conflict and also changes nothing. Only a new ID can change the value.
Predict and run
How many additions reach the stored value?
use std::collections::BTreeMap;
#[derive(Default)]
struct Counter {
value: u32,
receipts: BTreeMap<u32, u32>,
}
impl Counter {
fn add(&mut self, id: u32, amount: u32) -> Result<&'static str, &'static str> {
if let Some(previous) = self.receipts.get(&id) {
return if *previous == amount { Ok("replayed") } else { Err("conflict") };
}
let next = self.value.checked_add(amount).ok_or("overflow")?;
self.value = next;
self.receipts.insert(id, amount);
Ok("applied")
}
}
fn main() {
let mut counter = Counter::default();
println!("{:?}", counter.add(7, 5));
println!("{:?}", counter.add(7, 5));
println!("{:?}", counter.add(7, 8));
println!("Value: {}", counter.value);
}Check your prediction
Ok("applied")
Ok("replayed")
Err("conflict")
Value: 5Only the first call reached self.value. Now create a second Counter and send add(7, 5) to it. It reports applied again, because receipts live inside one value. A real service that must recognize retries after a restart would need to store receipts durably, and to commit them together with the stock so a crash cannot save one without the other.
The order of the checks is the contract
add looks up the receipt before it does any arithmetic. That order matters most when the state has moved on since the original request.
use std::collections::BTreeMap;
#[derive(Default)]
struct Counter {
value: u32,
receipts: BTreeMap<u32, u32>,
}
impl Counter {
fn add(&mut self, id: u32, amount: u32) -> Result<&'static str, &'static str> {
if let Some(previous) = self.receipts.get(&id) {
return if *previous == amount { Ok("replayed") } else { Err("conflict") };
}
let next = self.value.checked_add(amount).ok_or("overflow")?;
self.value = next;
self.receipts.insert(id, amount);
Ok("applied")
}
}
fn main() {
let mut counter = Counter::default();
println!("{:?}", counter.add(1, u32::MAX - 5));
println!("{:?}", counter.add(7, 5));
println!("{:?}", counter.add(7, 5));
println!("{:?}", counter.add(8, 1));
println!("ID 8 recorded: {}", counter.receipts.contains_key(&8));
println!("Value: {}", counter.value);
}Ok("applied")
Ok("applied")
Ok("replayed")
Err("overflow")
ID 8 recorded: false
Value: 4294967295The retry of ID 7 would overflow if it were applied again, yet it correctly reports replayed: the client is asking "did my request happen?", and the answer is yes. If the arithmetic ran first, that client would see overflow for a request that actually succeeded. ID 8 failed, and because a receipt is written only after the value changes, ID 8 stays free. The client can correct the amount and resend it under the same ID.
That last choice is a real trade-off. Some systems also record failures, so a retry returns the same error every time. That is more predictable, but it forbids correcting a request without minting a new ID. This ledger records only accepted payloads, which keeps the receipt map to exactly the requests that changed state.
Why the payload must be stored
Compare a version that remembers only IDs. It uses a BTreeSet and treats every known ID as a replay.
use std::collections::BTreeSet;
#[derive(Default)]
struct IdOnly {
value: u32,
seen: BTreeSet<u32>,
}
impl IdOnly {
fn add(&mut self, id: u32, amount: u32) -> &'static str {
if !self.seen.insert(id) {
return "replayed";
}
self.value += amount;
"applied"
}
}
fn main() {
let mut counter = IdOnly::default();
println!("{}", counter.add(7, 5));
println!("{}", counter.add(7, 8));
println!("Value: {}", counter.value);
}applied
replayed
Value: 5The request for 8 vanished, and the client was told it had succeeded. Storing the payload costs memory, but it turns an invisible data loss into an explicit conflict the caller can investigate.
Receipts need a budget
Every accepted ID stays in memory for the life of the Counter, so the map grows without bound. Real systems expire receipts after a time window or cap their number. Whatever the rule, a known ID must keep working until its receipt is deliberately dropped.
Practice
Your turn
Limit the counter to two receipts. A new ID that arrives when both slots are taken must fail with Err("full") and change nothing. Accepted IDs must still replay and conflict as before, even when the counter is full. Starting from an empty counter, print the results of:
add(1, 3)andadd(2, 4), bothOk("applied").add(1, 3), which should beOk("replayed").add(1, 5), which should beErr("conflict").add(3, 1), which should beErr("full").- The final value,
7.
use std::collections::BTreeMap;
#[derive(Default)]
struct Counter {
value: u32,
receipts: BTreeMap<u32, u32>,
}
impl Counter {
fn add(&mut self, id: u32, amount: u32) -> Result<&'static str, &'static str> {
if let Some(previous) = self.receipts.get(&id) {
return if *previous == amount { Ok("replayed") } else { Err("conflict") };
}
let next = self.value.checked_add(amount).ok_or("overflow")?;
self.value = next;
self.receipts.insert(id, amount);
Ok("applied")
}
}
fn main() {
// Add a receipt limit in Counter::add, then test a full counter.
}Hint 1: the idea
Check for a known ID before checking space for a new receipt. A replay does not need a new slot.
Hint 2: a first step
Find the line where a brand-new ID is first known to be new: after the existing-ID branch has returned for replays and conflicts, and before anything is calculated or stored. The capacity check goes there, so a replay of a stored ID still succeeds when the store is full. Work out the condition from the limit in the brief.
Worked solution
use std::collections::BTreeMap;
#[derive(Default)]
struct Counter {
value: u32,
receipts: BTreeMap<u32, u32>,
}
impl Counter {
fn add(&mut self, id: u32, amount: u32) -> Result<&'static str, &'static str> {
if let Some(previous) = self.receipts.get(&id) {
return if *previous == amount { Ok("replayed") } else { Err("conflict") };
}
if self.receipts.len() >= 2 { return Err("full"); }
let next = self.value.checked_add(amount).ok_or("overflow")?;
self.value = next;
self.receipts.insert(id, amount);
Ok("applied")
}
}
fn main() {
let mut counter = Counter::default();
println!("{:?}", counter.add(1, 3));
println!("{:?}", counter.add(2, 4));
println!("{:?}", counter.add(1, 3));
println!("{:?}", counter.add(1, 5));
println!("{:?}", counter.add(3, 1));
println!("Value: {}", counter.value);
}Ok("applied")
Ok("applied")
Ok("replayed")
Err("conflict")
Err("full")
Value: 7Placing the capacity check after the receipt lookup means a full counter still answers retries truthfully. Note the boundary: >= rejects the third ID, while > would quietly admit one extra. The Day 7 project carries exactly this check, and its tests include a deliberately broken > version to prove the boundary is covered.
Completion is saved in this browser only. It does not measure mastery.