Enjoying Blockend?

Give us a star on GitHub

Star on GitHub
blockend

Blockend

02 blocks

Idempotency

Validated

Make retried requests safe with an atomic store lock, optional cache, and adapters for Express, Fastify, and Hono.

The idempotency block wraps a state-changing operation so that retries with the same key return the stored result instead of running the operation again.

A request is scoped by (userId, operation, idempotency key). The first request creates a PROCESSING record. Later requests either replay the stored success, receive a conflict because the first request is still running, or receive a conflict because it failed.

The block does not include a database store or cache. You provide an IdempotencyStore. A cache is optional.

Set getUserId to a real authenticated user ID. The default falls back to "anonymous" when the framework request has no user, which gives every caller the same key scope. A client that learns a key and payload could then read another user's stored response.

Quick start

pnpm dlx blockend-cli init
pnpm dlx blockend-cli add idempotency
import express from "express";
import { IdempotencyHandler } from "@/blocks/idempotency";
import { idempotent } from "@/blocks/idempotency/adapters/express";

const app = express();
app.use(express.json());

// Your store implements IdempotencyStore.
const handler = new IdempotencyHandler(store);

app.post(
  "/payments",
  idempotent(
    handler,
    async (req) => {
      const charge = await createCharge(req.body);
      return { id: charge.id, status: charge.status };
    },
    {
      requireKey: true,
      getUserId: (req) => req.user.id,
      getOperation: () => "payments:create"
    }
  )
);

Register authentication before this route. req.user.id must be set by trusted middleware. The examples assume your auth layer declares req.user on the Express request type.

Files

idempotency/
├── adapters/
│   ├── express.ts
│   ├── fastify.ts
│   ├── hono.ts
│   └── shared.ts
├── core/
│   └── idempotency-handler.ts
├── errors/
├── interfaces/
│   ├── cache.ts
│   ├── logger.ts
│   ├── observability.ts
│   └── store.ts
├── jobs/
│   ├── record-cleaner.ts
│   └── record-recovery.ts
├── services/
│   └── cache-manager.ts
├── types/
├── utils/
└── index.ts

The root index.ts re-exports the core API. Framework adapters are not re-exported from the root. Import them from adapters/<framework>.

Installation

pnpm dlx blockend-cli add idempotency

The CLI copies the core, the shared adapter helpers, one framework adapter, and the tests. The core has no runtime dependencies.

Copy the files from the registry into blocks/idempotency. At minimum you need the root index.ts, core/, errors/, interfaces/, jobs/, services/, types/, utils/, adapters/shared.ts, and one framework adapter. Keep the relative directory layout.

Root exports

/**
 * Master barrel export for the idempotency library.
 *
 * Re-exports the complete public API so consumers can import everything from a
 * single entry point, exactly as they could from the previous monolithic
 * `IdempotencyHandler` module:
 *
 *   import { IdempotencyHandler, DEFAULT_CACHE_TTL } from "idempotency/core";
 *
 * The module is decomposed into focused sub-modules (errors, interfaces, types,
 * utils, services, jobs) — see `core/idempotency-handler.ts` for the main class.
 */

// Errors
export { IDEMPOTENCY_ERROR_CODES } from "./errors/codes";
export type { IdempotencyErrorCode } from "./errors/codes";
export { IdempotencyError } from "./errors/idempotency-errors";

// Interfaces
export type { IdempotencyCache } from "./interfaces/cache";
export type {
  DeleteExpiredParams,
  FindAllFilters,
  IdempotencyStore,
  RecoverStuckRecordsOptions,
  RecoveryResult
} from "./interfaces/store";
export { noopLogger, noopMetrics } from "./interfaces/observability";
export type { Logger, Metrics, MetricName } from "./interfaces/observability";

// Types
export type {
  CachedResponse,
  CreateIdempotencyRecord,
  CreateProcessingResult,
  CreateRecordResult,
  IdempotencyRecord,
  IdempotencyStatus
} from "./types/index";

// Services
export { CacheManager, DEFAULT_CACHE_TTL } from "./services/cache-manager";

// Utils
export {
  DEFAULT_MAX_KEY_LENGTH,
  DEFAULT_MIN_KEY_LENGTH,
  UUID_REGEX,
  validateKey
} from "./utils/key-validator";
export type { KeyValidationOptions } from "./utils/key-validator";
export { hashRequest, serialize } from "./utils/serializer";

// Jobs
export { cleanupExpiredRecords } from "./jobs/record-cleaner";
export type { CleanupExpiredOptions, CleanupResult } from "./jobs/record-cleaner";
export { recoverStuckRecords } from "./jobs/record-recovery";

// Core handler
export { IdempotencyHandler } from "./core/idempotency-handler";
export type { IdempotencyHandlerOptions } from "./core/idempotency-handler";

Handler

