# How to inject a deterministic idempotency key generator for tests

> Replace the random Idempotency-Key in SDK tests with a counting generator, then assert one generator call per operation and one key across every retried attempt.

Source: https://voxgig.com/howto/inject-a-key-generator-into-sdk-idempotency

- Audience: library-maintainer
- Level: intermediate
- Languages: typescript
- Verified: 2026-11-21
- Published: 2026-11-21

## Short answer

In an SDK generated by sdkgen, pass a counting function as `keygen` in `feature: { idempotency: { active: true, keygen } }`, with the retry feature on. Assert that it ran once for the operation and that every attempt carried its one key. Then check that a caller's key reached the server untouched and that a second operation got the next key. Kiota takes the same generator in a middleware handler, and Swagger Codegen in your own retry loop.

---
## You will need

Node 22 or later, a TypeScript SDK generated by sdkgen, and an API that honors the header, which
an [IETF draft](https://datatracker.ietf.org/doc/draft-ietf-httpapi-idempotency-key-header/)
defines. The API here is `api.json`, a Ledger API whose `POST /transfers` declares the header as
an optional parameter. A stand-in on 127.0.0.1 stores each transfer before it answers, and can
then answer 503 with `Retry-After: 0`, so a retry follows at once. The sdkgen packages ask for
Node 24 in `engines`, and npm installed them on Node 22 after `EBADENGINE` warnings.

## Approaches compared

| Approach | When it fits | What it costs you | When to pick something else |
| --- | --- | --- | --- |
| [Kiota middleware handler](https://learn.microsoft.com/en-us/openapi/kiota/middleware) | A Kiota client, where one handler ahead of the retry handler keys every POST | A handler you write and order yourself, since the generated client ignores the header parameter | You want the key rule generated with the client |
| [sdkgen idempotency `keygen` option](https://github.com/voxgig/sdkgen/blob/main/docs/reference/features.md) | A TypeScript SDK from sdkgen, with its retry feature on beside it | `keygen` takes no arguments, so a key from your own record needs a per-call key or a feature in `extend` | Your client is not generated by sdkgen |
| [stripe-node per-call `idempotencyKey`](https://docs.stripe.com/api/idempotent_requests) | You call Stripe and each test can pass its own key | A key at every call site in the test, because the client's own generator is an internal function | Your writes go to more than one API |
| [Swagger Codegen `idempotencyKey` argument](https://swagger.io/docs/open-source-tools/swagger-codegen/codegen-v3/about/) | A `typescript-fetch` client, where the header parameter becomes a typed argument | No retry and no generator in the client, so your loop owns both | You want retries without writing the loop |
| [vitest `vi.mock` of a `uuid` module](https://vitest.dev/api/vi.html#vi-mock) | A hand-written client that imports its key function from a module | A module-wide mock, hoisted ahead of imports, that cannot replace `require` calls or `Math.random` | The client takes the generator as an option |

Voxgig maintains sdkgen. This page is about its `keygen` option, and four other ways to make
the same assertion sit beside it.

An option is narrower than a module mock, because the test hands its generator to one client
and the rest of the process keeps its own. Each option costs something on the call path. sdkgen
hands its generator nothing, and Kiota leaves the handler and its place in the chain to you.
Swagger Codegen leaves you the retry loop as well, and stripe-node needs a key at each call.

## Hand the feature a counting generator

`generate.sh` scaffolds an sdkgen project from `api.json` with two features, generates the
TypeScript SDK, and compiles it into `generated/`.

```bash title="generate.sh"
npx --yes @voxgig/create-sdkgen@0.31.9 ledger --def api.json --target ts --feature idempotency --feature retry
(cd ledger-sdk/.sdk && npm run generate)
(cd ledger-sdk/ts && npm install --no-audit --no-fund && npm run build)
```

The feature's model file declares the option. The scaffold copies it to
`.sdk/model/feature/idempotency.aontu`, where `keygen` is a function the options accept.

```aontu title="model/idempotency.aontu"
main: kit: feature: idempotency: config: optspec: {
  # supplies the idempotency key
  keygen: '`$FUNCTION`'
}
```

The test's generator returns `test-1`, `test-2` and so on, and counts its calls. `keygen.mjs`
builds the client with retry on, and gives the retry feature a `sleep` that returns at once, so
no attempt waits.

```js title="keys.mjs"
export function sequence(prefix) {
  let n = 0
  const next = () => `${prefix}-${++n}`
  Object.defineProperty(next, 'calls', { get: () => n })
  return next
}
```

```js title="keygen.mjs"
export const ledger = (base, keygen) =>
  new LedgerSDK({
    base,
    feature: {
      retry: { active: true, sleep: () => {} },
      idempotency: { active: true, keygen },
    },
  })
```

```bash
node keygen.mjs
```

```text output
sdkgen, retry and idempotency on, keygen: sequence('test')
  call                                  attempts  keys sent           generator calls
  create, answered 503 twice            3         test-1              1
  create, a second transfer             1         test-2              1
  create, idempotency_key: 'payout-17'  1         payout-17           0
  list                                  1         none                0

transfers stored: 3, generator calls in all: 2
```

The first create took three attempts, and the server saw `test-1` on all three. The feature
calls `keygen` in its `PreRequest` hook, once for each operation, and the retry feature then
repeats the finished request. A key the caller passes as `idempotency_key`, the name the model
gives the document's header parameter, is sent as it is, and the generator is not called. A read
gets no key.

`keygen` is called with no arguments, so it cannot see which transfer it is keying. A key
derived from your own record goes in per call, as `idempotency_key`, or comes from a feature of
your own in `extend`. `record-key.mjs` places one `__before__` the idempotency feature, and its
`PreRequest` reads the record from `ctx.reqdata`, so the idempotency feature finds a key and
leaves it. Without `__before__`, an extended feature runs after a generated key is already set.
`@voxgig/sdkgen` 4.45.0 ships the feature's TypeScript template unchanged, byte for byte.

## Check it worked

The test reads what reached the server, because the client reports one success either way.

```js title="keygen.test.mjs"
test('sdkgen: the generator runs once for an operation, and all three attempts carry its one key', async (t) => {
  const server = await startServer()
  t.after(() => server.close())
  const gen = recording('test')
  const client = ledger(server.url, gen.keygen)
  server.state.failNext = 2

  const made = await client.Transfer().create(RENT)

  assert.equal(gen.calls, 1, 'one generator call for the operation')
  assert.deepEqual(keysSent(server), ['test-1', 'test-1', 'test-1'], 'three attempts, one key')
```

```bash
node --test keygen.test.mjs
```

```text output
1..15
# tests 15
# suites 0
# pass 15
# fail 0
# cancelled 0
# skipped 0
# todo 0
```

Other tests in the file assert `test-2` on a second transfer and `payout-17` on a caller's key
with zero generator calls. They also assert `acc_1:500` from the record through `extend`, and a
24-character hex key on every attempt when no `keygen` is passed.

## Give Kiota and Swagger Codegen the same generator

Neither client has an idempotency option, and `inspect.mjs` counts the words in the three
committed trees.

```bash
node inspect.mjs
```

```text output
mentions in each committed client, case ignored
  tree        files  retry        idempotency  keygen
  generated   52     33           24           6
  kiota       4      0            0            0
  swagger     3      0            15           0
```

Kiota's generated `post` takes no argument for the header, and its retry lives in the runtime
package's `RetryHandler`. [Kiota's middleware page](https://learn.microsoft.com/en-us/openapi/kiota/middleware)
adds a custom handler with `unshift`, ahead of the defaults. That place keeps one key per call,
because the retry handler repeats only the handlers after it.[^1]

```js title="kiota.mjs"
export class IdempotencyKeyHandler {
  constructor(keygen, methods = ['POST']) {
    this.keygen = keygen
    this.methods = methods
  }

  execute(url, init, options) {
    const headers = (init.headers ??= {})
    const has = Object.keys(headers).some((name) => name.toLowerCase() === 'idempotency-key')
    if (this.methods.includes(init.method) && !has) headers['Idempotency-Key'] = this.keygen()
    return this.next.execute(url, init, options)
  }
}
```

A caller's own key goes in the request configuration's `headers`, as
[Kiota's request headers page](https://learn.microsoft.com/en-us/openapi/kiota/query-parameters-request-headers)
shows. Swagger Codegen turns the header parameter into an argument, and its `typescript-fetch`
client has no retry, so the generator belongs in your loop, called before the first attempt.

```js title="swagger/api.js"
            if (idempotencyKey !== undefined && idempotencyKey !== null) {
                localVarHeaderParameter['Idempotency-Key'] = String(idempotencyKey);
            }
```

```bash
node generators.mjs
```

```text output
Kiota, IdempotencyKeyHandler ahead of the default RetryHandler
  call                                  attempts  keys sent           generator calls
  post, answered 503 twice              3         test-1              1
  post, a second transfer               1         test-2              1
  post, headers: 'payout-17'            1         payout-17           0
  get                                   1         none                0
  transfers stored: 3

Swagger Codegen, createTransfer() in swagger.mjs around the generated method
  call                                  attempts  keys sent           generator calls
  createTransfer, answered 503 twice    3         test-1              1
  createTransfer, a second transfer     1         test-2              1
  createTransfer, key: 'payout-17'      1         payout-17           0
  listTransfers                         1         none                0
  transfers stored: 3
```

Both tables match the sdkgen one. Kiota's handler is a dozen lines that apply to every POST
without regenerating anything. The Swagger Codegen loop is code you can read end to end.

## When it goes wrong

A generator that returns one value gives every write the same key, so unrelated writes replay
each other. The draft says a key must not be reused with a different payload,[^2] and the stand-in
answers that with 422. The same payload twice is worse.

```bash
node pitfall.mjs
```

```text output
sdkgen with keygen: () => 'test-key', three transfers
  create acc_1 500        resolved tr_1
  create acc_2 700        rejected 422
  create acc_1 500        resolved tr_1
  transfers stored: 1, replays served: 1

one transfer answered 503 twice, checked two ways
  client                                  weak check  strong check  transfers stored
  createTransfer, key before the loop     pass        pass          1
  createTransferKeyPerAttempt             pass        fail          3
```

The second rent payment resolved with the first one's id, and only one was stored. Return a new
value on every call.

The weak check asks whether each attempt carried a key the generator issued. It passes a loop
that calls the generator on every attempt, which stored three transfers. Assert one distinct key
across the attempts and one generator call, as the strong check does.

A key set in the client-wide `headers` option reaches every write, and the feature never replaces
it, so a second transfer with the same body comes back as a replay of the first. Pass `keygen`,
not a header. In Kiota, a handler pushed after the default chain never runs,
because `CustomFetchHandler` ends the chain without calling the next one; the test file covers
both.

## When not to do this

Do not ship a counting generator to production. The draft recommends a UUID or a similarly random
identifier, and `test-1` from two processes is the same key. Pass `randomUUID` from
[`node:crypto`](https://nodejs.org/api/crypto.html#cryptorandomuuidoptions) outside tests.

Do not expect sdkgen's `keygen` to derive a key from the record. It receives no arguments.
Pass `idempotency_key` on the call, or derive the key in a feature placed before the idempotency
feature, when the key must be yours.

Do not move to sdkgen for this option alone. If your client comes from Kiota, the handler in `kiota.mjs`
gives the same four assertions without a second generator. Swagger Codegen is the better fit when
you want a retry loop you can read line by line, since its client leaves the loop to you.

Do not mock a `uuid` module when the client takes the generator as an option. Vitest hoists
`vi.mock` ahead of every import, so the whole file sees the mock, and sdkgen's default key comes
from `Math.random`, which no module mock reaches.[^3]

## Related how-tos

- [Add an Idempotency-Key header to every POST from a client](/howto/add-idempotency-key-to-every-post-request)

- [Test a backoff schedule with a fake clock](/howto/test-a-backoff-schedule-with-a-fake-clock)

- [Run an in-memory mock of your API inside SDK tests](/howto/run-an-in-memory-mock-inside-sdk-tests)

- [Mock a generated SDK in your application tests](/howto/mock-a-generated-sdk-in-application-tests)

- [Decide which status codes an SDK should retry](/howto/decide-which-status-codes-an-sdk-retries)

## Last verified

Verified 2026-11-21 against Node 22.23.5, `@voxgig/create-sdkgen` 0.31.9, `@voxgig/sdkgen`
4.44.3, Kiota 1.39.0 with its runtime packages at 1.0.0-preview.113, and Swagger Codegen 3.0.85
on OpenJDK 21. Every output block is what the command preceding it printed. All three generators
ran once on `api.json` and their compiled output is committed, because the gate has neither
Java nor the Kiota binary. stripe-node and Vitest were not run; their rows come from their
documentation, and stripe-node's from its source as well.

[^1]: Kiota's middleware page says its Retry handler acts on a 429 or a 503. The
[TypeScript source](https://github.com/microsoft/kiota-typescript/blob/main/packages/http/fetch/src/middlewares/retryHandler.ts)
lists 504 as well, and sets a `Retry-Attempt` header on each repeat, counting from one. The
Idempotency-Key draft does not mention that header, so a server reading both can tell a retry
from a first attempt by two different means.

[^2]: Section 2.2 of
[revision 09](https://www.ietf.org/archive/id/draft-ietf-httpapi-idempotency-key-header-09.txt),
dated November 21, 2026, says the key must be unique and must not be reused with a different
payload. It calls the key opaque, lets a resource define what makes one unique, and offers
`"tenant-4821:1007"` as a key that is predictable by design. In a test the resource is the
stand-in, which forgets every key when it closes, so `test-1` is unique once per server.

[^3]: Vitest's [API page](https://vitest.dev/api/vi.html#vi-mock) says `vi.mock` works only for
modules imported with the `import` keyword and does not work with `require`. The SDK committed
here is compiled to CommonJS, which loads every one of its modules with `require`.