Rate limiting says: “you’re sending too many requests, slow down.” The well-behaved client responds by retrying. Idempotency keys say: “you already sent this one, here’s what happened.” Without the second, the first one creates duplicate charges, duplicate orders, duplicate emails ; because you told the client to retry and then punished it for doing so.

Ship them together or don’t bother.

Rate limiting and idempotency keys in Node.js

This post builds both in Express with TypeScript: a GCRA rate limiter as one Redis Lua script, layered policies, the IETF RateLimit headers and an Idempotency-Key ledger in Postgres, plus the reaper that handles a process dying mid-payment. It’s part seven of the series on securing a Node.js API. The limiter keys on the identity set up in part three, on JWT access and refresh tokens.

Quick answer

Rate limiting: use GCRA (or a sliding window counter) in a single Redis Lua script, so the read and the write can’t race. Don’t charge rejected requests against the quota. Key on a verified API key or user ID, fall back to IP with trust proxy set to your real proxy count, and bucket IPv6 by /64. Send RateLimit headers on every response and an honest Retry-After on 429.

Idempotency: the client sends a UUID in Idempotency-Key and reuses it on every retry. The server claims the key atomically, returns 409 while the first request is still running, replays the stored response once it finishes and releases the key on 5xx. Keep the record in the same database as the business write, and reconcile records orphaned by a crash.

Rate limiting algorithms compared

Algorithm Storage per client Boundary burst Exact Retry-After Use it for
Fixed window 1 counter Up to 2× the limit No Coarse daily quotas
Sliding window log 1 entry per request None Yes Low limits where cost doesn’t matter
Sliding window counter 2 counters Small, interpolated Approximate Most APIs
GCRA / token bucket 1 timestamp None Yes APIs that allow short bursts

Fixed window

Count requests per calendar minute. One Redis INCR with a TTL.

Simple, and broken at the boundary: with a limit of 100/minute, a client can send 100 at 11:00:59 and 100 more at 11:01:00. 200 requests in one second, fully within the limit. For protecting a database from a burst, this is exactly the failure you were trying to prevent.

Fine for coarse quotas (“10,000 API calls a day”). Bad for protecting capacity.

Sliding window log

Store a timestamp per request in a sorted set, drop old ones, count what’s left. Perfectly accurate.

Also stores one Redis entry per request. A limit of 10,000/hour means 10,000 members in a sorted set per client. At 50,000 clients that’s 500 million members. Accurate and unaffordable.

Sliding window counter

The pragmatic middle. Keep the current window’s count and the previous window’s, and interpolate:

estimate = currentCount + previousCount * (fraction of previous window still in view)

Two integers per client. Accuracy within a percent or two for real traffic. This is what most APIs should use, and what Cloudflare uses.

GCRA / token bucket

Instead of counting, track a single timestamp: the theoretical arrival time of the next permitted request. Each request pushes it forward by the emission interval. If it’s too far in the future, reject.

One value per client. Smooth ; no window boundaries at all ; and it gives you controlled burst capacity for free. It also tells you exactly how long to wait, which makes for an honest Retry-After.

Slightly harder to explain to a colleague. Worth it.

The GCRA script in Redis Lua

lua
-- src/ratelimit/scripts/gcra.lua
-- Generic Cell Rate Algorithm ;  a leaky bucket that stores one number.
--
-- KEYS[1] = client key
-- ARGV[1] = emission interval in ms (1000 / rate)
-- ARGV[2] = burst tolerance in ms (emission_interval * burst_size)
-- ARGV[3] = cost of this request (usually 1, higher for expensive endpoints)
--
-- Returns: { allowed (0|1), retry_after_ms, remaining_burst, reset_ms }

local emission   = tonumber(ARGV[1])
local tolerance  = tonumber(ARGV[2])
local cost       = tonumber(ARGV[3])

-- Use Redis's clock, not each app server's. Three Node processes with
-- clocks 300 ms apart will otherwise disagree about who is allowed.
local t   = redis.call("TIME")
local now = tonumber(t[1]) * 1000 + math.floor(tonumber(t[2]) / 1000)

local increment  = emission * cost

-- TAT = "theoretical arrival time" of the next conforming request.
local tat = tonumber(redis.call("GET", KEYS[1]))
if tat == nil or tat < now then
  tat = now
end

local new_tat     = tat + increment
local allow_after = new_tat - tolerance