import { IDEMPOTENCY_ERROR_CODES } from "../errors/codes";
import { IdempotencyError } from "../errors/idempotency-errors";
import type { IdempotencyCache } from "../interfaces/cache";
import type { Logger, Metrics } from "../interfaces/observability";
import { noopLogger, noopMetrics } from "../interfaces/observability";
import type {
  IdempotencyStore,
  RecoverStuckRecordsOptions,
  RecoveryResult
} from "../interfaces/store";
import type {
  CreateIdempotencyRecord,
  CreateProcessingResult,
  IdempotencyRecord
} from "../types/index";
import { validateKey } from "../utils/key-validator";
import type { KeyValidationOptions } from "../utils/key-validator";
import { hashRequest, serialize } from "../utils/serializer";
import { constantTimeEquals } from "../utils/constant-time-equals";
import { CacheManager } from "../services/cache-manager";
import { cleanupExpiredRecords } from "../jobs/record-cleaner";
import type { CleanupExpiredOptions, CleanupResult } from "../jobs/record-cleaner";
import { recoverStuckRecords } from "../jobs/record-recovery";

export type IdempotencyHandlerOptions = {
  logger?: Logger;
  metrics?: Metrics;
};

const DEFAULT_RECORD_TTL = 24 * 60 * 60 * 1000;
const MAX_ALLOWED_RETRIES = 3;

/**
 * IdempotencyHandler wraps business logic so that retries of the same request
 * are safe: a request keyed by (operation, userId, key) executes exactly once,
 * and subsequent attempts receive the stored result instead.
 *
 * The class deliberately focuses on orchestration only. All heavy lifting is
 * delegated to focused modules:
 *   - key validation   -> utils/key-validator
 *   - hashing          -> utils/serializer
 *   - L1 cache         -> services/cache-manager
 *   - background jobs  -> jobs/record-cleaner, jobs/record-recovery
 *
 * Public API (execute, validateKey, serialize, hashRequest,
 * cleanupExpiredRecords, recoverStuckRecords, retry) is fully
 * backward-compatible with the previous monolithic implementation.
 */
export class IdempotencyHandler {
  private readonly logger: Logger;
  private readonly metrics: Metrics;
  private readonly cacheManager: CacheManager;

  constructor(
    private readonly store: IdempotencyStore,
    cache?: IdempotencyCache,
    options: IdempotencyHandlerOptions = {}
  ) {
    this.logger = options.logger ?? noopLogger;
    this.metrics = options.metrics ?? noopMetrics;
    this.cacheManager = new CacheManager(cache, this.logger, this.metrics);
  }

  /**
   * Sanitizes and validates the incoming idempotency key.
   * Delegates to `utils/key-validator`, which trims BEFORE length checks so
   * whitespace alone can't bypass length limits or bloat storage.
   *
   * @returns the cleaned key; callers MUST use this returned value, not the raw input.
   */
  public validateKey(key: unknown, options?: KeyValidationOptions): string {
    return validateKey(key, options);
  }

  /**
   * Deterministically stringifies a payload structure (recursively sorted keys,
   * order-preserving arrays, non-ambiguous primitive encodings). Rejects
   * non-deterministic values (undefined, NaN, Infinity, BigInt, functions,
   * symbols). See `utils/serializer` for details.
   */
  public static serialize(value: unknown): string {
    return serialize(value);
  }

  /**
   * Produces a stable SHA-256 fingerprint of a request payload so identical
   * payloads (regardless of key order) hash identically.
   */
  public hashRequest(body: unknown): string {
    return hashRequest(body);
  }

  /**
   * Intended to be run periodically by a background worker or cron job.
   *
   * SAFETY INVARIANT: only deletes records with status 'SUCCESS' or 'FAILED'.
   * Records marked 'PROCESSING' are intentionally excluded here, even if
   * expired — purging an active lock would allow a duplicate incoming request
   * to grab a new lock and run concurrently. Stuck locks are handled by
   * `recoverStuckRecords()` instead.
   */
  public async cleanupExpiredRecords(options?: CleanupExpiredOptions): Promise<CleanupResult> {
    return cleanupExpiredRecords(this.store, this.logger, this.metrics, options);
  }

  /**
   * Recovers operations stuck in 'PROCESSING' (e.g., node crashed mid-execution)
   * by marking them 'FAILED'. A retry with the same key then returns
   * REQUEST_FAILED, so reconcile the side effect before using a new key.
   */
  public async recoverStuckRecords(options?: RecoverStuckRecordsOptions): Promise<RecoveryResult> {
    return recoverStuckRecords(this.store, this.logger, this.metrics, options);
  }

