Two concurrent calls can describe one logical action. This exercise gives them the same operation key and checks that a local transport runs once. A second case simulates a lost acknowledgement after the action has already happened.

Use Node.js 22 or newer. The program keeps synthetic effects in an array and never contacts a service. It assumes the application already authenticated and authorized the action; idempotency does not grant permission to act.

1. Track one operation and its payload

Save this as idempotency.mjs. The trusted scope and operation key identify the action. A digest binds that key to the normalized message. The promise is shared while work is pending, so duplicate callers observe the same operation.

import assert from 'node:assert/strict';
import { createHash } from 'node:crypto';

const records = new Map();
const effects = [];
async function execute(scope, key, input, transport) {
  for (const value of [scope, key]) assert(typeof value === 'string' && /^[a-z0-9-]{1,40}$/.test(value), 'invalid identity');
  assert(input && typeof input === 'object' && !Array.isArray(input), 'invalid action');
  assert.deepEqual(Object.keys(input), ['message']);
  assert(typeof input.message === 'string' && input.message.length > 0 && input.message.length <= 2000, 'invalid message');
  const action = { message: input.message };
  const fingerprint = createHash('sha256').update(JSON.stringify(action)).digest('hex');
  const recordKey = JSON.stringify([scope, key]);
  const existing = records.get(recordKey);
  if (existing) {
    assert.equal(existing.fingerprint, fingerprint, 'operation key conflict');
    assert(existing.state !== 'unknown', 'reconciliation required');
    return existing.promise;
  }
  // ponytail: one process and synthetic effects; production needs durable claims and provider idempotency.
  const record = { fingerprint, state: 'pending' };
  records.set(recordKey, record);
  record.promise = Promise.resolve().then(() => transport(action)).then(
    (result) => { record.state = 'accepted'; return result; },
    () => { record.state = 'unknown'; throw new Error('outcome unknown'); },
  );
  return record.promise;
}

const deliver = async (action) => { effects.push(action); return { reference: effects.length }; };
const input = { message: 'Synthetic notification' };
const results = await Promise.all([
  execute('tenant-a', 'op-1', input, deliver),
  execute('tenant-a', 'op-1', input, deliver),
]);
assert.equal(effects.length, 1);
assert.deepEqual(results[0], results[1]);
await execute('tenant-a', 'op-1', input, deliver);
assert.equal(effects.length, 1);
await assert.rejects(execute('tenant-a', 'op-1', { message: 'Changed' }, deliver), /operation key conflict/);
await execute('tenant-b', 'op-1', input, deliver);
assert.equal(effects.length, 2);
const loseAcknowledgement = async (action) => { effects.push(action); throw new Error('simulated lost response'); };
await assert.rejects(execute('tenant-a', 'op-2', input, loseAcknowledgement), /outcome unknown/);
assert.equal(effects.length, 3);
await assert.rejects(execute('tenant-a', 'op-2', input, deliver), /reconciliation required/);
assert.equal(effects.length, 3, 'unknown outcome must not trigger a second effect');
console.log('PASS: duplicate calls share one effect; conflicts and uncertain retries are blocked.');

2. Run and count effects

node idempotency.mjs

The PASS: line means the assertions completed. The array contains three effects: one for tenant A’s first operation, one for tenant B’s independent operation, and one whose acknowledgement was lost.

The last effect is especially important. An error did occur, but the effect count increased. The next retry is held for reconciliation rather than silently creating a fourth effect.

3. Verify the test detects duplicate execution

In a temporary copy, replace if (existing) { with if (false) {. Re-run the program. The first effect-count assertion must fail because the two calls both reach the transport. Restore the condition afterward.

You can also remove the fingerprint assertion to confirm that the changed-payload check fails. A repeated key should never authorize different content merely because a prior action succeeded.

4. Keep local and distributed guarantees separate

The map disappears on restart and does not coordinate separate workers. Every transport failure is conservatively marked unknown because this tiny example has no evidence that distinguishes pre-execution failure from a lost response.

A production workflow needs durable operation state, atomic claims, current authorization, and the receiving service’s idempotency or reconciliation contract. It also needs bounded retention; an unbounded map would grow indefinitely. The retry guide explains these decisions before real delivery is involved.