if allow_after > now then
  -- Too early. Reject WITHOUT advancing the TAT ;  a rejected request
  -- must not consume quota, or a client in a retry loop can lock
  -- itself out permanently.
  return { 0, math.ceil(allow_after - now), 0, math.ceil(tat - now) }
end

-- Expire slightly after the bucket would fully drain, so idle clients
-- don't occupy memory forever.
local ttl = math.ceil((new_tat - now + tolerance) / 1000) + 1
redis.call("SET", KEYS[1], new_tat, "EX", ttl)

local remaining = math.floor((now - (new_tat - tolerance)) / emission)
return { 1, 0, math.max(0, remaining), math.ceil(new_tat - now) }

The comment on the rejection path is the important one. Plenty of limiters increment the counter on rejected requests, which means a client hammering you can never recover ; every retry pushes its own unlock further away.

redis.call("TIME") inside a script needs Redis 5 or later, where scripts replicate their effects rather than the script itself. On anything older, pass the time in from Node and accept the clock skew.

Why it must be one Lua script

GET, compute, SET from Node is a read-modify-write race. Under concurrency, N requests all read the same value and all decide they’re allowed. Your limit of 100 admits 340.

MULTI/EXEC doesn’t fix it either ; Redis transactions aren’t interactive, so you can’t branch on a value you read inside one. You’d need WATCH and a retry loop, and now you’ve built a slower Lua script with more failure modes.

Lua on Redis is atomic because Redis runs commands on a single thread. The whole script runs to completion with nothing interleaved. That’s the guarantee you need, without a lock in sight.

The rate limiter class

ts
// src/ratelimit/limiter.ts
import type { Redis, Result } from 'ioredis';
import { readFileSync } from 'node:fs';

const GCRA = readFileSync(new URL('./scripts/gcra.lua', import.meta.url), 'utf8');

// Tell TypeScript about the command defineCommand adds at runtime.
declare module 'ioredis' {
  interface RedisCommander<Context> {
    gcra(
      key: string,
      emissionMs: string,
      toleranceMs: string,
      cost: string,
    ): Result<[number, number, number, number], Context>;
  }
}

export interface RateLimitPolicy {
  /** Human-readable policy name, surfaced in headers. */
  readonly name: string;
  /** Sustained requests per second. */
  readonly rate: number;
  /** How many requests may arrive back-to-back before throttling. */
  readonly burst: number;
}

export interface RateLimitDecision {
  readonly allowed: boolean;
  readonly retryAfterMs: number;
  readonly remaining: number;
  readonly resetMs: number;
  readonly policy: RateLimitPolicy;
}

export class RateLimiter {
  constructor(private readonly redis: Redis) {
    this.redis.defineCommand('gcra', { numberOfKeys: 1, lua: GCRA });
  }

  async check(
    key: string,
    policy: RateLimitPolicy,
    cost = 1,
  ): Promise<RateLimitDecision> {
    const emission = 1_000 / policy.rate;

    try {
      const [allowed, retryAfterMs, remaining, resetMs] = await this.redis.gcra(
        `rl:${policy.name}:${key}`,
        String(emission),
        String(emission * policy.burst),
        String(cost),
      );

      return { allowed: allowed === 1, retryAfterMs, remaining, resetMs, policy };
    } catch (err) {
      // FAIL OPEN. If Redis is down, a rate limiter that rejects
      // everything has converted a cache outage into a full outage.
      // Log it loudly ;  a silently-open limiter is worse than none.
      logger.error({ err, key }, 'rate limiter unavailable, failing open');
      metrics.increment('ratelimit.fail_open');
      return { allowed: true, retryAfterMs: 0, remaining: 0, resetMs: 0, policy };
    }
  }
}

Fail open or fail closed? For public APIs protecting shared capacity: fail open, and alert. An outage in your limiter shouldn’t take down your API. For a limiter guarding something dangerous: login attempts, password resets, payment initiation - fail closed. Getting brute-forced during a Redis outage is worse than a few minutes of 503s. Decide per endpoint, not globally.

Choosing the rate limit key

The key is where rate limiters break in production, and it has nothing to do with algorithms.

ts
// src/ratelimit/key.ts
import type { Request } from 'express';