  /**
   * Manually re-opens a FAILED record as PROCESSING for a custom recovery
   * workflow. This does not execute the operation. A subsequent execute call
   * sees an in-progress record and returns REQUEST_IN_PROGRESS.
   */
  public async retry(
    userId: string,
    operation: string,
    key: string
  ): Promise<IdempotencyRecord | null> {
    const record = await this.store.find(key, operation, userId);

    if (!record) {
      return null;
    }

    // Already completed successfully; no retry needed
    if (record.status === "SUCCESS") {
      return record;
    }

    // Another thread or node is already processing this job
    if (record.status === "PROCESSING") {
      this.metrics.increment("idempotency_duplicates_total", 1, {
        operation,
        status: "processing"
      });
      throw new IdempotencyError(
        IDEMPOTENCY_ERROR_CODES.REQUEST_IN_PROGRESS,
        "The request is already being processed."
      );
    }

    // Re-acquire lock for failed operation
    if (record.status === "FAILED") {
      await this.markRecordProcessing(userId, operation, key);

      return {
        ...record,
        status: "PROCESSING",
        updatedAt: new Date()
      };
    }

    throw new IdempotencyError(
      IDEMPOTENCY_ERROR_CODES.STORE_UNAVAILABLE,
      "Unable to retry the idempotency record."
    );
  }

  /**
   * Main entrypoint for wrapping business logic with idempotency.
   *
   * Flow:
   * 1. Validate key -> Hash body payload.
   * 2. Check L1 cache (Redis/Memory). Hit -> return response immediately.
   * 3. Acquire DB lock (create PROCESSING record).
   * 4. Run `execute()` callback.
   * 5. Success -> Mark DB record SUCCESS & sync L1 cache.
   * 6. Error -> Check if error is transient or permanent:
   *    - Permanent error: Mark FAILED immediately (blocks identical retries).
   *    - Transient error: Increment retry count. Delete record if retries
   *      remain so the client can retry.
   */
  public async execute(
    userId: string,
    operation: string,
    key: string,
    body: unknown,
    execute: () => Promise<unknown>,
    options?: { isPermanentError?: (err: unknown) => boolean }
  ): Promise<unknown> {
    const startTime = performance.now();

    // The entire flow — including key validation and body hashing — runs
    // inside the try so the latency histogram is always emitted, even when an
    // attacker-controlled key/body is rejected up front.
    try {
      const validKey = this.validateKey(key);
      const requestHash = this.hashRequest(body);

      // 1. Fast path: check short-lived cache hit
      const cachedResponse = await this.cacheManager.getCachedResponse(
        userId,
        operation,
        validKey,
        requestHash
      );

      if (cachedResponse?.status === "HIT") {
        return cachedResponse.data.response;
      }

      const expiresAt = new Date(Date.now() + DEFAULT_RECORD_TTL);

      // 2. Lock phase: Atomic insert into DB
      const result = await this.createProcessingRecord({
        key: validKey,
        request_hash: requestHash,
        response: null,
        status: "PROCESSING",
        expires_at: expiresAt,
        user_id: userId,
        operation
      });

      // 3. Return cached DB result if request was completed previously
      if (result.kind === "EXISTING_SUCCESS") {
        return result.response;
      }

      // 4. Lock acquired successfully -> run actual business logic
      try {
        const response = await execute();

        await this.markRecordSuccess(userId, operation, validKey, response);

        // Async write to L1 cache; non-blocking failure
        await this.cacheManager.setCachedResponse(
          userId,
          operation,
          validKey,
          requestHash,
          response
        );

        this.logger.info(
          { key: validKey, userId, operation, status: "executed_success" },
          "Idempotent operation executed and recorded successfully"
        );

        return response;
      } catch (error) {
        // FAIL CLOSED: if the caller's error classifier itself throws, treat
        // the failure as permanent (mark the record FAILED) and rethrow the
        // ORIGINAL error — never let a classifier bug swallow the real cause
        // or leave the lock dangling.
        let permanent = true;

        try {
          permanent = options?.isPermanentError ? options.isPermanentError(error) : true;
        } catch {
          permanent = true;
        }

        if (permanent) {
          // Permanent business logic failure (e.g., validation fail) -> save as FAILED
          await this.markRecordFailed(userId, operation, validKey);
        } else {
          // Transient failure (e.g., DB connection drop) -> increment counter
          const retryCount = await this.incrementRetryCount(userId, operation, validKey);

          if (retryCount >= MAX_ALLOWED_RETRIES) {
            await this.markRecordFailed(userId, operation, validKey);
          } else {
            // Delete lock row so caller can retry immediately on next request
            await this.deleteRecord(userId, operation, validKey);
          }
        }

        this.logger.error(
          {
            key: validKey,
            userId,
            operation,
            permanent,
            error: error instanceof Error ? error.message : error
          },
          "Idempotent operation execution failed"
        );

        throw error;
      }
    } finally {
      const durationInSeconds = (performance.now() - startTime) / 1000;
      this.metrics.histogram("idempotency_latency_seconds", durationInSeconds, {
        operation
      });
    }
  }

  // ---------------------------------------------------------------------------
  // Private store-coordination helpers (used by execute()/retry() orchestration)
  // ---------------------------------------------------------------------------

