# Rate Limiting, Idempotency Keys, Pagination and Error Contracts for APIs

> Rate limiting algorithms, idempotency keys, cursor pagination, RFC 9457 errors, versioning and conventions that suit both developers and AI agents.

Source: https://www.derar.dev/blog/api-rate-limiting-idempotency-pagination-design-2026 · Published 2026-11-08 · Updated 2026-11-14 · By Derar Sattouf

An API is a contract that outlives its implementation. The difference between an API developers love and one they tolerate lies in a handful of unglamorous decisions: what happens when a client retries a request, how list endpoints behave when data changes underneath them, what an error actually tells you, and how the server defends itself when clients misbehave.

There's an extra reason to care in 2026. A growing share of API traffic comes from AI agents and automated tools that retry aggressively, parse errors literally and follow documented conventions precisely. An API that's consistent, self-describing and safe to retry works for people and machines alike. The code below is TypeScript and SQL.

## Rate limiting

Rate limits protect availability, fairness and cost. They're a capacity-planning tool as much as an abuse control.

### Choose the algorithm

| Algorithm | Behavior | Notes |
| --- | --- | --- |
| Fixed window | N requests per calendar window | Simple; allows 2x bursts at window boundaries |
| Sliding window log | Exact count over last N seconds | Accurate; memory-heavy |
| Sliding window counter | Weighted blend of two windows | Good accuracy, low cost |
| **Token bucket** | Tokens refill at rate r, bucket holds b | Allows controlled bursts; the common default |
| Leaky bucket | Constant outflow | Smooths traffic; queueing semantics |
| Concurrency limit | Max N in-flight requests | Protects expensive endpoints |

### Token bucket in Redis (atomic via Lua)

```ts
const SCRIPT = `
local key      = KEYS[1]
local rate     = tonumber(ARGV[1])   -- tokens per second
local capacity = tonumber(ARGV[2])
local now      = tonumber(ARGV[3])   -- ms
local cost     = tonumber(ARGV[4])

local data   = redis.call("HMGET", key, "tokens", "ts")
local tokens = tonumber(data[1]) or capacity
local ts     = tonumber(data[2]) or now

tokens = math.min(capacity, tokens + (now - ts) / 1000 * rate)

local allowed = tokens >= cost
if allowed then tokens = tokens - cost end

redis.call("HSET", key, "tokens", tokens, "ts", now)
redis.call("PEXPIRE", key, math.ceil(capacity / rate * 1000) * 2)

local retry_after = 0
if not allowed then retry_after = math.ceil((cost - tokens) / rate) end
return { allowed and 1 or 0, math.floor(tokens), retry_after }
`;

export async function limit(key: string, rate = 10, capacity = 20, cost = 1) {
  const [allowed, remaining, retryAfter] = (await redis.eval(SCRIPT, {
    keys: [`rl:${key}`],
    arguments: [String(rate), String(capacity), String(Date.now()), String(cost)],
  })) as number[];
  return { allowed: allowed === 1, remaining, retryAfter };
}
```

Atomicity matters: doing read, compute, write in separate Redis calls creates race conditions under concurrency.

### Communicate limits to clients

```ts
app.use(async (req, res, next) => {
  const key = req.auth?.apiKeyId ?? req.ip;          // prefer identity over IP
  const { allowed, remaining, retryAfter } = await limit(key);

  res.set({
    "RateLimit-Limit": "20",
    "RateLimit-Remaining": String(remaining),
    "RateLimit-Reset": String(retryAfter),
  });

  if (!allowed) {
    res.set("Retry-After", String(retryAfter));
    return res.status(429).type("application/problem+json").json({
      type: "https://api.example.com/problems/rate-limited",
      title: "Too many requests",
      status: 429,
      detail: `Retry after ${retryAfter} seconds.`,
    });
  }
  next();
});
```

An IETF HTTP API working group draft aims to standardize `RateLimit` and `RateLimit-Policy` headers (the draft has changed its syntax between revisions, so check its current status), and the older `X-RateLimit-*` form is widespread. Pick one, document the exact semantics (is the reset value seconds until reset, or a timestamp?), and always send `Retry-After` on `429` and `503`. Also decide how you count rejected requests: counting them against the client can make recovery slower.

### Decisions that bite later

