Design duplicate-safe command handling
Quick answer
A command expresses an intent to change state. If the same command may arrive more than once, the application needs a documented duplicate-handling contract. An idempotency key identifies one intended operation, not every operation with equal data.
How it works
In a bounded in-memory teaching model, store each accepted command ID with its original payload identity and result. Repeating an ID with equal payload returns the earlier result without repeating the mutation. Reusing the ID for conflicting input is rejected. Production servers must scope keys by authenticated actor and operation, coordinate deduplication atomically with effects, bound retention and define retry behavior. A local Map cannot guarantee durable exactly-once delivery.
Local examples
Run in Node.js v22.16.0 as a CommonJS script. Actual ByteMind editor support is unverified.
(async () => {let total=0;const seen=new Map();function add(id,n){if(seen.has(id)){const old=seen.get(id);return old.n===n?old.result:"conflict";}total+=n;seen.set(id,{n,result:total});return total;}console.log(add("A",2),add("A",2),add("A",5),total);})()Expected console output:
2 2 conflict 2The repeat returns the stored result; conflicting reuse is rejected and total stays two.
Run in Node.js v22.16.0 as a CommonJS script. Actual ByteMind editor support is unverified.
(async () => {const commands=[{id:"A",qty:3},{id:"B",qty:3}];console.log(commands[0].qty===commands[1].qty,commands[0].id===commands[1].id);})()Expected console output:
true falseThe quantities match but the operation IDs differ.
Common mistakes
Do not mark a command processed before knowing the defined outcome without a recovery policy. Do not confuse a per-session demo with durable server deduplication.
Practice
Trace an accepted command, a duplicate of the same command and a conflicting reuse of its ID. Verify that only the first changes the total.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Design duplicate-safe command handling — Knowledge Check
Apply the concept and reason about local example output.
What should happen when the same key is reused with conflicting validated payload in this model?
What production property is not provided by an in-memory Map?
Why not deduplicate commands solely by equal quantity?
What is the exact console output in Design duplicate-safe command handling example 1?
(async () => {let total=0;const seen=new Map();function add(id,n){if(seen.has(id)){const old=seen.get(id);return old.n===n?old.result:"conflict";}total+=n;seen.set(id,{n,result:total});return total;}console.log(add("A",2),add("A",2),add("A",5),total);})()What is the exact console output in Design duplicate-safe command handling example 2?
(async () => {const commands=[{id:"A",qty:3},{id:"B",qty:3}];console.log(commands[0].qty===commands[1].qty,commands[0].id===commands[1].id);})()