AI & ML

How to Add Idempotency Keys to a Node.js API with PostgreSQL

· 5 min read
Community Article
Community articles are authored by SitePoint Premium contributors. Content is screened before publication, and SitePoint reserves the right to moderate or remove articles that violate our guidelines. Views expressed are those of the authors and do not necessarily reflect those of SitePoint.

How to Add Idempotency Keys to a Node.js API with PostgreSQL

VP
Vasyl Popovych
Published in
·Updated:

The AI briefing for Developers

Stay up to date with AI tools, model releases, and developer workflows that matter.

Weekly. Free. One click to leave.

Share this article

How to Add Idempotency Keys to a Node.js API with PostgreSQL
SitePoint Premium
Stay Relevant and Grow Your Career in Tech
  • Premium Results
  • Publish articles on SitePoint
  • Daily curated jobs
  • Learning Paths
  • Discounts to dev tools
Start Free Trial

7 Day Free Trial. Cancel Anytime.

A mobile app sends POST /orders. The server creates the order, but the response is lost when the phone switches from Wi-Fi to 4G. The app sees a timeout and retries. Now the customer has two orders, and your support team has a refund to process.

Retrying is the right thing for a client to do. The problem is that POST is not idempotent: RFC 9110 defines GET, PUT and DELETE as idempotent methods, but not POST or PATCH. Repeating a POST can repeat its side effects.

An idempotency key fixes this. The client generates a unique key for each logical operation and sends it with every attempt. The server does the work once, stores the response against the key, and returns the stored response for any retry. The IETF HTTPAPI working group is standardizing this pattern as the Idempotency-Key HTTP header field, and this tutorial follows its recommendations.

We'll build it with Node.js, Express 5 and PostgreSQL. By the end you'll have a table that stores keys, a function that safely claims a key under concurrent requests, an Express route that replays stored responses, and a client that retries without creating duplicates.

What the server has to handle

The client's job is simple: generate a key, usually a UUID, and send the same key on every retry of the same operation. The draft defines the header value as a quoted string:

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

{"productId": "sku_123", "quantity": 2}

The server's job is harder, because every request falls into one of five cases:

  1. The key is missing or malformed. Reject the request with 400 Bad Request, at least on endpoints where duplicates would cause damage.
  2. The key is new. Do the work, store the response with the key, and return it.
  3. The key was already used for the same request, and that request finished. Return the stored response without doing the work again.
  4. The key was already used for a different request. The client reused a key by mistake. The draft recommends 422 Unprocessable Content, and the original result is not returned.
  5. The key is in use by a request that hasn't finished yet. This happens when a client retries before the first attempt completes. The draft recommends 409 Conflict, so the client can wait and try again.

To tell case 3 from case 4, the server stores a fingerprint of the request alongside the key. A matching fingerprint means a genuine retry; a different one means key reuse. Case 5 is the one most implementations get wrong, because it only shows up under concurrency. A database constraint handles it for us.

Step 1: Store keys in PostgreSQL

Create a project and install the two dependencies:

mkdir idempotent-api && cd idempotent-api
npm init -y
npm pkg set type=module
npm install express@5 pg

The key table records who sent the key, the request fingerprint, whether the work has finished, and the response to replay:

CREATE TABLE idempotency_keys (
  client_id           text        NOT NULL,
  idempotency_key     text        NOT NULL,
  request_fingerprint text        NOT NULL,
  status              text        NOT NULL
                      CHECK (status IN ('in_progress', 'completed')),
  response_status     integer,
  response_body       jsonb,
  locked_until        timestamptz NOT NULL,
  created_at          timestamptz NOT NULL DEFAULT now(),
  completed_at        timestamptz,
  PRIMARY KEY (client_id, idempotency_key)
);

CREATE INDEX idempotency_keys_created_at_idx
  ON idempotency_keys (created_at);

CREATE TABLE orders (
  id         bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
  client_id  text        NOT NULL,
  product_id text        NOT NULL,
  quantity   integer     NOT NULL CHECK (quantity > 0),
  created_at timestamptz NOT NULL DEFAULT now()
);

Two details matter here. The primary key includes client_id, so keys are scoped per client: two customers who happen to generate the same value can't see each other's responses. And locked_until lets the server recover a key whose request crashed halfway, which we'll use in Step 3.

Step 2: Read the header and fingerprint the request

The draft defines the header value as a structured field string, which means it arrives wrapped in double quotes. Many clients send it without quotes, so the parser below accepts both and limits the characters and length it will store:

// idempotency-key.js
const KEY_PATTERN = /^[A-Za-z0-9._:-]{8,255}$/;