export function rateLimitKey(req: Request): string {
  // Only use identities that auth middleware has already verified.
  // Hashing the raw Authorization header looks equivalent, but it lets
  // anyone mint a fresh bucket per request by sending a random token.
  if (req.apiKey?.id) return `key:${req.apiKey.id}`;
  if (req.user?.id) return `user:${req.user.id}`;

  // Falling back to IP. Two serious caveats below.
  return `ip:${clientIp(req)}`;
}

Caveat 1: req.ip lies unless you configure trust proxy

Behind a load balancer, every request appears to come from the LB. Without trust proxy, you rate limit the entire internet as one client. With trust proxy: true; trusting all proxies; anyone can send X-Forwarded-For: 1.2.3.4 and impersonate a different bucket, or rotate through a million fake IPs and never hit a limit.

Set it to the number of proxies you actually run:

ts
// One LB in front of the app: trust exactly one hop.
app.set('trust proxy', 1);

Caveat 2: IPv6

A single customer typically gets a /64 ; that’s 18 quintillion addresses. Limiting per exact IPv6 address means a limit of one request per address, forever, for free. Bucket IPv6 by /64:

ts
// src/ratelimit/key.ts (continued)
import { isIPv6 } from 'node:net';

function clientIp(req: Request): string {
  let ip = req.ip ?? '0.0.0.0';

  // On a dual-stack socket an IPv4 client arrives as ::ffff:203.0.113.7.
  // Skip this and every IPv4 user collapses into one shared /64 bucket.
  if (ip.startsWith('::ffff:')) ip = ip.slice(7);
  if (!isIPv6(ip)) return ip;

  // Collapse to the /64 prefix ;  the smallest unit typically assigned
  // to one subscriber. Per-address limiting on IPv6 is not limiting.
  const expanded = expandIPv6(ip);
  return expanded.split(':').slice(0, 4).join(':') + '::/64';
}

I have watched a team spend a week on “the rate limiter isn’t working” that was entirely this.

Layered rate limit policies

One limit is never enough. You want a burst limit protecting per-second capacity and a quota limit protecting daily cost, plus a much tighter limit on expensive endpoints.

ts
// src/ratelimit/policies.ts
export const POLICIES = {
  burst:  { name: 'burst',  rate: 20,      burst: 40   },   // 20/s, tolerate 40
  hourly: { name: 'hourly', rate: 1000 / 3600, burst: 1000 }, // 1000/hour
  expensiveWrite: { name: 'write', rate: 1, burst: 5 },
} as const satisfies Record<string, RateLimitPolicy>;
ts
// src/ratelimit/middleware.ts
import type { RequestHandler } from 'express';
import { RateLimiter, type RateLimitPolicy } from './limiter.js';
import { rateLimitKey } from './key.js';
import { setRateLimitHeaders } from './headers.js';

export function rateLimit(
  limiter: RateLimiter,
  policies: readonly RateLimitPolicy[],
  options: { cost?: number } = {},
): RequestHandler {
  return async (req, res, next) => {
    const key = rateLimitKey(req);
    const decisions = await Promise.all(
      policies.map((p) => limiter.check(key, p, options.cost ?? 1)),
    );

    setRateLimitHeaders(res, decisions);

    const rejected = decisions.find((d) => !d.allowed);
    if (!rejected) return next();

    metrics.increment('ratelimit.rejected', { policy: rejected.policy.name });

    res.setHeader('Retry-After', Math.ceil(rejected.retryAfterMs / 1000));
    res.status(429).json({
      type: 'https://example.com/errors/rate-limited',
      title: 'Too Many Requests',
      status: 429,
      detail: `Exceeded the ${rejected.policy.name} policy.`,
      retryAfterMs: rejected.retryAfterMs,
    });
  };
}

Each policy check is atomic. The set of checks isn’t. A request rejected by the hourly policy has still spent a token from the burst policy, whether you run the checks with Promise.all or one after another. For most APIs that leak is small enough to ignore, and Promise.all keeps it to one round trip of latency. If it matters, pass every policy’s key to one script and only write the new TATs when all of them pass.

RateLimit headers (IETF draft)

The IETF httpapi working group is standardising these headers in draft-ietf-httpapi-ratelimit-headers. Revision 11, from May 2026, is still an Internet-Draft, not an RFC.

Two things changed from what you probably remember. The draft now defines two fields, RateLimit and RateLimit-Policy, instead of the three separate headers from earlier revisions, though RateLimit-Limit, RateLimit-Remaining and RateLimit-Reset are still what most clients read. And both new fields use Structured Fields syntax. A policy is a named item with parameters: q for quota and w for the window in seconds, as in RateLimit-Policy: "sliding";q=12;w=1. The companion RateLimit: "sliding";r=12;t=1 reports remaining quota and seconds to reset.