Limit per API key or user rather than per IP, because NAT and mobile carriers share IPs. You still want a coarse IP limit on unauthenticated endpoints like login. Tier the limits per plan, and give expensive endpoints (search, exports) separate budgets using `cost > 1`.

Enforce volumetric limits at the edge or gateway, and per-tenant business limits in the app.

Then there's the question of failing open or closed. If your limiter store is down, failing open preserves availability but removes protection; failing closed protects the backend but causes an outage. Most choose fail-open with local in-memory fallback limits.

Clients should honor `Retry-After` and use exponential backoff with jitter. Document it, and ship SDKs that do it.

## Idempotency

Networks fail between "server processed it" and "client got the response." The client can't know whether to retry. For `GET`, `PUT`, and `DELETE`, HTTP semantics already make retries safe. `POST` (create a payment, send an email) is the problem.

### The Idempotency-Key pattern

The client generates a unique key (a UUID) per *logical operation* and sends it in a header. The server stores the result keyed by it; a retry with the same key returns the stored response instead of executing again.

```text
POST /v1/payments
Idempotency-Key: 8f1d1e5e-7a65-4c43-9c3b-2a1d5f0a9b11
Content-Type: application/json

{"amount": 4999, "currency": "usd", "customer": "cus_88"}
```

### Implementation

```sql
CREATE TABLE idempotency_keys (
  key            TEXT        NOT NULL,
  tenant_id      TEXT        NOT NULL,
  request_hash   TEXT        NOT NULL,
  status         TEXT        NOT NULL CHECK (status IN ('in_progress', 'completed')),
  response_code  INT,
  response_body  JSONB,
  created_at     TIMESTAMPTZ NOT NULL DEFAULT now(),
  PRIMARY KEY (tenant_id, key)
);
```

```ts
export async function withIdempotency(req: Request, handler: () => Promise<{ code: number; body: unknown }>) {
  const key = req.header("Idempotency-Key");
  if (!key) return handler();                                   // or require it for POSTs

  const hash = sha256(req.method + req.path + JSON.stringify(req.body));

  // Try to claim the key atomically
  const claimed = await db.query(
    `INSERT INTO idempotency_keys (tenant_id, key, request_hash, status)
     VALUES ($1, $2, $3, 'in_progress') ON CONFLICT DO NOTHING RETURNING 1`,
    [req.tenantId, key, hash]
  );

  if (claimed.length === 0) {
    const [row] = await db.query(`SELECT * FROM idempotency_keys WHERE tenant_id=$1 AND key=$2`, [req.tenantId, key]);
    if (row.request_hash !== hash) {
      return { code: 422, body: problem("idempotency-key-reuse", "Key was used with a different request") };
    }
    if (row.status === "in_progress") {
      return { code: 409, body: problem("request-in-progress", "A request with this key is still processing") };
    }
    return { code: row.response_code, body: row.response_body };   // replay stored result
  }

  const result = await handler();
  await db.query(
    `UPDATE idempotency_keys SET status='completed', response_code=$3, response_body=$4
      WHERE tenant_id=$1 AND key=$2`,
    [req.tenantId, key, result.code, result.body]
  );
  return result;
}
```

A few rules keep this safe:

- Scope keys per tenant or account, to prevent cross-customer collisions.
- Hash the request, so reusing a key with different parameters is rejected instead of silently ignored.
- Do the business write and the key update in the same transaction when possible, so a crash can't leave a performed action without a stored result.
- Expire keys after a retention window long enough to cover client retry windows (24 hours to 7 days is typical), and document it.
- Cache only deterministic outcomes. Failures caused by transient server errors should allow a retry.
- Recover stuck keys. If the process crashes while a key is `in_progress`, retries would get `409` forever. Add a lock timeout (for example, treat `in_progress` rows older than a few minutes as abandoned) and make the handler safe to re-run.
- Align your semantics with the IETF draft for a standard `Idempotency-Key` header. Payment APIs (Stripe, for instance) popularized the pattern, so users will expect it.

For resource creation, you can also use client-supplied IDs (`PUT /v1/orders/{client-generated-uuid}`), which gives you idempotency for free through the primary key.

## Pagination

### Why not OFFSET