export function readIdempotencyKey(headerValue) {
  if (typeof headerValue !== "string") return null;

  const raw = headerValue.trim();
  const value =
    raw.length >= 2 && raw.startsWith('"') && raw.endsWith('"')
      ? raw.slice(1, -1)
      : raw;

  return KEY_PATTERN.test(value) ? value : null;
}

The fingerprint has to be identical for identical requests, even if a client serializes the JSON body with its properties in a different order. Sorting object keys before hashing takes care of that. The hash uses SHA-256 from Node's built-in crypto module:

// fingerprint.js
import { createHash } from "node:crypto";

function canonicalize(value) {
  if (Array.isArray(value)) {
    return `[${value.map(canonicalize).join(",")}]`;
  }
  if (value !== null && typeof value === "object") {
    const keys = Object.keys(value).sort();
    return `{${keys
      .map((key) => `${JSON.stringify(key)}:${canonicalize(value[key])}`)
      .join(",")}}`;
  }
  return JSON.stringify(value);
}

export function fingerprintRequest(method, path, body) {
  return createHash("sha256")
    .update(`${method} ${path}\n${canonicalize(body ?? null)}`)
    .digest("hex");
}

Including the method and path means a key reused on a different endpoint counts as a mismatch, not as a retry.

Step 3: Claim the key

The tempting approach is to SELECT the key, and insert it if nothing comes back. Under concurrency that fails: two retries arriving a few milliseconds apart both see no row, and both do the work.

Instead, let the primary key decide. INSERT ... ON CONFLICT DO NOTHING either inserts the row or does nothing, atomically, even across many application processes. The PostgreSQL INSERT documentation describes this behavior in detail. If the insert returns a row, this request owns the key. If not, we read the existing row and decide which case we're in:

// idempotency-store.js
const LOCK_SECONDS = 30;

export async function claimKey(pool, { clientId, key, fingerprint }) {
  const inserted = await pool.query(
    `INSERT INTO idempotency_keys
       (client_id, idempotency_key, request_fingerprint, status, locked_until)
     VALUES ($1, $2, $3, 'in_progress', now() + ($4::int * interval '1 second'))
     ON CONFLICT (client_id, idempotency_key) DO NOTHING
     RETURNING idempotency_key`,
    [clientId, key, fingerprint, LOCK_SECONDS]
  );
  if (inserted.rowCount === 1) return { state: "claimed" };

  const { rows } = await pool.query(
    `SELECT request_fingerprint, status, response_status, response_body
     FROM idempotency_keys
     WHERE client_id = $1 AND idempotency_key = $2`,
    [clientId, key]
  );
  const existing = rows[0];

  if (!existing) return { state: "in_progress" };
  if (existing.request_fingerprint !== fingerprint) return { state: "mismatch" };
  if (existing.status === "completed") {
    return {
      state: "replay",
      status: existing.response_status,
      body: existing.response_body,
    };
  }

  // Still in progress. Take the key over only if its lock has expired,
  // which means the request that claimed it crashed or timed out.
  const takeover = await pool.query(
    `UPDATE idempotency_keys
     SET locked_until = now() + ($3::int * interval '1 second')
     WHERE client_id = $1 AND idempotency_key = $2
       AND status = 'in_progress' AND locked_until < now()
     RETURNING idempotency_key`,
    [clientId, key, LOCK_SECONDS]
  );
  return takeover.rowCount === 1 ? { state: "claimed" } : { state: "in_progress" };
}

The UPDATE in the last step is also atomic. If two retries find the same expired lock, only one of them matches the locked_until < now() condition and gets the key. If the row disappears between the two queries, for example because it was released after a failure, the function reports in_progress and the client simply retries.

Set LOCK_SECONDS comfortably above the slowest time your operation takes. If the lock expires while the original request is still running, a retry can take over and run the work a second time.

Step 4: Do the work and store the response together

Once a request owns the key, it creates the order and marks the key as completed. Both writes happen in one transaction, so there is no moment where the order exists but the key still says in_progress, or the other way round. Note that a transaction in node-postgres has to use a single client checked out from the pool, as the node-postgres transaction documentation explains:

// idempotency-store.js (continued)
export async function completeKey(client, { clientId, key }, status, body) {
  await client.query(
    `UPDATE idempotency_keys
     SET status = 'completed',
         response_status = $3,
         response_body = $4::jsonb,
         completed_at = now()
     WHERE client_id = $1 AND idempotency_key = $2`,
    [clientId, key, status, JSON.stringify(body)]
  );
}