  /**
   * Attempts an atomic insert of a PROCESSING lock record.
   *
   * - On `CREATED`: the lock is ours; execute the business logic.
   * - On `DUPLICATE`: the key already exists; inspect the existing row and
   *   either return its stored SUCCESS response, or reject with the
   *   appropriate idempotency error (in-progress / failed / hash mismatch).
   */
  private async createProcessingRecord({
    key,
    request_hash,
    response,
    expires_at,
    status,
    user_id,
    operation
  }: CreateIdempotencyRecord & {
    operation: string;
  }): Promise<CreateProcessingResult> {
    const record: IdempotencyRecord = {
      key,
      requestHash: request_hash,
      response,
      expiresAt: expires_at,
      status,
      userId: user_id,
      createdAt: new Date(),
      updatedAt: new Date(),
      operation
    };

    try {
      // Primary DB call: attempts an atomic insert (e.g. INSERT INTO ... ON CONFLICT DO NOTHING)
      const result = await this.store.create(record);

      if (result.status === "CREATED") {
        return { kind: "CREATED", record };
      }

      // Insert failed due to duplicate key; fetch existing row state
      const existingData = await this.findRecordByKey(user_id, operation, key);

      return this.handleExistingRecord(existingData, request_hash);
    } catch (error) {
      if (error instanceof IdempotencyError) {
        throw error;
      }

      this.metrics.increment("idempotency_store_errors_total", 1, {
        operation
      });
      this.logger.error(
        {
          key,
          userId: user_id,
          operation,
          error: error instanceof Error ? error.message : error
        },
        "Idempotency store error during record creation"
      );

      throw new IdempotencyError(
        IDEMPOTENCY_ERROR_CODES.STORE_UNAVAILABLE,
        "The idempotency store is currently unavailable."
      );
    }
  }

  /**
   * Inspects a pre-existing record (the insert was a DUPLICATE) and decides the
   * outcome: return the stored SUCCESS response, or throw the correct error.
   */
  private handleExistingRecord(
    existingData: IdempotencyRecord,
    requestHash: string
  ): CreateProcessingResult {
    this.metrics.increment("idempotency_duplicates_total", 1, {
      operation: existingData.operation,
      status: existingData.status.toLowerCase()
    });

    // Key reuse with payload mismatch -> reject immediately. Compared in
    // constant time so hash probing can't leak prefix information.
    if (!constantTimeEquals(existingData.requestHash, requestHash)) {
      this.logger.warn(
        {
          key: existingData.key,
          userId: existingData.userId,
          operation: existingData.operation
        },
        "Idempotency key reused with different request body"
      );
      throw new IdempotencyError(
        IDEMPOTENCY_ERROR_CODES.KEY_REUSED_WITH_DIFFERENT_REQUEST,
        "Idempotency key was already used with a different request."
      );
    }

    if (existingData.status === "SUCCESS") {
      this.logger.info(
        {
          key: existingData.key,
          userId: existingData.userId,
          operation: existingData.operation
        },
        "Returning existing success response from store"
      );
      return {
        kind: "EXISTING_SUCCESS",
        // Return the stored response payload (not the full record) so callers
        // receive the same shape as a fresh execution.
        response: existingData.response
      };
    }

    if (existingData.status === "PROCESSING") {
      this.logger.warn(
        {
          key: existingData.key,
          userId: existingData.userId,
          operation: existingData.operation
        },
        "Concurrent request blocked; key is currently processing"
      );
      throw new IdempotencyError(
        IDEMPOTENCY_ERROR_CODES.REQUEST_IN_PROGRESS,
        "The request is already being processed."
      );
    }

    if (existingData.status === "FAILED") {
      throw new IdempotencyError(
        IDEMPOTENCY_ERROR_CODES.REQUEST_FAILED,
        "The previous request with this idempotency key failed."
      );
    }

    throw new IdempotencyError(
      IDEMPOTENCY_ERROR_CODES.STORE_UNAVAILABLE,
      "Unknown idempotency record status."
    );
  }

  private async findRecordByKey(userId: string, operation: string, key: string) {
    const record = await this.store.find(key, operation, userId);

    if (!record) {
      throw new IdempotencyError(
        IDEMPOTENCY_ERROR_CODES.RECORD_NOT_FOUND,
        "No idempotency record found."
      );
    }

    return record;
  }

  private async markRecordSuccess(
    userId: string,
    operation: string,
    key: string,
    response: unknown
  ): Promise<void> {
    try {
      await this.store.markSuccess(key, response, userId, operation);
    } catch (error) {
      this.metrics.increment("idempotency_store_errors_total", 1, {
        operation
      });
      if (error instanceof IdempotencyError) {
        throw error;
      }

      throw new IdempotencyError(
        IDEMPOTENCY_ERROR_CODES.STORE_UNAVAILABLE,
        "Failed to update the record to success."
      );
    }
  }

  private async markRecordProcessing(
    userId: string,
    operation: string,
    key: string
  ): Promise<void> {
    try {
      await this.store.markProcessing(key, operation, userId);
    } catch (error) {
      this.metrics.increment("idempotency_store_errors_total", 1, {
        operation
      });
      if (error instanceof IdempotencyError) {
        throw error;
      }

      throw new IdempotencyError(
        IDEMPOTENCY_ERROR_CODES.STORE_UNAVAILABLE,
        "Failed to update the record to processing."
      );
    }
  }

