# How to derive an idempotency key from a business identifier

> Hash the fields that identify a write as RFC 8785 canonical JSON, so any Node or Python process that retries the same event sends the same Idempotency-Key.

Source: https://voxgig.com/howto/derive-idempotency-keys-from-business-identifiers

- Audience: api-consumer
- Level: intermediate
- Languages: typescript, python
- Verified: 2026-11-30
- Published: 2026-11-30

## Short answer

Pick the fields that identify the write, such as tenant, order id, action, and refund number. Serialize them as RFC 8785 canonical JSON, and send the SHA-256 of those bytes as the Idempotency-Key. Use `canonicalize` in Node and `rfc8785` in Python, and the two produce byte-identical keys whatever the field order. Leave timestamps and attempt counters out of the input, or every retry becomes a different write.

---
## You will need

Node 22 or later, Python 3.12 or later, and an API that deduplicates on `Idempotency-Key`.
Verified 2026-11-30 against Node 22.23.5 and Python 3.12. `npm ci` in the sample directory
installs `canonicalize` and `uuid`, and its `postinstall` script installs `rfc8785` from PyPI
into a local directory, checked against a pinned hash. The header is specified by
[draft-ietf-httpapi-idempotency-key-header-09](https://datatracker.ietf.org/doc/draft-ietf-httpapi-idempotency-key-header/),
an Internet-Draft, not an RFC.[^1]

## Approaches compared

| Approach | When it fits | What it costs you | When to pick something else |
| --- | --- | --- | --- |
| [Random UUID persisted in an outbox](https://microservices.io/patterns/data/transactional-outbox.html) | One service owns the write and already commits to a database before sending | A table, a relay, and a transaction around every send; two consumers of one event still mint two keys | The same event can reach processes that share no database |
| [SHA-256 over RFC 8785 canonical JSON](https://www.rfc-editor.org/rfc/rfc8785.html#section-3.2.3) | Retries come from any process or language, and the event carries stable identifiers | A wrong field list silently merges distinct writes or splits one write into several | The event has no identifier that is stable across retries |
| [UUID v5 namespace hash](https://www.rfc-editor.org/rfc/rfc9562.html#section-5.5) | The API wants a UUID-shaped key, or you already keep a namespace UUID | SHA-1 underneath, and a name built by joining fields can collide | The API accepts any string, where a full SHA-256 digest keeps all its bits |

The outbox key never merges two writes, because it is random, but it must be stored before the
first send, and only the process that stored it can resend it. A derived key needs no storage
and survives a crashed client, at the price that the field list becomes a correctness decision.
UUID v5 is the same derivation in a UUID shape, with 122 of its 128 bits from SHA-1.[^2]

## Choose the fields that make two events the same write

The key input is an allowlist, written per action. Anything not on it, the amount, the request
time, a retry counter, stays out.

```js title="key.mjs"
// Which fields make two events the same write, per action. Everything else on the
// event (amount, timestamps, attempt counters, notes) stays out of the key.
export const IDENTITY = {
  capture: ['tenant', 'order_id'],
  refund: ['tenant', 'order_id', 'refund_no'],
}

export function identity(event) {
  const fields = Object.hasOwn(IDENTITY, event.action) ? IDENTITY[event.action] : null
  if (!fields) throw new Error(`no identity defined for action ${JSON.stringify(event.action)}`)
  const id = { scope: 'payments/v1', action: event.action }
  for (const f of fields) {
    const v = event[f]
    // Strings, or integers JSON carries exactly in every language. A float or an id
    // past 2^53 would canonicalize differently, or not at all, on the other side.
    if (typeof v !== 'string' && !Number.isSafeInteger(v)) {
      throw new Error(`identity field ${f} must be a string or a safe integer, got ${JSON.stringify(v)}`)
    }
    id[f] = v
  }
  return id
}

// RFC 8785 canonical JSON, then SHA-256, as lowercase hex behind a short prefix.
export function deriveKey(event) {
  const canonical = canonicalize(identity(event))
  return 'ik1_' + createHash('sha256').update(canonical, 'utf8').digest('hex')
}
```

`refund_no` is on the refund list because one order can have several refunds. The business
system numbers them, so the number is stable across retries, unlike a timestamp. The `scope`
field names the API and its version, so the same order id used for another kind of write never
produces the same key.

The amount is left out on purpose. A retry that changes the amount of refund 2 is a bug, and a
server that compares payloads should refuse it. Stripe's
[idempotent requests documentation](https://docs.stripe.com/api/idempotent_requests) says its
layer compares incoming parameters with those of the original request and errors when they differ.

## Write the same function in Python

[`rfc8785`](https://pypi.org/project/rfc8785/), a pure-Python implementation, does what
[`canonicalize`](https://github.com/erdtman/canonicalize) does in Node: sorted keys, no
whitespace, and the number and string rules of RFC 8785.

```python title="key.py"
def identity(event):
    fields = IDENTITY.get(event.get("action")) if isinstance(event.get("action"), str) else None
    if fields is None:
        raise ValueError(f"no identity defined for action {event.get('action')!r}")
    ident = {"scope": "payments/v1", "action": event["action"]}
    for f in fields:
        v = event.get(f)
        ok = isinstance(v, str) or (type(v) is int and -SAFE <= v <= SAFE)
        if not ok:
            raise ValueError(f"identity field {f} must be a string or a safe integer, got {v!r}")
        ident[f] = v
    return ident


def derive_key(event):
    canonical = rfc8785.dumps(identity(event))
    return "ik1_" + hashlib.sha256(canonical).hexdigest()
```

`type(v) is int` refuses `True`, which Python counts as an integer and JavaScript does not. The
range check matches `Number.isSafeInteger`, and `rfc8785` itself raises `IntegerDomainError`
past that range.

## Derive one key in two processes

`crosscheck.mjs` sends one refund to `node derive.mjs` and the same refund, fields reordered and
timestamp later, to `python3 key.py`, each in its own process.

```bash
node crosscheck.mjs
```

```text output
node   ik1_a1d0780ed3d4017c5b5e8c97a87cfc4ee627c86350760c429755ae3bddd36abc
python ik1_a1d0780ed3d4017c5b5e8c97a87cfc4ee627c86350760c429755ae3bddd36abc
identical: true
uuid v5 node f5ff5bb2-8a60-52e0-b556-13498224b9de  python f5ff5bb2-8a60-52e0-b556-13498224b9de  identical: true
python json.dumps(sort_keys=True) instead: identical: false
  it hashed {"action":"refund","order_id":"ord_1042","refund_no":2,"scope":"payments/v1","tenant":"caf\u00e9-z\u00fcrich"}

refund_no    -> 3                        key changes
order_id     -> "ord_1043"               key changes
tenant       -> "cafe-zurich"            key changes
amount       -> 700                      key unchanged
requested_at -> "2026-11-30T09:00:00Z"   key unchanged
```

The fifth line is the control. Python's `json.dumps` with sorted keys looks canonical, but it
escapes `é` as `\u00e9`, while RFC 8785 writes the character as UTF-8. The two digests differ for
any tenant name outside ASCII, which a test of ASCII-only fixtures never shows.

The UUID v5 keys agree too, because both sides use the canonical JSON as the name.
[`uuid.uuid5`](https://docs.python.org/3.12/library/uuid.html#uuid.uuid5) in Python and
[`v5`](https://github.com/uuidjs/uuid) in the `uuid` package both encode the name as UTF-8.

## Check it worked

Run the tests. They spawn both languages for every comparison, so a pass means two processes
agreed, not one function with itself.

```bash
node --test key.test.mjs
```

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

`# pass 7` covers the byte comparison, each identifying field changing the key in both
languages, and both languages refusing `2.5`, `2 ** 53`, a missing field, and an action named
`constructor`. It also checks the keyed variant below and the counts the pitfall and outbox
scripts print.

## When it goes wrong

Every retry creates a record. The key input included something that changes per attempt:

```bash
node pitfall.mjs
```

```text output
whole event, three attempts of one refund
  keys: ik1_984a4e9a56c8 ik1_4486a23d47f0 ik1_7ade931ff0f4
  records created: 3
identity without refund_no, refunds 2 and 3
  records created: 1, second request replayed: true (rf_1)
uuid v5 over "tenant:order_id:action"
  acme:eu + ord_7 and acme + eu:ord_7 share a key: true
  canonical JSON keeps them apart: true
```

Hashing the whole event put `requested_at` and `attempt` into the key, so three attempts made
three refunds. Hash the allowlist, never the payload.

The second refund on an order vanished. The identity left out `refund_no`, so refund 3 reused
refund 2's key and the stand-in replayed the first record. The client got a success response,
so no error marks the lost refund. List what distinguishes two legitimate writes before you
list anything else.

Two tenants share keys. Joining fields with `:` lets `acme:eu` plus `ord_7` read the same as
`acme` plus `eu:ord_7`. Canonical JSON quotes each value, so the boundary cannot move.

## When not to do this

Do not derive keys when the event has no stable identifier. A form submission with no client
id, or a message whose id is assigned per delivery, gives the hash nothing that survives a retry.
Mint a random key and store it in an outbox row, in the same transaction as the write.

```bash
python3 outbox.py
```

```text output
random key read from the outbox row, relay crashes after sending and restarts
  records created: 1
random key minted at send time, relay crashes after sending and restarts
  records created: 2
random key, one event delivered to two consumers with separate outboxes
  records created: 2
derived key, one event delivered to two consumers with separate outboxes
  records created: 1
```

Do not send a plain hash of identifiers to an API that does not scope keys per account. Section 5
of [draft 09](https://www.ietf.org/archive/id/draft-ietf-httpapi-idempotency-key-header-09.html#section-5)
warns about guessable keys, and anyone who knows the order id can compute this one. Use the
keyed variant there: `deriveKeyHmac` in `key.mjs` and `derive_key_hmac` in `key.py` take a
secret your processes share, and a test checks that the two languages agree.

## Related how-tos

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

- [Make queue consumer writes safe under redelivery](/howto/queue-consumer-writes-under-at-least-once)

- [Inject a deterministic idempotency key generator for tests](/howto/inject-a-key-generator-into-sdk-idempotency)

- [Make PUT and DELETE safe to retry without a key](/howto/retry-put-and-delete-safely-without-a-key)

- [Verify HMAC-signed requests and reject replays](/howto/verify-hmac-signed-requests-and-reject-replays)

## Last verified

Verified 2026-11-30 against Node 22.23.5, Python 3.12, `canonicalize` 5.1.0, `uuid` 14.0.3 and
`rfc8785` 0.1.4. Every output block is what the command preceding it printed. The API is an
in-process stand-in that honors the header, so every request stayed inside the process.

[^1]: Revision 09 of the draft, dated November 21, 2026, recommends a UUID or a similar random
identifier. [Section 2.2](https://www.ietf.org/archive/id/draft-ietf-httpapi-idempotency-key-header-09.html#section-2.2)
also gives an example key built from a tenant and a request number, `"tenant-4821:1007"`. That
is a business identifier by any definition. The section calls such keys predictable and points
to its security section for how a resource keeps them from being guessed.

[^2]: UUID version 5 hashes with SHA-1 and keeps the first 128 bits.
[RFC 9562](https://www.rfc-editor.org/rfc/rfc9562.html#section-5.5) anticipates organizations
that will not use SHA-1, and says a name-based UUID built on SHA-256 MUST NOT use version 5. It
goes in the version 8 space instead, which the same RFC sets aside for experimental or
vendor-specific use and whose uniqueness, it adds, MUST NOT be assumed.