export async function releaseKey(pool, { clientId, key }) {
  await pool.query(
    `DELETE FROM idempotency_keys
     WHERE client_id = $1 AND idempotency_key = $2 AND status = 'in_progress'`,
    [clientId, key]
  );
}

releaseKey runs when the work fails. Deleting the claim lets the client retry with the same key instead of waiting for the lock to expire. It only deletes rows that are still in progress, so a completed response is never thrown away.

Step 5: Wire it into an Express route

The route validates the body first. A request with invalid input never touches the key table, so the client can fix the input and resend with the same key. Error responses use the application/problem+json format from RFC 9457, which the idempotency draft also uses in its examples:

// server.js
import express from "express";
import pg from "pg";
import { readIdempotencyKey } from "./idempotency-key.js";
import { fingerprintRequest } from "./fingerprint.js";
import { claimKey, completeKey, releaseKey } from "./idempotency-store.js";

const pool = new pg.Pool(); // reads PGHOST, PGUSER, PGDATABASE and so on
const app = express();
app.use(express.json({ limit: "100kb" }));

// Demo only: replace with your real authentication middleware.
app.use((req, res, next) => {
  req.clientId = req.get("X-Client-Id") ?? "demo-client";
  next();
});

function problem(res, status, title) {
  return res
    .status(status)
    .type("application/problem+json")
    .json({ type: "about:blank", title, status });
}

app.post("/orders", async (req, res) => {
  const { productId, quantity } = req.body ?? {};
  if (typeof productId !== "string" || !Number.isInteger(quantity) || quantity < 1) {
    return problem(res, 400, "productId and a positive integer quantity are required");
  }

  const key = readIdempotencyKey(req.get("Idempotency-Key"));
  if (!key) {
    return problem(res, 400, "Idempotency-Key is missing or invalid");
  }

  const ctx = {
    clientId: req.clientId,
    key,
    fingerprint: fingerprintRequest(req.method, req.path, req.body),
  };
  const claim = await claimKey(pool, ctx);

  if (claim.state === "replay") {
    res.set("Idempotent-Replayed", "true");
    return res.status(claim.status).json(claim.body);
  }
  if (claim.state === "mismatch") {
    return problem(res, 422, "Idempotency-Key was already used for a different request");
  }
  if (claim.state === "in_progress") {
    res.set("Retry-After", "1");
    return problem(res, 409, "A request with this Idempotency-Key is still in progress");
  }

  const client = await pool.connect();
  try {
    await client.query("BEGIN");
    const { rows } = await client.query(
      `INSERT INTO orders (client_id, product_id, quantity)
       VALUES ($1, $2, $3)
       RETURNING id, product_id AS "productId", quantity, created_at AS "createdAt"`,
      [ctx.clientId, productId, quantity]
    );
    const order = rows[0];
    await completeKey(client, ctx, 201, order);
    await client.query("COMMIT");
    return res.status(201).json(order);
  } catch (error) {
    await client.query("ROLLBACK");
    await releaseKey(pool, ctx);
    throw error;
  } finally {
    client.release();
  }
});

app.listen(3000, () => console.log("Listening on http://localhost:3000"));

A few points about this route:

  • Express 5 forwards rejected promises to the error handler, so the throw in the catch block ends up in the default handler as a 500, as described in the Express error-handling guide. On Express 4 you'd need to call next(error) yourself.
  • The replayed response is the stored one, status code included. A retry gets 201 Created with the same order ID, exactly as if the first response had arrived.
  • Idempotent-Replayed** is not part of the draft.** It's an optional convention that makes replays easy to spot in logs and client code. Drop it if you prefer to keep responses identical.
  • Retry-After** on the 409** tells the client how long to wait before checking again.

Step 6: Retry from the client with the same key

The server side only works if the client keeps the key stable. The most common client bug is generating a new key inside the retry loop, which turns every retry into a new operation. Generate the key once per logical action, before the first attempt:

// client.js
import { randomUUID } from "node:crypto";

const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));

export async function createOrder(order, { attempts = 4 } = {}) {
  const key = randomUUID(); // one key for every attempt of this order

  for (let attempt = 1; attempt <= attempts; attempt++) {
    try {
      const response = await fetch("http://localhost:3000/orders", {
        method: "POST",
        headers: {
          "Content-Type": "application/json",
          "Idempotency-Key": `"${key}"`,
        },
        body: JSON.stringify(order),
        signal: AbortSignal.timeout(5000),
      });

      const retryable = response.status === 409 || response.status >= 500;
      if (!retryable || attempt === attempts) return response;

      const retryAfter = Number(response.headers.get("Retry-After")) || 0;
      await sleep(Math.max(retryAfter * 1000, backoff(attempt)));
    } catch (error) {
      // Network error or timeout: the server may or may not have done the work.
      if (attempt === attempts) throw error;
      await sleep(backoff(attempt));
    }
  }
}