While it’s a draft, emit both forms:

ts
// src/ratelimit/headers.ts
import type { Response } from 'express';
import type { RateLimitDecision } from './limiter.js';

export function setRateLimitHeaders(
  res: Response,
  decisions: readonly RateLimitDecision[],
): void {
  if (decisions.length === 0) return;

  // Structured-field form, per the current IETF draft.
  // q = quota, w = window seconds, r = remaining, t = seconds to reset.
  const policyField = decisions
    .map((d) => `"${d.policy.name}";q=${d.policy.burst};w=${windowSeconds(d.policy)}`)
    .join(', ');

  // t is time until the bucket is full again, not retry-after ; 
  // retry-after is 0 on every allowed request, which would tell
  // clients their quota resets instantly.
  const rateLimitField = decisions
    .map((d) => `"${d.policy.name}";r=${d.remaining};t=${Math.ceil(d.resetMs / 1000)}`)
    .join(', ');

  res.setHeader('RateLimit-Policy', policyField);
  res.setHeader('RateLimit', rateLimitField);

  // De facto legacy form, keyed to the tightest policy. Still what
  // most client SDKs actually read. Cheap to keep; drop it when the
  // draft becomes an RFC and your clients have caught up.
  const tightest = decisions.reduce((a, b) => (a.remaining <= b.remaining ? a : b));
  res.setHeader('RateLimit-Limit', String(tightest.policy.burst));
  res.setHeader('RateLimit-Remaining', String(tightest.remaining));
  res.setHeader('RateLimit-Reset', String(Math.ceil(tightest.resetMs / 1000)));
}

const windowSeconds = (p: { rate: number; burst: number }) =>
  Math.ceil(p.burst / p.rate);

Always send these on successful responses too. Headers only on 429 mean a client learns its limit exclusively by exceeding it. Sending them always lets a well-written client throttle itself before you have to.

What idempotency keys solve

Client → POST /payments {amount: 5000}
Server → charges the card ✅
       → 200 OK ────────────✂️─── connection dies here
Client → sees a timeout. Retries.
Server → charges the card AGAIN ❌

The client cannot distinguish “request never arrived” from “response never arrived.” From its side both look identical. It has two options: retry and risk a double charge, or don’t retry and risk a lost payment.

An idempotency key gives it a third: retry safely. The client generates a UUID, sends it with the request, and reuses it on every retry. The server recognises the repeat and returns the original outcome instead of doing the work again.

The header is specified in draft-ietf-httpapi-idempotency-key-header, which defines Idempotency-Key as a way to make non-idempotent methods like POST and PATCH fault-tolerant. It is also still an Internet-Draft, but Stripe, PayPal, Adyen and Square all ship the pattern, so the header name is settled in practice.

The idempotency state machine

Storing “key → response” only handles the case where the first request finished. The interesting case is the one where the retry arrives while the original is still running ; which is the common case, because the client retried on timeout, and a timeout usually means the request is slow, not dead.

Three states:

                  ┌──────────────┐
   first request  │              │
  ───────────────▶│  IN_FLIGHT   │
                  │              │
                  └──────┬───────┘
                         │
         ┌───────────────┴───────────────┐
         ▼                               ▼
   ┌───────────┐                   ┌───────────┐
   │ COMPLETED │                   │  FAILED   │
   │  replay   │                   │  allow    │
   │  response │                   │  retry    │
   └───────────┘                   └───────────┘
  • IN_FLIGHT and a duplicate arrives → 409 Conflict. Not 200; you don’t have a result yet, and inventing one is worse than an honest conflict.
  • COMPLETED → replay the stored status, body and headers verbatim.
  • FAILED with a retryable error → clear the record and let the retry through. A 500 shouldn’t be permanently cached against that key. (FAILED is never stored; deleting the row is the transition.)

Storing idempotency keys in Postgres

Postgres, not Redis. This record is the reason the payment isn’t duplicated ; it needs to survive a Redis restart, and it needs to participate in your transaction.

sql
-- migrations/001_idempotency.sql
CREATE TYPE idempotency_state AS ENUM ('in_flight', 'completed');