`?page=500&limit=50` requires the database to scan and discard 25,000 rows, and results shift if rows are inserted or deleted between requests (duplicates or gaps). It also invites scraping with deep pages.

### Cursor (keyset) pagination

```text
GET /v1/events?limit=50
-> { "data": [...50 items...], "next_cursor": "eyJ0IjoiMjAyNi0xMS0wN1QxMDoxNTozMFoiLCJpIjo5ODc2fQ" }

GET /v1/events?limit=50&cursor=eyJ0Ijoi...
```

The cursor is an opaque encoding of the last row's sort key. Opaque means clients can't depend on its structure, so you can change it later.

```ts
const encode = (o: object) => Buffer.from(JSON.stringify(o)).toString("base64url");
const decode = (s: string) => JSON.parse(Buffer.from(s, "base64url").toString());

app.get("/v1/events", async (req, res) => {
  const limit = Math.min(Number(req.query.limit ?? 50), 100);
  const cursor = req.query.cursor ? decode(String(req.query.cursor)) : null;

  const rows = await db.query(
    `SELECT id, created_at, type FROM events
      WHERE ($1::timestamptz IS NULL OR (created_at, id) < ($1, $2))
      ORDER BY created_at DESC, id DESC
      LIMIT $3`,
    [cursor?.t ?? null, cursor?.i ?? null, limit + 1]       // fetch one extra to know if there's more
  );

  const hasMore = rows.length > limit;
  const page = hasMore ? rows.slice(0, limit) : rows;
  const last = page.at(-1);

  res.json({
    data: page,
    next_cursor: hasMore && last ? encode({ t: last.created_at, i: last.id }) : null,
  });
});
```

Always include a unique tiebreaker (`id`) in the ordering, and back the query with a matching composite index. Cap `limit` server-side. If clients need random page jumps or total counts, offer them as separate, possibly approximate, features. Link headers (`rel="next"`) are an alternative to body fields.

Use cursors for feeds and large collections. Page numbers only make sense for small, stable data or admin UIs that need jumping.

## Errors that clients can act on

Return a consistent structure, using Problem Details (RFC 9457, `application/problem+json`), extended with a stable machine-readable code and field-level detail.

```json
{
  "type": "https://api.example.com/problems/validation-error",
  "title": "Validation failed",
  "status": 422,
  "detail": "2 fields are invalid.",
  "instance": "/v1/orders",
  "code": "validation_error",
  "request_id": "req_01JD3G7K9",
  "errors": [
    { "field": "items[0].qty", "code": "min", "message": "Must be at least 1" },
    { "field": "email", "code": "format", "message": "Must be a valid email address" }
  ]
}
```

A few principles make errors usable. Pick the right status code: `400` malformed, `401` unauthenticated, `403` forbidden, `404` not found, `409` conflict, `422` semantically invalid, `429` rate limited, `5xx` server fault. Don't return `200` with an error body.

Clients (and agents) should branch on a stable `code` string, never on the human `message`, which you may reword. Include a `request_id` that also appears in your logs, to make support and debugging fast, and don't leak internals: no stack traces, SQL or hostnames.

Say what to do next: include `Retry-After`, link to docs, and state which fields to fix. Agents rely heavily on actionable error text to self-correct. Mark which errors are retryable (`503`, `429`, network errors) and which are permanent (`4xx` other than `408/429`).

## Using HTTP properly

Use the methods as intended: `GET` is safe and cacheable, `PUT` is a full replace (idempotent), `PATCH` is a partial update, `DELETE` is idempotent, and `POST` covers creation or actions.

For caching, send `ETag` and honor `If-None-Match` (return `304`), and set `Cache-Control` appropriately. For concurrent updates use optimistic concurrency: clients send `If-Match: "<etag>"`, and you return `412 Precondition Failed` on mismatch to prevent lost updates. Support `gzip` and `br` compression.

Define server and client timeouts. For long operations, return `202 Accepted` with a `Location` of a status resource rather than holding connections open.

```text
POST /v1/exports            -> 202 Accepted
                               Location: /v1/exports/exp_123
GET  /v1/exports/exp_123    -> 200 {"status":"running","progress":0.4}
GET  /v1/exports/exp_123    -> 200 {"status":"done","download_url":"https://..."}
```

## Versioning and change management

