---
topic: backend-engineering
author: Crashtech Editorial
published: Nov 15, 2026 · read: 4 min
---

Modern REST API Design: Noun-Based Resources, Idempotency Keys, Cursor Pagination, and Security Hardening

An architectural guide to designing production REST APIs: idempotent mutations, cursor pagination, status code precision, and zero-trust security.

– –

A well-designed API feels invisible: it is predictable, self-documenting, resilient to transient network drops, and hardened against security vulnerabilities. Conversely, a poorly designed API breeds subtle production bugs: accidental double-charges, schema breakages during deployments, and database collapse under pagination loads.

Building production-grade APIs requires looking beyond basic CRUD tutorials. Engineers must adhere to foundational architectural standards: semantic URI hierarchies, strict HTTP method idempotency, cursor-based pagination, and defensive security controls.

+-----------------------------------------------------------------------------------+
|                        PRODUCTION REST API ANATOMY                                |
+-----------------------------------------------------------------------------------+

Incoming HTTP Request:
POST /v1/customers/cus_981a/invoices HTTP/1.1
Host: api.platform.com
Authorization: Bearer eyJhbGciOi... (Cryptographically Signed JWT)
Idempotency-Key: 7b89e3a1-4f12-4d56-b891-9c3f4e1a0b5c
Content-Type: application/json

{
  "amount_cents": 4500,
  "currency": "usd"
}

Server Evaluation:
1. Verify TLS 1.3 & Authenticate Bearer JWT
2. Check Redis for existing Idempotency-Key
   -> If Found: Return Cached 201 Response (Zero Re-Execution)
   -> If Not Found: Acquire Lock & Execute Database Transaction
3. Return Standardized JSON Payload with Links & Cursor Tokens

1. Resource Modeling: Nouns, Plurals, and Hierarchies

The cornerstone of RESTful architecture is that URIs represent resources (nouns), while the HTTP verb describes the action.

The Anti-Pattern: RPC via HTTP

Novice API developers frequently embed verbs into URLs, treating HTTP as an arbitrary Remote Procedure Call (RPC) transport:

// Bad API Design: Verb-based RPC endpoints
POST /api/createProduct
POST /api/getProducts
POST /api/updateProduct?id=12
POST /api/deleteProduct

The REST Standard: Nouns and Hierarchies

REST standardizes operations around clean, pluralized resource nouns:

GET    /v1/products          -> List products (Paginated)
POST   /v1/products          -> Create a new product
GET    /v1/products/prod_12  -> Retrieve specific product
PUT    /v1/products/prod_12  -> Replace product completely
PATCH  /v1/products/prod_12  -> Partially update product fields
DELETE /v1/products/prod_12  -> Delete product

Modeling Sub-Resource Hierarchies

When entities exist exclusively within the context of a parent entity, model them as nested URI paths:

GET    /v1/teams/team_42/members               -> List members in team 42
POST   /v1/teams/team_42/members               -> Add member to team 42
DELETE /v1/teams/team_42/members/user_99       -> Remove user 99 from team 42

Limit URI nesting to a maximum depth of two levels (/parents/{id}/children). Deeper relationships (such as /orgs/1/teams/2/projects/3/tasks/4) create unwieldy URLs; flatten deep relationships into top-level resources filtered by query parameters (e.g., GET /v1/tasks?project_id=3).


2. HTTP Method Semantics and Idempotency

Understanding safety and idempotency prevents data corruption during client retries.

+-------------------------------------------------------------------+
|               HTTP METHODS: SAFETY AND IDEMPOTENCY                |
+-------------------------------------------------------------------+
| Method | Safe? (Read-Only) | Idempotent? | Description            |
| :---   | :---              | :---        | :---                   |
| **GET**| YES               | YES         | Retrieve representation|
| **PUT**| NO                | YES         | Replace resource state |
| **DELETE**| NO             | YES         | Remove resource        |
| **POST**| NO               | NO          | Create / Subordinate   |
| **PATCH**| NO              | NO          | Delta modification     |
+-------------------------------------------------------------------+

The Idempotency Key Pattern for POST Mutations

Networks are inherently unreliable. When a mobile client issues POST /v1/payments and the network connection drops before the server’s HTTP 201 Created response reaches the client, the client cannot tell if the payment succeeded or failed.