CREATE TABLE idempotency_records (
  -- Scope the key to the caller. Two tenants using the same UUID must
  -- not collide, and one tenant must not be able to probe another's keys.
  tenant_id        UUID          NOT NULL,
  idempotency_key  TEXT          NOT NULL,

  state            idempotency_state NOT NULL,

  -- Fingerprint of method + path + body. If a client reuses a key with
  -- DIFFERENT parameters, that is a client bug and must be rejected,
  -- not silently served the old response.
  request_fingerprint TEXT       NOT NULL,

  response_status  SMALLINT,
  response_body    JSONB,
  response_headers JSONB,

  created_at       TIMESTAMPTZ   NOT NULL DEFAULT now(),
  completed_at     TIMESTAMPTZ,
  expires_at       TIMESTAMPTZ   NOT NULL,

  PRIMARY KEY (tenant_id, idempotency_key)
);

-- Reaping expired records. Partial index keeps it small.
CREATE INDEX idempotency_expiry_idx
  ON idempotency_records (expires_at)
  WHERE state = 'completed';

Idempotency middleware for Express

ts
// src/idempotency/middleware.ts
import type { RequestHandler, Response } from 'express';
import { createHash } from 'node:crypto';
import type { Pool } from 'pg';

const RETENTION_HOURS = 24;

/**
 * A key reused with different parameters is a client bug. Fingerprinting
 * the request lets us return 422 instead of quietly replaying a response
 * for an operation the client didn't ask for.
 */
function fingerprint(req: { method: string; path: string; body: unknown }): string {
  return createHash('sha256')
    .update(req.method)
    .update('\0')
    .update(req.path)
    .update('\0')
    .update(stableStringify(req.body))
    .digest('hex');
}

export function idempotency(pool: Pool): RequestHandler {
  return async (req, res, next) => {
    // Only for methods that aren't already idempotent by definition.
    if (!['POST', 'PATCH'].includes(req.method)) return next();

    const key = req.get('Idempotency-Key');
    if (!key) {
      // Optional or mandatory is a per-endpoint decision. For anything
      // that moves money, make it mandatory ;  a client that doesn't
      // send one cannot retry safely and will eventually double-charge.
      return next();
    }
    if (key.length > 255) {
      return res.status(400).json({ title: 'Idempotency-Key too long' });
    }

    // Assumes auth middleware ran first and set req.user.
    const tenantId = req.user!.tenantId;
    const fp = fingerprint(req);

    // Atomic claim. INSERT ... ON CONFLICT DO NOTHING RETURNING gives
    // us "did we win the race" in one round trip, with no read-then-write
    // window for a concurrent retry to slip through.
    const claim = await pool.query(
      `INSERT INTO idempotency_records
         (tenant_id, idempotency_key, state, request_fingerprint, expires_at)
       VALUES ($1, $2, 'in_flight', $3, now() + make_interval(hours => $4))
       ON CONFLICT (tenant_id, idempotency_key) DO NOTHING
       RETURNING idempotency_key`,
      [tenantId, key, fp, RETENTION_HOURS],
    );

    if (claim.rowCount === 0) {
      return replayOrConflict(pool, res, tenantId, key, fp);
    }

    // We own this key. Capture the response so we can store it.
    captureResponse(res, async (status, body, headers) => {
      if (status >= 500) {
        // Server errors are transient by assumption. Release the key so
        // the client's retry gets a genuine second attempt rather than a
        // permanently cached 500.
        await pool.query(
          'DELETE FROM idempotency_records WHERE tenant_id = $1 AND idempotency_key = $2',
          [tenantId, key],
        );
        return;
      }

      // 2xx and 4xx are both real outcomes worth replaying. A 422 for
      // invalid input will be a 422 again; no reason to redo the work.
      await pool.query(
        `UPDATE idempotency_records
            SET state = 'completed',
                response_status = $3,
                response_body = $4,
                response_headers = $5,
                completed_at = now()
          WHERE tenant_id = $1 AND idempotency_key = $2`,
        [tenantId, key, status, JSON.stringify(body), JSON.stringify(headers)],
      );
    });

    next();
  };
}