Prefer additive evolution: new optional fields, new endpoints, new enum values (warn clients to handle unknown values). Never remove or change the meaning of a field without a new version.

Putting the version in the URL (`/v1/`) is simple and visible. Header-based or date-based versions (as used by some large platforms) allow finer-grained pinning. For deprecation, announce it, add `Deprecation` and `Sunset` headers, log who still calls old versions, and contact them before removal. Contract tests and OpenAPI diffing in CI (for example `oasdiff`) detect breaking changes before they ship.

```text
Deprecation: true
Sunset: Wed, 01 Jul 2027 00:00:00 GMT
Link: <https://api.example.com/docs/migrate-v2>; rel="deprecation"
```

## Security basics

- Authenticate every request (OAuth 2.x tokens or scoped API keys), and authorize per resource to avoid broken object-level authorization.
- Validate and bound all inputs: body size limits, string lengths, array sizes, and pagination limits.
- Never accept sensitive data in query strings (they end up in logs).
- Return `404` instead of `403` where revealing existence is a leak.
- Log access with request IDs, but redact secrets and personal data.
- Use TLS everywhere, and set CORS narrowly.

## Making the API agent-friendly

AI agents consume APIs through documentation and tool schemas, and they fail in predictable ways. A few habits help:

- Publish OpenAPI with accurate schemas, a `description` for every operation and field, and examples. It also powers docs, SDKs and validation, and many agent frameworks can generate tools from it.
- Use descriptive, consistent naming (`list_invoices`, not `getInv`), and the same patterns across resources.
- Return actionable errors (see above) with field-level hints, so the agent can fix its request without guessing.
- Make mutations safe to retry with idempotency keys.
- Support dry-run or preview modes (`?dry_run=true`) for destructive operations, so agents (and humans) can verify before committing.
- Keep responses compact and predictable: allow field selection (`?fields=id,status`) and pagination, since giant payloads waste an agent's context window.
- Provide scoped credentials with least privilege, plus clear permission errors naming the missing scope.
- Consider offering an MCP server or `llms.txt` describing capabilities for discovery.

## A server-side checklist

1. Rate limits per identity with token bucket, `429` + `Retry-After`, and documented headers.
2. `Idempotency-Key` on all non-idempotent `POST` endpoints, scoped, hashed, and expiring.
3. Cursor pagination with opaque cursors, tiebreaker ordering, and capped page sizes.
4. RFC 9457 problem details with stable `code` and `request_id`.
5. Correct status codes, ETags, and conditional requests for concurrency.
6. Additive-only changes; deprecation with `Sunset` headers; OpenAPI diff in CI.
7. Authorization on every resource; bounded inputs; no secrets in URLs.
8. OpenAPI published and examples tested against the live API.

## Retrying from the client

The server is only half of it. Clients should retry only safe or idempotent requests, honor `Retry-After`, back off with jitter, and cap total retry time. Something like this:

```ts
type RetryOptions = { retries?: number; baseMs?: number; maxMs?: number };

export async function fetchWithRetry(
  url: string,
  init: RequestInit & { idempotent?: boolean },
  { retries = 4, baseMs = 300, maxMs = 10_000 }: RetryOptions = {},
): Promise<Response> {
  const method = (init.method ?? "GET").toUpperCase();
  const safe = ["GET", "HEAD", "PUT", "DELETE"].includes(method) || init.idempotent === true;

  for (let attempt = 0; ; attempt++) {
    try {
      const res = await fetch(url, init);
      const retryable = res.status === 429 || res.status === 503 || res.status === 502 || res.status === 504;
      if (!retryable || !safe || attempt >= retries) return res;

      const retryAfter = Number(res.headers.get("Retry-After"));
      const backoff = Math.min(maxMs, baseMs * 2 ** attempt);
      const wait = Number.isFinite(retryAfter) && retryAfter > 0
        ? retryAfter * 1000
        : Math.random() * backoff; // full jitter
      await new Promise((r) => setTimeout(r, wait));
    } catch (err) {
      if (!safe || attempt >= retries) throw err;       // network error
      await new Promise((r) => setTimeout(r, Math.random() * Math.min(maxMs, baseMs * 2 ** attempt)));
    }
  }
}

// POST becomes safe to retry when it carries an idempotency key
await fetchWithRetry("/v1/payments", {
  method: "POST",
  idempotent: true,
  headers: { "Idempotency-Key": crypto.randomUUID(), "Content-Type": "application/json" },
  body: JSON.stringify({ amount: 4999, currency: "usd" }),
});
```