  private async markRecordFailed(userId: string, operation: string, key: string): Promise<void> {
    try {
      await this.store.markFailed(key, operation, userId);
    } catch (error) {
      this.metrics.increment("idempotency_store_errors_total", 1, {
        operation
      });
      if (error instanceof IdempotencyError) {
        throw error;
      }

      throw new IdempotencyError(
        IDEMPOTENCY_ERROR_CODES.STORE_UNAVAILABLE,
        "Failed to update the record to failed."
      );
    }
  }

  private async incrementRetryCount(
    userId: string,
    operation: string,
    key: string
  ): Promise<number> {
    try {
      return await this.store.incrementRetryCount(key, operation, userId);
    } catch (error) {
      this.metrics.increment("idempotency_store_errors_total", 1, {
        operation
      });
      if (error instanceof IdempotencyError) {
        throw error;
      }

      throw new IdempotencyError(
        IDEMPOTENCY_ERROR_CODES.STORE_UNAVAILABLE,
        "Failed to increment retry count."
      );
    }
  }

  private async deleteRecord(userId: string, operation: string, key: string): Promise<void> {
    try {
      await this.store.delete(key, operation, userId);
    } catch (error) {
      this.metrics.increment("idempotency_store_errors_total", 1, {
        operation
      });
      this.logger.error(
        {
          key,
          userId,
          operation,
          error: error instanceof Error ? error.message : error
        },
        "Failed to delete idempotency record"
      );
    }
  }
}

Store interface

import type { CreateRecordResult, IdempotencyRecord } from "../types/index";

export interface FindAllFilters {
  status?: "PROCESSING" | "SUCCESS" | "FAILED";
  updatedBefore?: Date;
  limit?: number;
}

export interface RecoverStuckRecordsOptions {
  timeoutInMs?: number;
  limit?: number;
}

export interface RecoveryResult {
  processed: number;
  succeeded: number;
  failed: number;
}

export interface DeleteExpiredParams {
  /** Cutoff timestamp; purge rows where expires_at < expiredBefore */
  expiredBefore: Date;
  /**
   * Only delete non-active records (SUCCESS/FAILED).
   * Excludes PROCESSING records to prevent deleting active locks during long jobs.
   */
  statuses: Array<"SUCCESS" | "FAILED">;
  /** Optional batch limit to prevent database lock escalation during cleanup */
  limit?: number;
}

export interface IdempotencyStore {
  create(record: IdempotencyRecord): Promise<CreateRecordResult>;

  find(key: string, operation: string, userId: string): Promise<IdempotencyRecord | null>;

  /** Query records with optional filtering for background jobs or adapters */
  findAll(filters?: FindAllFilters): Promise<IdempotencyRecord[]>;

  markSuccess(key: string, response: unknown, userId: string, operation: string): Promise<void>;

  markProcessing(key: string, operation: string, userId: string): Promise<void>;

  markFailed(key: string, operation: string, userId: string): Promise<void>;

  /**
   * Increments the retry counter for a key and returns the updated count.
   *
   * CONTRACT: the counter MUST survive record deletion. The handler deletes a
   * record after a transient failure (so the client can retry) and then
   * creates a fresh one on the next attempt — if the counter lived on the row
   * and reset on re-creation, `MAX_ALLOWED_RETRIES` would never be reached and
   * the key would never be poisoned. Implementations should keep the count in
   * a location that outlives the row (e.g. a dedicated counter table/column
   * upserted by key, never reset on re-create).
   */
  incrementRetryCount(key: string, operation: string, userId: string): Promise<number>;

  /** Deletes/releases an idempotency record (e.g., after a transient error) */
  delete(key: string, operation: string, userId: string): Promise<void>;

  /**
   * Deletes expired records matching specific status conditions.
   * Returns the count of deleted rows.
   */
  deleteExpired(params: DeleteExpiredParams): Promise<number>;
}

Shared adapter helpers

/**
 * Adapter-agnostic HTTP helpers shared by every framework adapter.
 *
 * The framework adapters (Express / Fastify / Hono) translate `IdempotencyError`
 * into HTTP responses. The status mapping and the error envelope are identical
 * across frameworks, so they live here once instead of being copied into each
 * adapter.
 */
import type { IdempotencyErrorCode } from "../errors/codes";
import { IdempotencyError } from "../errors/idempotency-errors";

// Default error code -> HTTP status mapping.
export const DEFAULT_STATUS_MAP: Record<IdempotencyErrorCode, number> = {
  // Client input problems -> 400
  KEY_INVALID_TYPE: 400,
  KEY_REQUIRED: 400,
  KEY_TOO_SHORT: 400,
  KEY_TOO_LONG: 400,
  KEY_INVALID_FORMAT: 400,
  UNSUPPORTED_REQUEST_VALUE: 400,
  // Idempotency conflicts -> 409 Conflict
  KEY_REUSED_WITH_DIFFERENT_REQUEST: 409,
  REQUEST_IN_PROGRESS: 409,
  REQUEST_FAILED: 409,
  // Lookups
  RECORD_NOT_FOUND: 404,
  // Infrastructure
  STORE_UNAVAILABLE: 503,
  CACHE_UNAVAILABLE: 503,
  // Should not happen; treat as a server error
  INVALID_CACHED_RESPONSE: 500
};

