Enjoying Blockend?

Give us a star on GitHub

Star on GitHub
blockend

Blockend

03 guides

Idempotency in production

Design the store, scope keys, classify failures, and run recovery jobs for retried requests.

The idempotency block deduplicates retries against one store. The guarantee depends on your schema, key scope, failure classification, and background jobs. This guide covers the parts that usually break first.

Install the block before you start:

pnpm dlx blockend-cli add idempotency

See Idempotency for the API and framework adapters.

The client contract

A client must generate one key for one logical operation and reuse that key, with the same payload, for every retry.

Client behaviorResult
Retry with the same key and same payloadThe stored response is replayed.
Retry with the same key and a different payload409 KEY_REUSED_WITH_DIFFERENT_REQUEST.
Send two requests at the same time with the same keyOne runs, the other gets 409 REQUEST_IN_PROGRESS.
Retry after a permanent failure409 REQUEST_FAILED.
Retry after a transient failureThe operation runs again. The third transient failure marks the key FAILED.

Keys are scoped by (userId, operation, key). The same key used by two users or two operations is two independent records.

Do not generate a new key for each retry. That turns every retry into a new operation and defeats the block.

Store design

The store is the source of truth. The cache is optional. Everything depends on create being atomic.

Use a unique constraint on the scope:

CREATE TABLE idempotency_records (
  operation      TEXT        NOT NULL,
  user_id        TEXT        NOT NULL,
  key            TEXT        NOT NULL,
  request_hash   TEXT        NOT NULL,
  status         TEXT        NOT NULL CHECK (status IN ('PROCESSING', 'SUCCESS', 'FAILED')),
  response       JSONB,
  expires_at     TIMESTAMPTZ NOT NULL,
  created_at     TIMESTAMPTZ NOT NULL DEFAULT now(),
  updated_at     TIMESTAMPTZ NOT NULL DEFAULT now(),
  PRIMARY KEY (operation, user_id, key)
);

create should insert only when the scope is free, and replace a terminal record that has expired:

INSERT INTO idempotency_records
  (operation, user_id, key, request_hash, status, expires_at)
VALUES ($1, $2, $3, $4, 'PROCESSING', $5)
ON CONFLICT (operation, user_id, key) DO UPDATE
  SET request_hash = EXCLUDED.request_hash,
      status = 'PROCESSING',
      response = NULL,
      expires_at = EXCLUDED.expires_at,
      created_at = now(),
      updated_at = now()
  WHERE idempotency_records.expires_at <= now()
    AND idempotency_records.status IN ('SUCCESS', 'FAILED')
RETURNING operation, (xmax <> 0) AS replaced;

A returned row means the scope was free or an expired terminal record was replaced. xmax is zero for a fresh insert and nonzero when the conflict path updated the expired record.

If replaced is true, delete the matching retry counter in the same transaction and return { status: "CREATED" }. If replaced is false, keep the counter and return { status: "CREATED" }. Otherwise return { status: "DUPLICATE" }, and the handler reads the existing row. Do not clear the counter for every returned row: a retry after a transient failure inserts a new record, and clearing the counter would reset the attempt count before it reaches three.

Treat an expired SUCCESS or FAILED row as absent in both find and create. The handler checks the request hash and record status, but not expiresAt. If find returns an expired success, the old response is replayed. If create cannot replace the expired row, the handler either replays that record or returns RECORD_NOT_FOUND; cleanup eventually removes it. Do not treat an expired PROCESSING row as free, because the original operation may still be running. Let recovery mark abandoned locks FAILED.

Keep the retry counter outside the record

After a transient failure, the handler deletes the record so the client can retry. A retry_count column on that record would reset on the next insert, so the counter would never reach three. Store it separately:

CREATE TABLE idempotency_retry_counts (
  operation   TEXT        NOT NULL,
  user_id     TEXT        NOT NULL,
  key         TEXT        NOT NULL,
  retry_count INTEGER     NOT NULL DEFAULT 0,
  updated_at  TIMESTAMPTZ NOT NULL DEFAULT now(),
  PRIMARY KEY (operation, user_id, key)
);

incrementRetryCount can be an upsert:

INSERT INTO idempotency_retry_counts (operation, user_id, key, retry_count)
VALUES ($1, $2, $3, 1)
ON CONFLICT (operation, user_id, key)
DO UPDATE SET retry_count = idempotency_retry_counts.retry_count + 1,
              updated_at = now()