If the client retries blindly, the user is charged twice.

To solve this, production APIs mandate an Idempotency-Key header:

Client                             Server                           Redis Cache
  |                                  |                                   |
  |-- POST /charges (Key: "abc-1") ->|                                   |
  |                                  |-- SETNX lock:abc-1 -------------->|
  |                                  |<-- 1 (Lock Acquired) -------------|
  |                                  |                                   |
  |                                  | [Processes Payment in Stripe DB]  |
  |                                  |                                   |
  |                                  |-- SET result:abc-1 JSON --------->|
  |<- HTTP 201 Created --------------|                                   |
  |   (Network drops packet!)        |                                   |
  |                                  |                                   |
  |-- POST /charges (Key: "abc-1") ->|                                   |
  |   (Client Retries)               |-- GET result:abc-1 -------------->|
  |                                  |<-- Returns Stored JSON -----------|
  |<- HTTP 201 Created --------------|                                   |
      (Zero duplicate charge!)
# Conceptual Idempotency Middleware in FastAPI / Python
import json
from fastapi import Request, HTTPException

async def idempotency_middleware(request: Request, call_next):
    if request.method != "POST":
        return await call_next(request)

    key = request.headers.get("Idempotency-Key")
    if not key:
        return await call_next(request)

    redis = request.app.state.redis
    cache_key = f"idempotency:{key}"

    # Atomic lock acquisition
    acquired = await redis.set(f"lock:{key}", "1", nx=True, ex=30)
    if not acquired:
        # Request is currently in flight from another concurrent call
        raise HTTPException(status_code=409, detail="Concurrent request in flight")

    cached_response = await redis.get(cache_key)
    if cached_response:
        data = json.loads(cached_response)
        return Response(content=data["body"], status_code=data["status"], headers=data["headers"])

    response = await call_next(request)

    # Cache successful response for 24 hours
    if 200 <= response.status_code < 300:
        await redis.set(cache_key, json.dumps({
            "status": response.status_code,
            "body": response.body.decode(),
            "headers": dict(response.headers)
        }), ex=86400)

    return response

3. Pagination: Why Offset-Limit Breaks and How Cursors Fix It

When returning collections containing thousands of records, returning all records in a single array exhausts memory and crashes clients. APIs must paginate.

The Pitfall of Offset Pagination: ?offset=100000&limit=20

Offset pagination maps directly to SQL LIMIT 20 OFFSET 100000:

  1. Performance Collapse: The database storage engine cannot jump straight to row 100,000. It must traverse the B-Tree index, scan and load 100,020 rows off disk, discard the first 100,000 rows, and return the trailing 20. Execution time scales linearly $O(N)$ with page depth.
  2. Offset Drift: If a new product is inserted at row 1 while a user is paginating from page 1 to page 2, all rows shift downward by one. The user sees the last record of page 1 repeated at the top of page 2.

The Standard: Cursor-Based Pagination

Cursor pagination passes an opaque, encoded pointer representing the boundary of the last retrieved record:

GET /v1/transactions?limit=20&cursor=eyJpZCI6InR4Xzg5MDEiLCJ0IjoxNzM5NjAwMH0=

The server decodes the cursor into an index predicate:

SELECT * FROM transactions
WHERE (created_at, id) < ('2026-11-15 13:00:00', 'tx_8901')
ORDER BY created_at DESC, id DESC
LIMIT 21;
+-------------------------------------------------------------------+
|               OFFSET VS CURSOR PAGINATION COMPARISON              |
+-------------------------------------------------------------------+
| Characteristic   | Offset Pagination        | Cursor Pagination   |
| :---             | :---                     | :---                |
| **SQL Query**    | `LIMIT 20 OFFSET 50000`  | `WHERE id > cursor` |
| **Complexity**   | $O(N)$ Sequential Scan   | $O(\log N)$ B-Tree  |
| **Deep Paging**  | Times out / High I/O     | Constant Sub-5ms    |
| **Item Drift**   | Severe duplicates/skips  | Zero drift          |
| **Arbitrary Jump**| Allows jump to Page 50  | Sequential only     |
+-------------------------------------------------------------------+