/**
 * Maps an `IdempotencyError` to the HTTP status it should be served with.
 */
export function idempotencyErrorStatus(
  error: IdempotencyError,
  statusMap?: Partial<Record<IdempotencyErrorCode, number>>
): number {
  return statusMap?.[error.code] ?? DEFAULT_STATUS_MAP[error.code] ?? 500;
}

/**
 * Builds the standard error envelope: `{ error: { code, message } }`.
 */
export function buildErrorEnvelope(error: IdempotencyError): {
  error: { code: string; message: string };
} {
  return { error: { code: error.code, message: error.message } };
}

Store contract

Your IdempotencyStore is the source of truth. It must implement:

interface IdempotencyStore {
  create(record: IdempotencyRecord): Promise<CreateRecordResult>;
  find(key: string, operation: string, userId: string): Promise<IdempotencyRecord | null>;
  findAll(filters?: FindAllFilters): Promise<IdempotencyRecord[]>;
  markSuccess(key: string, response: unknown, userId: string, operation: string): Promise<void>;
  markProcessing(key: string, operation: string, userId: string): Promise<void>;
  markFailed(key: string, operation: string, userId: string): Promise<void>;
  incrementRetryCount(key: string, operation: string, userId: string): Promise<number>;
  delete(key: string, operation: string, userId: string): Promise<void>;
  deleteExpired(params: DeleteExpiredParams): Promise<number>;
}

Requirements that the block depends on:

  1. create must be atomic. Use a unique constraint on (operation, userId, key) or an equivalent compare-and-set. If two inserts can both return CREATED, both requests will run your business logic.
  2. incrementRetryCount must survive record deletion. After a transient failure the handler deletes the row so the client can retry. If the counter lives on that row, it resets and the key is never poisoned.
  3. markSuccess and markFailed should only update a record that is still PROCESSING. Do not overwrite a completed success.
  4. deleteExpired must only delete SUCCESS and FAILED records. Active PROCESSING locks are handled by the recovery job.
  5. find must treat expired SUCCESS and FAILED records as absent, and create must be able to replace them. The handler does not check expiresAt before replaying a stored response. Do not hide or replace an expired PROCESSING record, because the original operation may still be running.
  6. Storage must be shared by every app instance. A per-process map cannot deduplicate requests across replicas.

The IdempotencyRecord passed to create uses camelCase fields:

type IdempotencyRecord = {
  key: string;
  userId: string;
  operation: string;
  requestHash: string;
  status: "PROCESSING" | "SUCCESS" | "FAILED";
  response?: unknown;
  expiresAt: Date;
  createdAt: Date;
  updatedAt: Date;
};

Map those fields to your schema. The internal record TTL is 24 hours. It is not configurable.

Configuration

Handler

const handler = new IdempotencyHandler(store, cache?, options?);
ArgumentTypeRequiredDescription
storeIdempotencyStoreYesPersistent, shared idempotency records.
cacheIdempotencyCacheNoFast replay path. Falls back to the store when unavailable.
loggerLoggerNoPino-shaped logger. Defaults to a no-op logger.
metricsMetricsNoMetrics sink. Defaults to a no-op sink.

Adapter options

Express, Fastify, and Hono use the same option names:

OptionTypeDefaultDescription
keyIdempotencyKeySourceIdempotency-Key headerAlso supports bodyField and queryParam.
requireKeybooleanfalseReject a missing key with 400 instead of running unprotected.
getUserId(request) => string | undefinedFramework user ID or "anonymous"Scopes the key to a user.
getOperation(request) => stringMethod and pathScopes the key to an operation.
getBody(request) => unknownRequest body or {}Payload hashed to detect key reuse with different input.
isPermanentError(error) => booleanEvery error is permanentDecides whether a failure poisons the key.
attachContextbooleantrueAttaches request context for observability.
statusMapPartial<Record<IdempotencyErrorCode, number>>Built-in mapOverrides HTTP status codes.

Fastify uses the registered route pattern for its default operation, so /payments/:id stays stable across IDs. Express and Hono use the concrete path by default. Set getOperation if you want identical behavior across frameworks.

The examples assume your auth layer declares req.user on Express, request.user on Fastify, and the user context variable on Hono.

Key validation

handler.validateKey(key) trims the key, checks its length, and checks the allowed characters.

const key = handler.validateKey("  order_123  "); // "order_123"

The default minimum is 1 character, the maximum is 128, and the allowed characters are letters, numbers, ., _, -, and :. Pass KeyValidationOptions to require a UUID or change the limits:

const key = handler.validateKey(rawKey, {
  minLength: 16,
  maxLength: 64,
  requireUuid: true
});

Adapters call handler.validateKey with the defaults. If you need per-route validation options, validate the key before calling the adapter or use the core directly.

Usage

Express wrapper

Use idempotent() when the route returns its response payload. The adapter sends the returned value with res.json.

import { idempotent } from "@/blocks/idempotency/adapters/express";

app.post(
  "/payments",
  idempotent(
    handler,
    async (req) => {
      const charge = await createCharge(req.body);
      return { id: charge.id, status: charge.status };
    },
    {
      requireKey: true,
      getUserId: (req) => req.user.id,
      getOperation: () => "payments:create",
      isPermanentError: (error) => error instanceof ValidationError
    }
  )
);

Express middleware

Use idempotencyMiddleware() when the route sends its own response with res.json or res.send.

import { idempotencyMiddleware } from "@/blocks/idempotency/adapters/express";

app.post(
  "/payments",
  idempotencyMiddleware(handler, {
    requireKey: true,
    getUserId: (req) => req.user.id
  }),
  async (req, res) => {
    const charge = await createCharge(req.body);
    res.status(201).json(charge);
  }
);

The middleware captures the body, but not the status code. A replay is sent with status 200. If clients depend on 201, return the status in the body or use a response shape that does not require the original status.

Fastify

The Fastify wrapper supports both return-style and reply.send() routes.

import { idempotent } from "@/blocks/idempotency/adapters/fastify";

app.post(
  "/payments",
  idempotent(
    handler,
    async (request) => {
      const charge = await createCharge(request.body);
      return { id: charge.id, status: charge.status };
    },
    {
      requireKey: true,
      getUserId: (request) => request.user.id
    }
  )
);

app.post(
  "/refunds",
  idempotent(handler, async (request, reply) => {
    reply.code(201).send(await createRefund(request.body));
  })
);

As with Express, only the payload is stored. A replay uses the adapter's default 200 response.

Hono

Hono has a wrapper and a capture middleware.

import { idempotent, idempotencyMiddleware } from "@/blocks/idempotency/adapters/hono";

app.post(
  "/payments",
  idempotent(
    handler,
    async (c) => {
      const charge = await createCharge(await c.req.json());
      return { id: charge.id, status: charge.status };
    },
    {
      requireKey: true,
      getUserId: (c) => c.get("user").id
    }
  )
);

app.post(
  "/refunds",
  idempotencyMiddleware(handler, {
    requireKey: true,
    getUserId: (c) => c.get("user").id
  }),
  async (c) => {
    const refund = await createRefund(await c.req.json());
    return c.json(refund, 201);
  }
);

The Hono middleware reads the request body from a clone, so the route can still call c.req.json().

Return a plain payload from the Hono wrapper when you need replay. A Response object does not serialize to useful JSON in a persistent store.

Core without an adapter

import { IdempotencyError, IdempotencyHandler } from "@/blocks/idempotency";
import { buildErrorEnvelope, idempotencyErrorStatus } from "@/blocks/idempotency/adapters/shared";

const handler = new IdempotencyHandler(store);

app.post("/payments", async (req, res, next) => {
  try {
    const key = handler.validateKey(req.get("Idempotency-Key"));
    const result = await handler.execute(
      req.user.id,
      "payments:create",
      key,
      req.body,
      () => createCharge(req.body),
      { isPermanentError: (error) => error instanceof ValidationError }
    );

    res.json(result);
  } catch (error) {
    if (error instanceof IdempotencyError) {
      res.status(idempotencyErrorStatus(error)).json(buildErrorEnvelope(error));
      return;
    }

    next(error);
  }
});

validateKey throws KEY_INVALID_TYPE for a missing or non-string value, and KEY_REQUIRED for an empty or whitespace-only string. Use an adapter with requireKey: true for the same behavior with less code.

What gets stored

The block stores the return value of your route as JSON. It does not store the HTTP status code or response headers.

Return a value from wrapper-style routes. A stored undefined response leaves Fastify with nothing to send, and adapters differ in how they handle an empty replay.

The request body is hashed with a deterministic serializer. Values such as undefined, NaN, Infinity, BigInt, functions, and symbols cannot be serialized and will fail. The adapters use {} when the request has no body, so a missing body hashes as an empty object. Pass only JSON-compatible data, or provide getBody that returns a stable subset of the body.

getBody also controls key reuse detection. Do not include fields that change on every retry, such as timestamps or trace IDs:

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

Failure behavior

SituationResult
Missing key, requireKey: falseRoute runs without idempotency protection.
Missing key, requireKey: true400 KEY_REQUIRED.
Same key and same payloadStored result is returned.
Same key and different payload409 KEY_REUSED_WITH_DIFFERENT_REQUEST.
Same key while the first request runs409 REQUEST_IN_PROGRESS.
Same key after a permanent failure409 REQUEST_FAILED.
Store throws503 STORE_UNAVAILABLE.
Cache throwsRequest continues against the store.

