An idempotency key for payments
A client didn't get a reply to "charge $100" because of a timeout and retries. To avoid charging twice, such APIs accept an Idempotency-Key header. Write withIdempotency(handler, { ttlMs, now }) that returns (key, payload) => Promise.
- The first call with a key runs handler(payload); concurrent calls with the same key while it runs get the same promise.
- A successful result is remembered for ttlMs and returned without calling the handler again.
- An error isn't remembered: the next call with the key tries again.
- The same key with a different payload (compared with JSON.stringify) rejects with Idempotency key reused with a different payload.
Ctrl+Enter runs the tests. Tab indents; to leave the editor with the keyboard, press Esc and then Tab. Your code is saved in this browser.
Tests (6)
let t = 0; const charge = fn(async (p) => ({ id: 'ch_1', amount: p.amount })); const pay = withIdempotency(charge, { ttlMs: 60_000, now: () => t }); const first = await pay('key-1', { amount: 100 }); const second = await pay('key-1', { amount: 100 }); expect(second).toEqual(first); expect(charge).toHaveBeenCalledTimes(1);
let t = 0; const charge = fn(async (p) => { await wait(20); return p.amount; }); const pay = withIdempotency(charge, { ttlMs: 60_000, now: () => t }); const results = await Promise.all([pay('k', { amount: 5 }), pay('k', { amount: 5 }), pay('k', { amount: 5 })]); expect(results).toEqual([5, 5, 5]); expect(charge).toHaveBeenCalledTimes(1);
let t = 0; const pay = withIdempotency(async (p) => p.amount, { ttlMs: 60_000, now: () => t }); await pay('k', { amount: 100 }); await expect(pay('k', { amount: 999 })).rejects.toThrow('different payload');
let t = 0; let calls = 0; const pay = withIdempotency(async () => { calls++; if (calls === 1) throw new Error('gateway timeout'); return 'ok'; }, { ttlMs: 60_000, now: () => t }); await expect(pay('k', {})).rejects.toThrow('gateway timeout'); expect(await pay('k', {})).toBe('ok'); expect(calls).toBe(2);
let t = 0; const charge = fn(async () => 'ok'); const pay = withIdempotency(charge, { ttlMs: 1000, now: () => t }); await pay('k', {}); t = 999; await pay('k', {}); expect(charge).toHaveBeenCalledTimes(1); t = 1000; await pay('k', {}); expect(charge).toHaveBeenCalledTimes(2);
let t = 0; const charge = fn(async (p) => p.n); const pay = withIdempotency(charge, { ttlMs: 1000, now: () => t }); expect(await pay('a', { n: 1 })).toBe(1); expect(await pay('b', { n: 2 })).toBe(2); expect(charge).toHaveBeenCalledTimes(2);