RETURNING retry_count;

deleteExpired should remove expired records and their retry counters.

Conditional updates

markSuccess and markFailed should only change a PROCESSING record:

UPDATE idempotency_records
SET status = 'FAILED', updated_at = now()
WHERE operation = $1 AND user_id = $2 AND key = $3
  AND status = 'PROCESSING';

Without the status condition, a late failure from an old process can overwrite a success.

Map record fields

IdempotencyStore.create receives a camelCase record: key, operation, userId, requestHash, response, status, expiresAt, createdAt, and updatedAt. Map them to your column names. find must return the same camelCase shape.

A per-process Map cannot work across multiple app instances. Use a shared database or another store with an atomic create. If two inserts can both return CREATED, two requests will run the same operation.

Scope keys to users and operations

The default user ID is "anonymous" when your auth middleware has not set a user. That makes keys global. Any client that learns a key and payload could read another user's stored response.

Set getUserId on every protected route. The examples assume your auth middleware declares req.user, request.user, or the Hono user context variable.

// Express
getUserId: (req) => req.user.id;

// Fastify
getUserId: (request) => request.user.id;

// Hono
getUserId: (c) => c.get("user").id;

Set getOperation when the default path is not stable enough:

// Express
getOperation: (req) => `payments:create:${req.user.tenantId}`;

The operation is part of the key. Including the tenant adds another isolation boundary. Use the same operation string for every retry of the same logical operation.

Classify failures

isPermanentError decides whether a failure poisons the key.

isPermanentError: (error) =>
  error instanceof ValidationError || error instanceof InsufficientFundsError;
ErrorClassify asClient result
Validation or business rule failurePermanent409 REQUEST_FAILED on retry.
Timeout, connection reset, temporary upstream failureTransientLock released; retry can run again.
Unknown errorYour choiceDefault is permanent.

The default is permanent for every error. If you omit the classifier, one temporary database error blocks the key for 24 hours. Decide for every route.

A transient failure increments the retry counter. The first two transient failures delete the lock so the client can retry. The third marks the key FAILED.

Response limits

The block stores the route's return value as JSON. It does not store the HTTP status code or response headers. A replay is sent with the adapter's default 200 status.

This affects routes that create resources with 201. Put the status in the body, or document that a replay returns 200. Do not rely on the block to reproduce headers such as Location.

The request body is hashed with a deterministic serializer. It must be JSON-compatible. undefined, NaN, Infinity, BigInt, functions, and symbols fail. The adapters substitute {} when no body is present.

Use getBody to hash only fields that define the operation. Fields such as timestamps and trace IDs change on retry and make a valid retry look like a different request:

getBody: (req) => ({
  amount: req.body.amount,
  currency: req.body.currency
});

Failure windows

The block records success after your route returns. A process can die between those steps.

Failure pointState left behindEffect
Before the lock is createdNo recordRetry can run normally.
After the lock, before the side effectPROCESSINGRetry gets 409 REQUEST_IN_PROGRESS while recovery later marks it FAILED.
After the side effect, before markSuccessPROCESSINGRecovery marks it FAILED; retry gets 409 even though the side effect happened.
After markSuccessSUCCESSRetry replays the stored response.

Recovery does not know whether your side effect happened. If the operation charges a card or moves inventory, reconcile records marked FAILED by the recovery job before you let a client retry with a new key.

This is why the block provides a single-store deduplication guarantee, not distributed exactly-once execution.

Store and cache outages

If the store throws, the handler throws STORE_UNAVAILABLE, and the adapters return 503. This is fail-closed.

If the cache throws, the cache manager logs the error and falls back to the store. The request still succeeds if the store is healthy.

const handler = new IdempotencyHandler(store, cache, { logger, metrics });

Use a shared cache such as Redis when you have multiple instances. A per-process cache is only a local fast path and does not break correctness because the store remains authoritative.

Run recovery and cleanup jobs

Run both jobs on a schedule from one worker or with a lock that prevents overlapping runs.

import { IdempotencyHandler } from "@/blocks/idempotency";

const handler = new IdempotencyHandler(store);

const recovery = await handler.recoverStuckRecords({
  timeoutInMs: 5 * 60 * 1000,
  limit: 100
});