isPermanentError defaults to true for every error. If you do not set it, one transient database error marks the key FAILED, and every retry returns 409 until cleanup deletes the record after 24 hours. Set it on every protected route.

A transient failure deletes the lock so the client can retry. The retry counter increments, and the third transient failure marks the key FAILED.

Background jobs

Run both jobs on a schedule. They are methods on the handler and also standalone exports.

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

const handler = new IdempotencyHandler(store);

// Mark locks older than 5 minutes as failed.
await handler.recoverStuckRecords({ timeoutInMs: 5 * 60 * 1000, limit: 100 });

// Delete expired SUCCESS and FAILED records.
await handler.cleanupExpiredRecords({ limit: 500 });

recoverStuckRecords does not retry the operation. It marks abandoned PROCESSING records FAILED. A client retry with the same key then returns 409 REQUEST_FAILED. To run the operation again, use a new idempotency key or delete the record through your store. The public retry method only changes a FAILED record to PROCESSING; it does not execute the operation, and execute treats the key as in progress after that change.

If a legitimate operation can run longer than timeoutInMs, either raise the timeout or update the record's updatedAt through your store while the operation runs. Otherwise recovery can mark a live operation as failed, and a client can run it again with a new key.

cleanupExpiredRecords asks the store to delete at most limit records per run, default 500. The store must honor the limit. It never deletes PROCESSING records.

Errors

Import error codes and the error class from the root:

import { IDEMPOTENCY_ERROR_CODES, IdempotencyError } from "@/blocks/idempotency";

Default HTTP mapping is in adapters/shared:

CodeStatus
KEY_INVALID_TYPE, KEY_REQUIRED, KEY_TOO_SHORT, KEY_TOO_LONG, KEY_INVALID_FORMAT, UNSUPPORTED_REQUEST_VALUE400
KEY_REUSED_WITH_DIFFERENT_REQUEST, REQUEST_IN_PROGRESS, REQUEST_FAILED409
RECORD_NOT_FOUND404
STORE_UNAVAILABLE, CACHE_UNAVAILABLE503
INVALID_CACHED_RESPONSE500

Override a code per route with statusMap.

Observability

IdempotencyHandler accepts a logger and metrics sink. The logger interface is duck-typed:

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

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

Metrics names:

  • idempotency_cache_hits_total
  • idempotency_cache_misses_total
  • idempotency_duplicates_total
  • idempotency_store_errors_total
  • idempotency_recovered_records_total
  • idempotency_cleaned_records_total
  • idempotency_latency_seconds

The adapters attach context to each request when attachContext is true:

FrameworkLocation
Expressres.locals.idempotency
Fastifyrequest.idempotency
HonogetIdempotencyContext(c) from the Hono adapter

The Hono context key is blockend.idempotency. Read it with getIdempotencyContext(c), not c.get("idempotency").

API reference

IdempotencyHandler

class IdempotencyHandler {
  constructor(
    store: IdempotencyStore,
    cache?: IdempotencyCache,
    options?: { logger?: Logger; metrics?: Metrics }
  );

  execute(
    userId: string,
    operation: string,
    key: string,
    body: unknown,
    run: () => Promise<unknown>,
    options?: { isPermanentError?: (error: unknown) => boolean }
  ): Promise<unknown>;

  validateKey(key: unknown, options?: KeyValidationOptions): string;

  static serialize(value: unknown): string;
  hashRequest(body: unknown): string;

  retry(userId: string, operation: string, key: string): Promise<IdempotencyRecord | null>;

  cleanupExpiredRecords(options?: { limit?: number }): Promise<{ deleted: number }>;
  recoverStuckRecords(options?: {
    timeoutInMs?: number;
    limit?: number;
  }): Promise<{ processed: number; succeeded: number; failed: number }>;
}

retry changes a FAILED record to PROCESSING and does not execute the operation. A SUCCESS record is returned unchanged. A PROCESSING record throws REQUEST_IN_PROGRESS. After retry returns, execute also rejects the key as in progress, so use it only in a custom workflow that completes or releases the record through the store.

Adapter exports

ModuleExports
adapters/expressidempotent, idempotencyMiddleware, getIdempotencyKey, sendIdempotencyError, idempotencyErrorStatus
adapters/fastifyidempotent, getIdempotencyKey
adapters/honoidempotent, idempotencyMiddleware, getIdempotencyKey, getIdempotencyContext, readJsonBody
adapters/sharedDEFAULT_STATUS_MAP, idempotencyErrorStatus, buildErrorEnvelope

getIdempotencyKey is synchronous in Express and Fastify. In Hono it returns a promise because it may read the cloned body.

When not to use it

  • Read-only endpoints. There is nothing to deduplicate.
  • Operations that cannot tolerate a 24 hour key lifetime and have retry windows longer than that.
  • Systems that need exactly-once across multiple services. This block provides a single-store guarantee, not a distributed transaction.
  • Stores without atomic create. Two concurrent requests can both acquire the lock.

On this page