4. Status Code Precision and Error Contracts

APIs must never return HTTP 200 OK with an error payload (e.g., {"status": "error", "message": "unauthorized"}). This breaks reverse proxies, monitoring tools, and client error-handling libraries.

Core Status Codes:

  • 200 OK: Successful GET, PUT, or PATCH.
  • 201 Created: Successful POST resulting in a new resource. Returns Location header.
  • 202 Accepted: Asynchronous task queued for processing.
  • 204 No Content: Successful DELETE. Zero response body.
  • 400 Bad Request: Malformed JSON or syntax failure.
  • 401 Unauthorized: Missing or invalid authentication token.
  • 403 Forbidden: Valid identity, but caller lacks permission for this resource.
  • 404 Not Found: Resource does not exist.
  • 409 Conflict: State conflict (e.g., duplicate unique constraint or concurrent modification).
  • 422 Unprocessable Entity: Valid JSON, but fails business schema validation.
  • 429 Too Many Requests: Rate limit exceeded.

Standardized Error Payloads (RFC 7807 Problem Details)

Standardize all errors on RFC 7807 JSON schemas:

{
  "type": "https://api.platform.com/errors/insufficient-funds",
  "title": "Insufficient Funds",
  "status": 422,
  "detail": "Account balance $45.00 is insufficient for transaction amount $100.00.",
  "instance": "/v1/charges/ch_9128",
  "code": "CARD_DECLINED_INSUFFICIENT_FUNDS"
}

5. Security Hardening Checklist

  1. Enforce TLS 1.3 Exclusively: Reject legacy SSLv3, TLS 1.0, and TLS 1.1 handshakes. Redirect all HTTP requests to HTTPS with Strict-Transport-Security: max-age=63072000; includeSubDomains; preload.
  2. Stateless JWT Validation: Validate token signature, issuer (iss), audience (aud), and expiration (exp) on every request. Never store sensitive passwords or credit card numbers inside JWT claims.
  3. Expose Standard Rate-Limiting Headers: Inform clients of their remaining budget:
    • RateLimit-Limit: 1000
    • RateLimit-Remaining: 842
    • RateLimit-Reset: 1739612400
  4. Input Size Limits & Schema Validation: Set maximum body limits (e.g., reject payloads > 10MB) at the reverse proxy to prevent denial-of-service memory exhaustion attacks.

Summary Takeaways

  • Nouns over verbs: Model APIs as collections of plural resources manipulated via standard HTTP verbs.
  • Make mutations safe with idempotency: Protect billing and critical state mutations using client-supplied Idempotency-Key headers stored in Redis.
  • Ditch offset pagination: Always use cursor-based pagination for large or rapidly growing datasets to prevent $O(N)$ database scans and row drift.
  • Communicate with precision: Use standard HTTP status codes and RFC 7807 structured error payloads so client libraries handle failures gracefully.
Advertisement

Frequently asked questions

What is the difference between an idempotent HTTP method and a safe HTTP method?

A safe method (like GET or HEAD) never mutates server-side state. An idempotent method (like PUT or DELETE) can mutate state, but repeating the identical request multiple times results in the exact same server state as a single invocation. POST and PATCH are not idempotent by default.

How does an Idempotency-Key header protect payment endpoints from double-charging?

When a client initiates a POST mutation, it passes a unique UUID in the Idempotency-Key header. The server acquires an atomic lock in Redis, stores the result, and if the client retries due to a network timeout, the server returns the cached response without re-executing the charge.

Why is cursor-based pagination superior to offset-and-limit pagination?

Offset pagination (OFFSET 100000) forces the database to read and discard 100,000 index entries, creating severe performance degradation. Furthermore, concurrent row insertions cause offset drift where items are skipped or duplicated. Cursor pagination uses index range scans (WHERE id > cursor) in constant O(log N) time.

Should API versioning reside in the URI path or in HTTP request headers?

URI path versioning (/v1/payments) is the industry standard for public APIs due to simplicity, transparent browser cacheability, and clear developer ergonomics. Header-based versioning (Accept: application/vnd.company.v1+json) conforms strictly to REST semantics but complicates debugging and proxy caching.

Sources & further reading

/* Comments */