async function replayOrConflict(
  pool: Pool,
  res: Response,
  tenantId: string,
  key: string,
  fingerprint: string,
) {
  const { rows } = await pool.query(
    `SELECT state, request_fingerprint, response_status, response_body, response_headers
       FROM idempotency_records
      WHERE tenant_id = $1 AND idempotency_key = $2`,
    [tenantId, key],
  );

  // Lost the INSERT race, then the row vanished (a 5xx cleanup). Rare.
  if (rows.length === 0) {
    return res.status(409).json({
      title: 'Conflict',
      detail: 'Request is being processed. Retry shortly.',
    });
  }

  const record = rows[0];

  if (record.request_fingerprint !== fingerprint) {
    return res.status(422).json({
      title: 'Idempotency-Key reuse with different parameters',
      detail: 'This key was already used for a different request body.',
    });
  }

  if (record.state === 'in_flight') {
    res.setHeader('Retry-After', '1');
    return res.status(409).json({
      title: 'Conflict',
      detail: 'A request with this Idempotency-Key is currently in progress.',
    });
  }

  // Completed ;  replay verbatim.
  res.setHeader('Idempotency-Replayed', 'true');
  for (const [name, value] of Object.entries(record.response_headers ?? {})) {
    if (!isHopByHop(name)) res.setHeader(name, value as string);
  }
  return res.status(record.response_status).json(record.response_body);
}

Idempotency-Replayed isn’t in the draft. It’s a convention, borrowed from Stripe, which sends Idempotent-Replayed: true. Pick one name and document it.

The crash window after the side effect

Everything above still has a window. Consider:

1. INSERT idempotency record (in_flight)  ✅ committed
2. Charge the card                        ✅ succeeded
3. Process crashes ☠️
4. UPDATE record to completed             ❌ never happened

The record is stuck in_flight forever. Every retry gets 409. The card was charged and the client has no way to learn that.

Two real fixes.

Option A: one transaction

If the side effect is a database write, do it in the same transaction as the idempotency record. Then step 2 and step 4 commit or roll back together, and the window disappears entirely.

The transaction has to run on one connection. pool.query('BEGIN') checks out a client, runs BEGIN and hands the client back, so the next pool.query may land on a different connection outside your transaction. Check one out yourself:

ts
const client = await pool.connect();
try {
  await client.query('BEGIN');

  const claimed = await claimKey(client, tenantId, key, fp);
  if (!claimed) {
    await client.query('ROLLBACK');
    return replayOrConflict(pool, res, tenantId, key, fp);
  }

  const payment = await createPayment(client, req.body);   // the real work
  await completeKey(client, tenantId, key, 201, payment);  // the record

  await client.query('COMMIT');
  return res.status(201).json(payment);
} catch (err) {
  await client.query('ROLLBACK');
  throw err;
} finally {
  client.release();
}

Nothing short of this closes the window, and it’s why the idempotency record lives in the same database as your business data. Putting it in Redis makes this impossible.

It also changes how duplicates behave. The claim row isn’t committed until the end, so a concurrent retry’s INSERT ... ON CONFLICT waits on the unique index until the first transaction finishes, then finds a completed record and replays it. No 409 on this path, at the cost of one held connection per waiting retry.

Option B: when the effect is external

You can’t put a Stripe API call in a Postgres transaction. So: reap stale in_flight records after a timeout, and on reap, reconcile ; ask the provider whether the operation actually happened, using the same key.

ts
// src/idempotency/reaper.ts

/**
 * Records stuck in_flight past the timeout mean a process died mid-request.
 * We cannot assume the side effect didn't happen. Reconcile against the
 * provider before releasing the key ;  releasing blindly is how you get
 * the double charge you built this whole system to prevent.
 */
export async function reapStaleRecords(pool: Pool, provider: PaymentProvider) {
  const client = await pool.connect();
  try {
    // Row locks only last as long as the transaction holding them.
    await client.query('BEGIN');

    const { rows } = await client.query(
      `SELECT tenant_id, idempotency_key
         FROM idempotency_records
        WHERE state = 'in_flight'
          AND created_at < now() - interval '5 minutes'
        LIMIT 20
        FOR UPDATE SKIP LOCKED`,
    );

    for (const row of rows) {
      const existing = await provider.lookupByIdempotencyKey(row.idempotency_key);

      if (existing) {
        await markCompleted(client, row, 201, existing);
        logger.warn({ key: row.idempotency_key }, 'reconciled orphaned request');
      } else {
        await deleteRecord(client, row);
      }
    }

    await client.query('COMMIT');
  } catch (err) {
    await client.query('ROLLBACK');
    throw err;
  } finally {
    client.release();
  }
}