function backoff(attempt) {
  const base = 250 * 2 ** (attempt - 1);
  return base + Math.random() * base; // exponential backoff with jitter
}

The catch branch is the reason idempotency keys exist. After a timeout, the client can't know whether the order was created. With a stable key, retrying is safe either way: if the first attempt succeeded, the retry returns the stored order; if it didn't, the retry creates it. The random jitter spreads retries out, so many clients recovering from the same outage don't all hit the server at once.

In a browser or mobile app, store the key with the pending action, for example in the form state or a local queue. If the user taps "Place order" again after an error, reuse it. Only generate a new key when the user starts a genuinely new action.

Step 7: Expire old keys

Keys can't live forever, or the table grows without limit. The draft leaves the retention period to the server but says it should be published in the API documentation, so clients know how long a retry stays safe. Twenty-four hours covers most retry scenarios. A scheduled job can delete older rows in batches:

DELETE FROM idempotency_keys
WHERE ctid IN (
  SELECT ctid FROM idempotency_keys
  WHERE created_at < now() - interval '24 hours'
  LIMIT 5000
);

Run it every few minutes from cron or your job scheduler until it deletes zero rows. Deleting in batches keeps each transaction short, and the created_at index from Step 1 keeps the inner query fast. A retry that arrives after its key has expired is treated as a new request, which is why the retention period belongs in your documentation.

Test the behavior with curl

Start the server with node server.js, then send the same request twice:

KEY=$(uuidgen)

curl -i -X POST http://localhost:3000/orders \
  -H "Content-Type: application/json" \
  -H "Idempotency-Key: \"$KEY\"" \
  -d '{"productId":"sku_123","quantity":2}'

# Same key, same body: returns the stored 201 with Idempotent-Replayed: true
curl -i -X POST http://localhost:3000/orders \
  -H "Content-Type: application/json" \
  -H "Idempotency-Key: \"$KEY\"" \
  -d '{"quantity":2,"productId":"sku_123"}'

The second request lists the properties in a different order, and it's still recognized as a retry because of the canonical fingerprint. Both responses carry the same order ID, and the orders table contains one row.

Now change the quantity while keeping the key. The server answers 422, because the key now belongs to a different request:

curl -i -X POST http://localhost:3000/orders \
  -H "Content-Type: application/json" \
  -H "Idempotency-Key: \"$KEY\"" \
  -d '{"productId":"sku_123","quantity":5}'

To see the concurrent case, add await new Promise((r) => setTimeout(r, 3000)); before completeKey in the route, restart the server, and fire two requests with a new key at the same time:

KEY=$(uuidgen)
for i in 1 2; do
  curl -s -o /dev/null -w "%{http_code}\n" -X POST http://localhost:3000/orders \
    -H "Content-Type: application/json" \
    -H "Idempotency-Key: \"$KEY\"" \
    -d '{"productId":"sku_123","quantity":1}' &
done
wait

One request prints 201 and the other 409. Without the ON CONFLICT claim, both would have printed 201 and created two orders. Remove the delay when you're done.

Know the limits

This design guarantees that the database work in Step 4 happens once per key. Two situations need extra care:

  • Side effects outside your database. If the route charges a card or sends an email through another service, the commit in Step 4 can't roll that call back. Pass a key derived from yours to the downstream API if it supports idempotency keys, and make the external call before completeKey so a crash leaves the key in progress rather than completed without the side effect.
  • Very slow operations. If the work can take longer than LOCK_SECONDS, either raise the lock time or extend locked_until periodically while the work runs. Otherwise a retry can take over a key that is still being processed.

Idempotency keys don't replace other safeguards either. A unique constraint on a natural business key, such as one payment per invoice, still catches duplicates that arrive with different keys, for example when a user submits the same form from two tabs.

Wrapping up

With one table, an atomic claim and a transaction that stores the response next to the work, POST endpoints become safe to retry. Clients get a simple rule: generate one key per action, reuse it on every retry. The server takes care of the rest, including the concurrent retries that a SELECT-then-INSERT approach misses.

The same pattern works for PATCH endpoints and for webhooks you send to other systems. Start with the endpoints where a duplicate costs real money or confuses a customer, and publish your key format and retention period in the API documentation so client developers know what to send.

hostinger_2026_11_footer
Source: Vasyl Popovych · www.sitepoint.com