Generate the idempotency key once per logical operation and reuse it across all retries of that operation. Generating a new key per attempt defeats the purpose. The `Retry-After` header can also be an HTTP date, so handle both formats in production code.

## Filtering, sorting and field selection

Keep list endpoints predictable.

```text
GET /v1/invoices?status=open&customer=cus_88&created[gte]=2026-01-01&sort=-created&fields=id,status,total&limit=50
```

- Allow only whitelisted filter and sort fields, each backed by an index.
- Use a documented minus prefix (`-created`) for descending sort.
- Reject unknown parameters with `400` and a problem detail instead of ignoring them silently, so typos don't return unfiltered data.
- Document limits for filter complexity, to avoid expensive queries.

## Concurrency control with ETags

Two clients editing the same resource can overwrite each other. Optimistic concurrency fixes it without locks.

```ts
app.put("/v1/orders/:id", async (req, res) => {
  const current = await db.orders.get(req.params.id);
  if (!current) return res.status(404).end();

  const etag = `"${current.version}"`;
  if (req.header("If-Match") !== etag) {
    return res.status(412).type("application/problem+json").json({
      type: "https://api.example.com/problems/precondition-failed",
      title: "Resource changed",
      status: 412,
      detail: "Fetch the latest version and retry your change.",
    });
  }

  const updated = await db.orders.update(req.params.id, req.body, { version: current.version + 1 });
  res.set("ETag", `"${updated.version}"`).json(updated);
});
```

Return `428 Precondition Required` if you want to force clients to send `If-Match`.

## Bulk operations and partial failure

Batch endpoints save round trips but need a clear failure contract.

```json
{
  "results": [
    { "index": 0, "status": 201, "id": "ord_1" },
    { "index": 1, "status": 422, "error": { "code": "validation_error", "message": "qty must be at least 1" } }
  ]
}
```

Return `200` (or `207`) for the batch with per-item status, accept an idempotency key for the whole batch, cap batch size, and document whether the batch is atomic. Don't mix atomic and non-atomic behavior in one endpoint.

## Webhooks: the reverse direction

If your API sends webhooks, the same reliability ideas apply. Sign payloads (HMAC with a per-endpoint secret) and include a timestamp so receivers can reject replays. Retry with backoff for non-2xx responses, then disable the endpoint and notify the owner. Include an event id so receivers can be idempotent. Delivery should be at-least-once, and your docs should say so, since order isn't guaranteed. Let consumers replay events from a dashboard or API.

```ts
import { createHmac, timingSafeEqual } from "node:crypto";

export function verifyWebhook(rawBody: string, signatureHex: string, timestamp: string, secret: string) {
  if (Math.abs(Date.now() / 1000 - Number(timestamp)) > 300) return false; // 5 minute window
  const expected = createHmac("sha256", secret).update(`${timestamp}.${rawBody}`).digest();
  const given = Buffer.from(signatureHex, "hex");
  return given.length === expected.length && timingSafeEqual(given, expected);
}
```

Verify against the raw request body, not re-serialized JSON, and use a constant-time comparison.

## Gateway-level limits

Application limits aren't enough against volumetric abuse, so add edge controls:

```nginx
# Nginx: 10 requests per second per client IP, burst of 20
limit_req_zone $binary_remote_addr zone=api:10m rate=10r/s;

server {
    location /v1/ {
        limit_req zone=api burst=20 nodelay;
        limit_req_status 429;
        proxy_pass http://app;
    }
}
```

Use the gateway for coarse protection and the application for per-tenant and per-plan rules that need business context. Cloud providers' WAFs and API gateways offer managed rate limiting; check each product's current features and billing.

## Testing the contract

- **Rate limiter:** fire a burst and assert the 429 count and `Retry-After`. Test refill by advancing a fake clock.
- **Idempotency:** send the same request twice concurrently, and assert exactly one side effect. Send a different body with the same key, and assert `422`.
- **Pagination:** insert and delete rows between page fetches and assert there are no duplicates or gaps.
- **Errors:** snapshot the problem details for each error class, since the `code` values are part of your contract.
- **Backward compatibility:** run OpenAPI diff in CI on every pull request.