FOR UPDATE SKIP LOCKED is doing real work there ; it lets multiple reaper instances run concurrently without processing the same row twice. But only inside a transaction. Run that SELECT through pool.query and it autocommits. The locks are gone before the loop starts, and two reapers reconcile the same rows.

The five-minute timeout has to be longer than your slowest legitimate request, provider timeouts included. Reap a request that is still running and the provider lookup finds nothing yet. The key is released, and the client’s next retry charges the card a second time.

Most implementations skip the reaper because the orphaned record never shows up in testing. It shows up months later, as a stuck payment nobody can explain.

Wiring both together

ts
// src/app.ts
import express from 'express';
import { rateLimit } from './ratelimit/middleware.js';
import { idempotency } from './idempotency/middleware.js';
import { POLICIES } from './ratelimit/policies.js';

const app = express();
app.set('trust proxy', 1);
app.use(express.json({ limit: '1mb' }));

// Verifies credentials and sets req.user / req.apiKey. Runs before the
// limiter so buckets are keyed on verified identities only.
app.use(authenticate);

// Global: every request, cheap policies.
app.use(rateLimit(limiter, [POLICIES.burst, POLICIES.hourly]));

// Expensive endpoints: tighter limit AND idempotency, in that order.
// Rate limiting first ;  no point claiming an idempotency key for a
// request you're about to reject.
app.post(
  '/payments',
  rateLimit(limiter, [POLICIES.expensiveWrite], { cost: 5 }),
  idempotency(pool),
  createPaymentHandler,
);

The ordering comment matters. Idempotency before rate limiting means a rejected request has already inserted a record, and the client’s legitimate retry with the same key hits 409 instead of being processed.

If authenticate hits the database on every call, put a cheap IP-only limiter in front of it. Otherwise a flood of bad tokens reaches your auth store before any limit applies.

Production checklist

Rate limiting

  • Decision is atomic ; Lua script, not read-modify-write
  • Rejected requests don’t consume quota
  • Buckets keyed on verified identities, never on a raw token
  • trust proxy set to your actual proxy count, not true
  • IPv6 bucketed by /64, and ::ffff: IPv4 addresses unwrapped first
  • Layered policies (burst + quota + per-endpoint)
  • Fail-open decided per endpoint, and alerted on
  • Headers on every response, not just 429
  • Retry-After present and honest
  • Rejection rate graphed per policy ; a limit nobody hits does nothing, and a limit everybody hits is an outage

Idempotency

  • Key scoped to tenant
  • Atomic claim via INSERT ... ON CONFLICT DO NOTHING
  • Concurrent duplicate returns 409, not a fabricated success
  • Fingerprint check catches key reuse with different bodies
  • 5xx releases the key; 2xx/4xx are stored
  • Same transaction as the business write, on one checked-out connection, where possible
  • Reaper with provider reconciliation, inside a transaction, where not
  • Reaper timeout longer than your slowest request
  • Expiry ≥ your client SDK’s longest retry window
  • Idempotency-Replayed header so clients can tell

The two lists are one system. A rate limiter without idempotency tells clients to retry into an API that can’t handle retries. Idempotency without rate limiting handles retries from clients that have no idea when to send them.

Frequently Asked Questions

Which rate limiting algorithm should a Node.js API use? GCRA or a sliding window counter. Both store one or two values per client and have no boundary burst. Use a fixed window only for coarse daily quotas.

Can I rate limit in memory instead of Redis? Only on a single process. With four instances behind a load balancer, an in-memory limit of 100 becomes roughly 400, and it resets on every deploy.

Should a rate limiter fail open or fail closed? Fail open, with an alert, for limits that protect capacity. Fail closed for login, password reset and payment initiation, where a Redis outage shouldn’t open the door to brute force.

What status code should a duplicate idempotency key return? 409 Conflict while the original is still in flight, 422 if the key is reused with a different body, and the original stored response once it has completed.

How long should idempotency keys be kept? At least as long as your clients’ longest retry window. 24 hours is the common default; Stripe prunes keys once they’re at least 24 hours old.

Do GET, PUT and DELETE need idempotency keys? No. They’re idempotent by definition in HTTP. Keys matter for POST and PATCH, where repeating the request repeats the effect.

Can idempotency keys live in Redis? Only if you accept losing them on a Redis restart and never need them in the same transaction as the business write. For payments, keep them in the primary database.