Skip to content

Idempotency Belongs to an Actor and a Payload

The Course
•
18 min study

The decision

A receipt key is not globally meaningful. Reusing another actor’s key must not return their result, and using the same key for a different payload should not silently report success.

Read, predict, run

The function compares actor, key and payload fingerprint with a stored receipt. It returns replay only for the same logical operation. In persistence, uniqueness and transaction boundaries must protect receipt creation alongside the write:

JavaScript
export function run({ actor, key, fingerprint, receipt }) {
  if (!receipt || receipt.actor !== actor || receipt.key !== key) return "new";
  return receipt.fingerprint === fingerprint ? "replay" : "conflict";
}

Before pressing Run, predict what run returns for {"actor": "ada", "key": "a", "fingerprint": "x", "receipt": {"actor": "ada", "key": "a", "fingerprint": "y"}}, from the code above. Write your answers down first: after Run, the case table shows the expected values beside the actual ones.

Idempotency Belongs to an Actor and a Payload Next.js · 5 files
import "./globals.css"; export default function RootLayout({ children }) { return ( <html lang="en"> <body> <header> <strong>Review Queue · Practice lab</strong> </header> {children} </body> </html> ); } import Cases from "./Cases.jsx"; export default function Page() { return ( <main> <h1>Idempotency Belongs to an Actor and a Payload</h1> <p> Read the input and predict the result before running. Change lib/contract.js for the exercise. </p> <Cases /> </main> ); } import { run, examples } from "@/lib/contract.js"; const text = (value) => JSON.stringify(value) ?? "undefined"; export default async function Cases() { const results = await Promise.all( examples.map(async ([input, expected]) => { // Record the input before running, to show whether run changed it. const before = text(input); const actual = await run(input); return { input: before, expected, actual, kept: text(input) === before, pass: text(actual) === text(expected), }; }), ); return ( <section> <h2>Executable cases</h2> <p> Checks: {results.filter((row) => row.pass).length}/{results.length}{" "} passed </p> <table> <thead> <tr> <th>Input</th> <th>Expected</th> <th>Actual</th> <th>Input kept</th> </tr> </thead> <tbody> {results.map((row, i) => ( <tr key={i}> <td> <code>{row.input}</code> </td> <td> <code>{text(row.expected)}</code> </td> <td className={row.pass ? "pass" : "fail"}> <code>{text(row.actual)}</code> </td> <td className={row.kept ? "pass" : "fail"}> {row.kept ? "yes" : "no: run changed it"} </td> </tr> ))} </tbody> </table> </section> ); } body { font: 16px/1.5 system-ui; margin: 0; color: #182b3c; background: #f4f8fc; } header, main { max-width: 900px; margin: auto; padding: 20px; } header { border-bottom: 1px solid #cbd5e1; } a { color: #075985; } button, input, textarea, select { font: inherit; padding: 8px; margin: 4px; } button { cursor: pointer; } table { border-collapse: collapse; width: 100%; } th, td { padding: 10px; border: 1px solid #cbd5e1; text-align: left; vertical-align: top; } pre, code { white-space: pre-wrap; overflow-wrap: anywhere; } .pass { color: #166534; } .fail, [role="alert"] { color: #a01818; } section { margin: 16px 0; padding: 12px; background: white; border-radius: 8px; } nav { display: flex; gap: 16px; } export function run({ actor, key, fingerprint, receipt }) { if (!receipt || receipt.actor !== actor || receipt.key !== key) return "new"; return receipt.fingerprint === fingerprint ? "replay" : "conflict"; } export const examples = [ [ { actor: "ada", key: "a", fingerprint: "x", receipt: { actor: "ada", key: "a", fingerprint: "y" }, }, "conflict", ], ];
Runs with real Next.js on your computer: unzip, then npm install and npm run dev.
Add and remove files here; write their code in the editor.
Check your prediction
  • Input {"actor": "ada", "key": "a", "fingerprint": "x", "receipt": {"actor": "ada", "key": "a", "fingerprint": "y"}} → "conflict".

The case table computes these results on the server side of the simulation. It compares values; it does not prove a production deployment or database works.

The failure to avoid

If the write commits but its receipt does not, a retry can duplicate it. If the receipt commits first, it can claim success for work that never happened.

Trace the two orderings that go wrong without a transaction.

  • Write, then receipt. The review is saved, then the server crashes before the receipt is stored. The client retries with the same key, finds no receipt, and saves a second copy.
  • Receipt, then write. The receipt is stored, then the write fails. The retry finds the receipt and answers replay, a success, for a review that doesn't exist.

The fix is to make them one unit: insert the receipt and perform the write in the same database transaction, with a unique index on (actor, key). Both commit or neither does, and two concurrent requests with the same key can't both insert a receipt.

Exercise

Extend the contract

An expired receipt should be treated as new. Compare its expiresAt to the supplied now; do not read the clock inside this pure function.

Decide the boundary before coding: is a receipt whose expiresAt equals now still valid? Write your answer as a case, with a sentence on why, then make it pass.

Edit lib/contract.js, then rerun the original cases. If the requested rule changes an earlier result, update that expected value deliberately. Keep the other cases. Add the acceptance cases to examples so the preview checks them too.

  • Input {"actor": "ada", "key": "a", "fingerprint": "x", "now": 10, "receipt": {"actor": "ada", "key": "a", "fingerprint": "x", "expiresAt": 10}} must return "new".
Your working space Next.js · 5 files
import "./globals.css"; export default function RootLayout({ children }) { return ( <html lang="en"> <body> <header> <strong>Review Queue · Practice lab</strong> </header> {children} </body> </html> ); } import Cases from "./Cases.jsx"; export default function Page() { return ( <main> <h1>Idempotency Belongs to an Actor and a Payload</h1> <p> Read the input and predict the result before running. Change lib/contract.js for the exercise. </p> <Cases /> </main> ); } import { run, examples } from "@/lib/contract.js"; const text = (value) => JSON.stringify(value) ?? "undefined"; export default async function Cases() { const results = await Promise.all( examples.map(async ([input, expected]) => { // Record the input before running, to show whether run changed it. const before = text(input); const actual = await run(input); return { input: before, expected, actual, kept: text(input) === before, pass: text(actual) === text(expected), }; }), ); return ( <section> <h2>Executable cases</h2> <p> Checks: {results.filter((row) => row.pass).length}/{results.length}{" "} passed </p> <table> <thead> <tr> <th>Input</th> <th>Expected</th> <th>Actual</th> <th>Input kept</th> </tr> </thead> <tbody> {results.map((row, i) => ( <tr key={i}> <td> <code>{row.input}</code> </td> <td> <code>{text(row.expected)}</code> </td> <td className={row.pass ? "pass" : "fail"}> <code>{text(row.actual)}</code> </td> <td className={row.kept ? "pass" : "fail"}> {row.kept ? "yes" : "no: run changed it"} </td> </tr> ))} </tbody> </table> </section> ); } body { font: 16px/1.5 system-ui; margin: 0; color: #182b3c; background: #f4f8fc; } header, main { max-width: 900px; margin: auto; padding: 20px; } header { border-bottom: 1px solid #cbd5e1; } a { color: #075985; } button, input, textarea, select { font: inherit; padding: 8px; margin: 4px; } button { cursor: pointer; } table { border-collapse: collapse; width: 100%; } th, td { padding: 10px; border: 1px solid #cbd5e1; text-align: left; vertical-align: top; } pre, code { white-space: pre-wrap; overflow-wrap: anywhere; } .pass { color: #166534; } .fail, [role="alert"] { color: #a01818; } section { margin: 16px 0; padding: 12px; background: white; border-radius: 8px; } nav { display: flex; gap: 16px; } export function run({ actor, key, fingerprint, receipt }) { if (!receipt || receipt.actor !== actor || receipt.key !== key) return "new"; return receipt.fingerprint === fingerprint ? "replay" : "conflict"; } export const examples = [ [ { actor: "ada", key: "a", fingerprint: "x", receipt: { actor: "ada", key: "a", fingerprint: "y" }, }, "conflict", ], ];
Runs with real Next.js on your computer: unzip, then npm install and npm run dev.
Add and remove files here; write their code in the editor.
Hint 1: the idea

A receipt is evidence for a limited time. After it expires, the key may be reused, so the request is new again. Time is an input to the decision, like the actor.

Hint 2: a first step

Keep time an explicit input so a test can exercise the exact expiry boundary.

Show one solution

Replace the exported run function and any constants shown here; keep the examples export underneath it. Compare the result with your own approach.

JavaScript
export function run({ actor, key, fingerprint, receipt, now }) {
  if (
    !receipt ||
    receipt.expiresAt <= now ||
    receipt.actor !== actor ||
    receipt.key !== key
  )
    return "new";
  return receipt.fingerprint === fingerprint ? "replay" : "conflict";
}

receipt.expiresAt <= now treats the exact expiry moment as expired, which the acceptance case pins with expiresAt: 10, now: 10. It sits with the other reasons to answer new, before the fingerprint, so an expired receipt can never produce replay or conflict. Taking now as an input lets a test hit the boundary exactly; reading Date.now() inside would make the test depend on timing.

Explain it without the code

Write what a client should do when it receives conflict for a key it reused with a different payload.

Going further

Read the Next.js guide for the framework boundary around this rule. The preview runs code-playpad's Next.js simulation. Real caching, hydration, authentication and persistence require the real-server checks described on Day 7.

Was this article helpful?

Your response is saved on this device.