```bash
# Concurrent duplicate request check
for i in 1 2 3 4 5; do
  curl -s -o /dev/null -w "%{http_code}\n" -X POST http://localhost:3000/v1/payments \
    -H "Idempotency-Key: test-123" -H "Content-Type: application/json" \
    -d '{"amount":100,"currency":"usd"}' &
done; wait
```

Expect one `201` and the others `409` (in progress) or replayed `201`, but only one payment row in the database.

## Troubleshooting

| Symptom | Likely cause | Fix |
| --- | --- | --- |
| Legitimate users get 429 behind a corporate NAT | Limiting by IP | Limit by authenticated identity; raise IP limits |
| Bursts of 2x the limit at window edges | Fixed window algorithm | Token bucket or sliding window counter |
| Duplicate charges after client timeouts | No idempotency key or key regenerated per retry | Require keys; reuse the key across retries |
| `409 in progress` forever | Crash left a key stuck | Lock timeout and safe re-run |
| Pagination returns duplicates or skips items | Ordering without a unique tiebreaker, or OFFSET on changing data | Keyset with `(created_at, id)` |
| Deep pages slow | OFFSET scan | Cursor pagination plus matching index |
| Agents loop on an error | Vague or inconsistent error body | Stable `code`, field errors, clear next step |
| Limiter outage takes API down | Fail closed | Fail open with local fallback limits, alert |

## Where this usually goes wrong

- Returning `200` for errors, or `500` for client mistakes.
- Using the human message as the contract.
- Letting clients choose arbitrary `limit` values.
- Cursors that expose raw database ids and are trusted without validation. Validate and, if needed, sign cursors.
- Rate limiting only by IP.
- Generating idempotency keys server-side, which does nothing for client retries.
- Changing response shapes without versioning.
- Counting limits in memory per instance, so effective limits scale with replicas.

## When not to build this yourself

For coarse rate limiting and auth, use your API gateway or a managed service rather than writing it in every service. Reach for a well-reviewed library (for example `express-rate-limit` with a shared store) before hand-rolling limiter code. For tiny internal APIs with trusted clients, start with timeouts, validation and basic limits, and add idempotency where money or side effects are involved.

## Questions that come up

**Should every POST require an idempotency key?** Require it for operations with side effects that are costly to duplicate (payments, emails, resource creation). Make it optional elsewhere.

**What status for validation errors, 400 or 422?** Either is defensible. Choose one convention and use it consistently; many teams use `400` for malformed requests and `422` for semantic validation.

**Do I need API versioning from day one?** Put `/v1/` in the URL from the start. It's cheap and gives you room later.

## Sources and docs

- [RFC 9457: Problem Details for HTTP APIs](https://www.rfc-editor.org/rfc/rfc9457.html)
- [RFC 9110: HTTP Semantics](https://www.rfc-editor.org/rfc/rfc9110.html) (status codes, conditional requests, `Retry-After`)
- [IETF: Idempotency-Key HTTP Header Field (draft)](https://datatracker.ietf.org/doc/draft-ietf-httpapi-idempotency-key-header/)
- [IETF: RateLimit header fields (draft)](https://datatracker.ietf.org/doc/draft-ietf-httpapi-ratelimit-headers/)
- [RFC 8594: The Sunset HTTP Header Field](https://www.rfc-editor.org/rfc/rfc8594.html)
- [Stripe: Idempotent requests](https://docs.stripe.com/api/idempotent_requests)
- [OpenAPI Specification](https://spec.openapis.org/oas/latest.html)
- [oasdiff](https://github.com/oasdiff/oasdiff)

On this site: [Event-driven architecture: outbox and idempotency](https://www.derar.dev/blog/event-driven-architecture-outbox-idempotency-2026), [Redis and Valkey caching](https://www.derar.dev/blog/redis-valkey-caching-strategies-2026), [OAuth, OIDC and API security pitfalls](https://www.derar.dev/blog/oauth-oidc-api-security-pitfalls-2026), [Express.js performance](https://www.derar.dev/blog/expressjs-performance-optimization), [Securing MCP servers](https://www.derar.dev/blog/securing-mcp-servers-production-2026).
