# Idempotency-Key in NestJS and Postgres for safe POST retries

> Send an Idempotency-Key, keep it under a unique index in Postgres and return the first result on a retry. Here is the NestJS code, the race and the tests.

- Author: toyfox
- Publisher: toyfox (https://toyfox.app)
- Published: 2026-12-03
- Language: en (also in ar, es, fa, sv)
- Category: programming; tags: nestjs, postgresql, api-design, idempotency
- Canonical URL: https://toyfox.app/en/blog/idempotency-key-rest-api-nestjs-postgres/
- Cite as: toyfox, "Idempotency-Key in NestJS and Postgres for safe POST retries", toyfox blog, 2026-12-03, https://toyfox.app/en/blog/idempotency-key-rest-api-nestjs-postgres/

Someone taps "Place order" on a phone in a train. The spinner turns for ten seconds, the app says the network failed, and they tap again. On the server there are now two orders, two confirmation emails and two lines in the usage meter. The first request had worked all along. Only its response got lost in a tunnel.

What should the client have done differently? Should an app never retry a `POST`? And how can a server tell a retry of the same intent from a genuinely new order with the same content, especially when both copies arrive a few milliseconds apart?

The answer most APIs settled on, Stripe for years and now an IETF draft, is an idempotency key. The client sends an `Idempotency-Key` header with a random value, the server stores that key under a unique index next to the order it created, and every retry with the same key gets the first order back instead of a new one.

This guide shows how we built it in one of our projects with NestJS, Prisma and PostgreSQL. It covers where the key lives, what happens on a plain retry, what happens when two requests with the same key race, which side effects must not run twice, and the one case we deliberately left out, the same key with a different body, with the code to add it.

## Why a retried POST creates duplicates

HTTP already has a word for "safe to repeat". [RFC 9110](https://www.rfc-editor.org/rfc/rfc9110#name-idempotent-methods) calls a method idempotent when sending the same request twice has the same effect on the server as sending it once, and it gives that property to `PUT`, `DELETE` and the safe methods such as `GET`. `POST` and `PATCH` do not have it. Two `POST /orders` with the same body are two orders, as far as HTTP is concerned.

The real problem is the timeout. When the client gets no answer, it cannot know which of three things happened. The request may never have reached the server, the server may have failed half way, or the server finished and the response was lost on the way back. Only the first two are safe to retry blindly. Mobile networks, load balancers with idle timeouts and a user who taps the button twice all produce the third case on a normal day.

So the client needs a way to say "this is the same intent as before", and the server needs a way to recognise it. That is what the idempotency key is.

## How the Idempotency-Key header works

The pattern is old, Stripe has used it for years, and the IETF httpapi working group is turning it into a standard called [The Idempotency-Key HTTP Header Field](https://datatracker.ietf.org/doc/draft-ietf-httpapi-idempotency-key-header/). At the time of writing it is draft 09, updated 2026-11-21 and still an Internet-Draft, not an RFC. The idea fits in four sentences. The client generates a unique key, and the draft recommends a UUID. It sends the key with the request in the header. The server remembers the key together with the outcome. A later request with the same key gets the same outcome instead of a second execution.

```http
POST /orders HTTP/1.1
Content-Type: application/json
Idempotency-Key: "8e03978e-40d5-43e8-bc93-6894a57f9324"

{ "sku": "A-1", "qty": 2 }
```

The draft defines the header as a Structured Field string, which is why the example quotes the value. Many APIs, Stripe included, accept the bare value too. Decide which you accept and document it.

The interesting part is what the server answers in each situation. Here is what the draft recommends next to what [Stripe documents](https://docs.stripe.com/api/idempotent_requests).

| Situation | IETF draft 09 | Stripe API v1 |
|---|---|---|
| Key required but missing | `400 Bad Request` | key is optional |
| Same key, same body, first request finished | a response consistent with the completed request | the saved status code and body, header `Idempotent-Replayed: true` |
| Same key, different body | `422 Unprocessable Content` | an error saying the request does not match the original |
| Same key, first request still running | `409 Conflict` | `409`, wait and retry with the same key |
| How long a key is kept | the server defines and documents it | at least 24 hours |

Two details from Stripe's docs are worth copying. Results are saved only after the endpoint starts executing, so a request that fails validation leaves nothing behind and a corrected retry with the same key works. And keys are scoped. Stripe keys belong to an account, and two customers who happen to pick the same string never collide.

## Where to store the key in Postgres

There are two common designs. One is a separate `idempotency_keys` table that records the key, a hash of the request, a state such as in progress or done, and the saved response. That is what you need when one mechanism has to cover many endpoints, or when the operation calls outside systems and may run for seconds.

The other is to put the key on the row the request creates. Our endpoint creates exactly one row, plus its children in the same transaction, so we chose this. It needs a nullable column and a unique index over the owner and the key.

```prisma
model Order {
  id             String  @id @default(uuid())
  accountId      String  @map("account_id")
  /// Idempotency-Key of the create call: a retry with the same key returns this order
  idempotencyKey String? @map("idempotency_key") @db.VarChar(100)
  // ...the order's own fields

  @@unique([accountId, idempotencyKey])
  @@map("orders")
}
```

Prisma turns that into a migration like this one.

```sql
ALTER TABLE "orders" ADD COLUMN "idempotency_key" VARCHAR(100);

CREATE UNIQUE INDEX "orders_account_id_idempotency_key_key"
  ON "orders" ("account_id", "idempotency_key");
```

Three properties of this index do the work. The key is unique per account, not globally, so tenants cannot collide or probe each other's keys. Requests without a key store `NULL`, and in PostgreSQL [null values in a unique index are not considered equal](https://www.postgresql.org/docs/current/indexes-unique.html) by default, so any number of keyless orders fit. And the key lives as long as the order lives, so there is no expiry job to write. The price is one nullable `VARCHAR(100)` column on the table, which we were happy to pay.

> If you ever want a missing key to count as a value, PostgreSQL 15 added `NULLS NOT DISTINCT` to unique indexes. Here we want the default. No key means no idempotency, not "one keyless order per account".

## Validating the header in NestJS

Before anything touches the database, the controller checks the header. We accept 1 to 100 visible ASCII characters, which covers UUIDs and any reasonable key a client invents, and fits the column. A bad key is a client bug, so it gets a `400` with its own error code instead of being silently ignored.

```ts
/** The Idempotency-Key header, checked; undefined when absent. */
function idempotencyKeyOf(header?: string): string | undefined {
  if (header === undefined) return undefined;
  if (!/^[!-~]{1,100}$/.test(header)) {
    throw new BadRequestException({
      error: 'IDEMPOTENCY_KEY_INVALID',
      message: 'Idempotency-Key must be 1 to 100 visible ASCII characters',
    });
  }
  return header;
}
```

The range `[!-~]` is every printable ASCII character from `!` at 0x21 to `~` at 0x7E, so spaces, control characters and non-ASCII letters are rejected. The key is optional in our API. If you make it required, the draft's answer for a missing key is the same `400`.

The controller then passes the key to the service and looks at one flag on the way back.

```ts
@Post()
async create(
  @Body() dto: CreateOrderDto,
  @AccountId() accountId: string,
  @Headers('idempotency-key') key?: string,
) {
  const order = await this.orders.create(accountId, dto, idempotencyKeyOf(key));
  if (order.replayed) return order;

  await this.usage.record(accountId, order.id); // metering runs once per real order
  return order;
}
```

Node lowercases incoming header names, which is why `@Headers('idempotency-key')` is written in lower case.

## Look up the key, insert, and catch the unique violation

The service has two paths to the earlier order. The fast path is a lookup before any work. If an order with this account and key already exists, return it marked as replayed. The slow path handles the race, and it is the reason the unique index matters more than the lookup.

```ts
/** The unique columns a failed insert collided with (Prisma P2002). */
const uniqueTarget = (error: unknown): string =>
  error instanceof Prisma.PrismaClientKnownRequestError && error.code === 'P2002'
    ? String(error.meta?.target ?? '')
    : '';

async create(accountId: string, dto: CreateOrderDto, idempotencyKey?: string) {
  if (idempotencyKey) {
    const earlier = await this.findByIdempotencyKey(accountId, idempotencyKey);
    if (earlier) return earlier;
  }

  // ...validation, plan limits, lookups of related rows

  const order = await this.prisma.order
    .create({ data: { accountId, idempotencyKey, ...dto }, include: ORDER_INCLUDE })
    .catch(async (error: unknown) => {
      // a concurrent call with the same key won the race
      if (idempotencyKey && uniqueTarget(error).includes('idempotency_key')) {
        const earlier = await this.findByIdempotencyKey(accountId, idempotencyKey);
        if (earlier) return earlier;
      }
      throw error;
    });
  if ('replayed' in order) return order;

  await this.invalidateCaches(order.id);
  this.mail.notify(order.id, 'created'); // the confirmation email, also once
  return order;
}

/** The order an earlier create with this Idempotency-Key made, marked as replayed. */
private async findByIdempotencyKey(accountId: string, idempotencyKey: string) {
  const earlier = await this.prisma.order.findUnique({
    where: { accountId_idempotencyKey: { accountId, idempotencyKey } },
    include: ORDER_INCLUDE,
  });
  return earlier && { ...earlier, replayed: true };
}
```

`P2002` is Prisma's error code for a unique constraint violation, and PostgreSQL itself reports SQLSTATE `23505`, `unique_violation`. We check that the violated index is the idempotency one, because the same table can have other unique columns, and a collision on one of those is a real error for the caller, not a replay.

Notice what the replay returns. It is the order as it is now, read from the database, with `replayed: true`. Stripe stores the exact first response, while we return the current state of the resource. The draft allows both, since it asks for a response "consistent with the request being completed", and for an order the current state is more useful to a client that is catching up anyway.

![A sequence diagram with three lanes, client, API and Postgres. The first POST inserts the order and its 201 is lost, and the retry with the same key finds the row and returns 201 with replayed true.](https://toyfox.app/media/blog/idempotency-key-rest-api-nestjs-postgres/flow-f8bb1ccd.svg "First request and retry. The second call never reaches the INSERT.")

### What happens when two requests with the same key race

The fast-path lookup is not enough on its own. Two requests with the same key can arrive a few milliseconds apart, after a double tap or from a client that retries too early. Both miss the lookup, and both start inserting. Without the unique index you get two orders. With it, PostgreSQL settles the race for you.

The [PostgreSQL docs on unique checks](https://www.postgresql.org/docs/current/index-unique-checks.html) describe what happens. If a conflicting row has been inserted by a transaction that has not committed yet, the second inserter waits to see whether that transaction commits. If it commits, the second insert fails with a unique violation. Our `catch` then reads the winner's row, which is now visible, and answers it as a replay. If the first transaction rolls back, the second insert simply succeeds. Either way there is exactly one order.

![The race. Two POST requests with the same key both miss the lookup, and the second INSERT waits on the unique index until the first commits, gets 23505 and answers the first order as replayed.](https://toyfox.app/media/blog/idempotency-key-rest-api-nestjs-postgres/race-744bc76f.svg "Two requests, one key. The unique index makes the second one wait, then replay.")

This is where our design differs from the draft's `409 Conflict`. A key table with an "in progress" state answers `409` because the first request may still be talking to a payment provider for seconds, and holding the second one open that long is a bad idea. In our endpoint the whole operation is one transaction of a few inserts, so the second request waits milliseconds and gets a real answer. If your operation calls outside systems, use the key table and the `409`.

## Side effects must not run twice

A replay must be invisible to everything outside the response. Look back at the controller and the service. Usage metering, the confirmation email and the cache invalidation all sit after the `replayed` check, so a retry returns the order and does nothing else. In the real project the same rule also covers an assignment step that runs after the create. The variant of the endpoint that assigns the order to someone afterwards returns early on a replay, so a retry never assigns twice.

The `replayed` flag is in the body because our clients read the body. If you want to follow Stripe, send `Idempotent-Replayed: true` as a header instead, or as well. Either way, give the client a way to know, because "your order was created" and "your order already existed" deserve different messages in some UIs.

Errors are the other half of this rule. Because we store the key only on a row that was actually inserted, a request that fails on validation, a plan limit or a missing related row leaves no trace, and a retry with the same key runs fresh. That matches Stripe's behaviour for errors that happen before execution starts. It also means a key cannot get "stuck" on a failure the client has since fixed.

## Same key with a different body and the 422 we did not build yet

Our implementation does not compare bodies. A client that reuses a key for a different order gets the first order back. The draft names this exactly, a resource without fingerprints "cannot detect a key reused with a different payload, and handles such a request as a duplicate." For our clients, which generate a UUID per order, that was an acceptable first version. It is also the case most likely to hide a client bug, so here is how to close it.

Store a fingerprint of the body with the key and compare it on a replay. The function below hashes the JSON with its object keys sorted, so the same fields in a different order give the same hash.

```ts
import { createHash } from 'node:crypto';

/** SHA-256 of a JSON body with object keys sorted, so field order does not change it. */
export function fingerprint(body: unknown): string {
  const canonical = (v: unknown): unknown =>
    Array.isArray(v) ? v.map(canonical)
    : v && typeof v === 'object'
      ? Object.fromEntries(Object.keys(v).sort().map((k) => [k, canonical((v as Record<string, unknown>)[k])]))
      : v;
  return createHash('sha256').update(JSON.stringify(canonical(body))).digest('hex');
}
```

We ran it in Node 26. `fingerprint({ sku: 'A-1', qty: 2 })` equals `fingerprint({ qty: 2, sku: 'A-1' })`, and changing `qty` to 3 gives a different hash. Add a `request_hash CHAR(64)` column next to the key, write the hash on insert, and compare in `findByIdempotencyKey` before replaying.

```ts
if (earlier && earlier.requestHash !== hash) {
  throw new UnprocessableEntityException({
    error: 'IDEMPOTENCY_KEY_REUSED',
    message: 'Idempotency-Key must not be reused with a different request body',
  });
}
```

Hash the validated DTO rather than the raw bytes, so whitespace and defaults filled in by the `ValidationPipe` do not count as a different request. Watch out for computed decimals in the body too. In JavaScript `0.1 + 0.2` serialises as `0.30000000000000004`, so a client that rebuilds a total in a slightly different way on the retry sends a different hash and gets a `422`. We explain where those digits come from in our post on [floating point in unit conversion](https://toyfox.app/en/blog/floating-point-unit-conversion-javascript/).

## Testing the retry

The end-to-end test is the part we would write first next time. It runs against a real PostgreSQL database and checks three things. The retry returns the same id with the flag, only one row exists, and a malformed key is rejected.

```ts
it('creates once per Idempotency-Key', async () => {
  const key = `order-${randomUUID()}`;
  const first = (await post('/orders').set('Idempotency-Key', key)
    .send(order({ externalReference: 'ORDER-1001' })).expect(201)).body.data;
  expect(first.replayed).toBeUndefined();

  const retry = (await post('/orders').set('Idempotency-Key', key)
    .send(order({ externalReference: 'ORDER-1001' })).expect(201)).body.data;
  expect(retry).toMatchObject({ id: first.id, replayed: true });
  expect(await prisma.order.count({ where: { externalReference: 'ORDER-1001' } })).toBe(1);

  await post('/orders').set('Idempotency-Key', 'has space').send(order()).expect(400);
});
```

Note the replay answers `201`, like the original, so a client that only checks the status code keeps working. Our suite covers the sequential retry. The race is cheap to add with `Promise.all` over two requests with one key, then the same count of one. Run it a few times, since a race test that passes once proves little.

## What the client has to do

The server side is only half. The client must create one key per user intent and reuse it for every retry of that intent. A new key on each attempt turns the whole mechanism off. In the browser and in Node, [`crypto.randomUUID()`](https://developer.mozilla.org/en-US/docs/Web/API/Crypto/randomUUID) gives a version 4 UUID.

```ts
async function createOrder(body: unknown): Promise<Response> {
  const key = crypto.randomUUID(); // one key per intent, reused by every retry
  for (let attempt = 0; ; attempt++) {
    try {
      const res = await fetch('/api/orders', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json', 'Idempotency-Key': key },
        body: JSON.stringify(body),
      });
      if ((res.status < 500 && res.status !== 409) || attempt === 3) return res;
    } catch (error) {
      if (attempt === 3) throw error; // network error: the outcome is unknown, so retry
    }
    await new Promise((resolve) => setTimeout(resolve, 2 ** attempt * 500));
  }
}
```

It retries on network errors, `5xx` and `409`, with 0.5, 1 and 2 seconds between attempts, and returns anything else to the caller. If your app queues writes while offline, store the key with the queued request, so a resend after the app restarts still carries the same key. And do not build keys from personal data such as an email address. Stripe's docs warn against that too, and a random UUID has nothing to leak.

If you take one thing from this, put a unique index under the key before you write the lookup, because the lookup only handles the polite retry and the index handles the race. Then gate every side effect on "not replayed", write the sequential test, and add the fingerprint once more than one client team talks to your API.

---

Source: https://toyfox.app/en/blog/idempotency-key-rest-api-nestjs-postgres/ (toyfox, https://toyfox.app). When you use this article, please name toyfox and link the URL above.