const cleanup = await handler.cleanupExpiredRecords({
  limit: 500
});

logger.info({ recovery, cleanup }, "idempotency maintenance complete");

recoverStuckRecords finds PROCESSING records whose updatedAt is older than the timeout and marks them FAILED. It does not retry them.

cleanupExpiredRecords removes expired SUCCESS and FAILED records. It never removes PROCESSING records.

The internal record TTL is 24 hours and is not configurable. Expiry is enforced by your store. The handler does not check expiresAt, so a store that returns an expired success replays it. With the find and create behavior above, an expired terminal record is replaced and the operation runs again before cleanup removes it.

If a legitimate operation can run longer than the recovery timeout, raise the timeout or update updatedAt through your store while it runs. Otherwise recovery can mark a live operation as failed, and a retry can execute it again.

Observability

Pass the logger block's Pino instance directly:

import { logger } from "@/blocks/logger/core";
import { IdempotencyHandler } from "@/blocks/idempotency";

const handler = new IdempotencyHandler(store, cache, { logger });

The logger block sets requestId through runWithLoggerContext. Its adapters already create that context for HTTP requests, so idempotency logs written during a request carry the same requestId.

If you use another logger, bridge it:

import { createLoggerAdapter } from "@/blocks/idempotency/utils/create-logger";

const logger = createLoggerAdapter((level, message, meta) => {
  console[level](message, meta ?? "");
});

const handler = new IdempotencyHandler(store, undefined, { logger });

The handler expects debug, info, warn, and error methods that accept an object and a message. A Pino-shaped logger already matches.

Metrics to alert on:

MetricMeaning
idempotency_store_errors_totalStore failures. Alert on any sustained value.
idempotency_duplicates_totalDuplicate requests, including replays and conflicts.
idempotency_latency_secondsHandler latency, including your operation.
idempotency_recovered_records_totalLocks recovered from crashed workers.

A spike in idempotency_duplicates_total can mean clients are retrying heavily, or a client is reusing a key with different payloads.

The adapters attach context to the request:

FrameworkLocation
Expressres.locals.idempotency
Fastifyrequest.idempotency
HonogetIdempotencyContext(c)
// Fastify
app.addHook("onResponse", (request, _reply, done) => {
  request.log.info({ idempotency: request.idempotency }, "idempotency decision");
  done();
});

Compose with the other blocks

Error handler

The adapters already map IdempotencyError to HTTP. Let business errors reach your global error handler:

import { idempotent } from "@/blocks/idempotency/adapters/express";
import { createExpressErrorHandler } from "@/blocks/error-handler/adapters/express";

app.post("/payments", idempotent(handler, createPayment));

app.use(createExpressErrorHandler(boundary));

Do not add a second IdempotencyError branch to the global handler unless you disable the adapter's mapping.

Use statusMap to change a status for one route:

idempotent(handler, createPayment, {
  statusMap: { REQUEST_IN_PROGRESS: 425 }
});

Response formatter

If the route returns a formatted body, that body is stored and replayed. Keep the response shape stable across versions, because old records remain valid for 24 hours. A deploy that changes the response type can replay an old shape.

Rate limiter

Rate limit the endpoint before the idempotency wrapper. The limiter rejects retry storms before they reach the store.

Testing checklist

Test these cases with a real store or a faithful in-memory implementation:

  • Duplicate request replays the stored body and runs the route once.
  • Same key with a different body returns 409.
  • Concurrent duplicates: one runs, one gets 409 REQUEST_IN_PROGRESS.
  • Permanent failure returns 409 REQUEST_FAILED on retry.
  • Transient failure releases the lock and re-runs.
  • Three transient failures mark the key failed.
  • Store failure returns 503.
  • Cache failure falls back to the store.
  • Keys are isolated by user and operation.
  • Recovery marks an abandoned PROCESSING record FAILED.
  • Cleanup removes expired successes and failures but not PROCESSING records.
  • Capture middleware does not store a 4xx or 5xx response as success.

Run these tests against the same database engine you use in production. SQLite and Postgres can differ on conflict handling and timestamp precision.

Limits

  • Single-store deduplication, not cross-service exactly-once.
  • 24 hour record lifetime.
  • No stored status code or headers.
  • No bundled store or cache.
  • Recovery marks records failed; it does not replay operations.

On this page