Engineering Note

A comprehensive guide to designing resilient REST APIs: deterministic contracts, idempotency keys, RFC 7807 problem details, and defense-in-depth rate limiting.

Contract Determinism & Schema Boundaries

An API in production is a legally binding contract between distributed systems. The most common failure in evolving APIs is unintentional contract drift — where internal database mutations subtly alter the output shape.

Enforce strict boundary validation at runtime using libraries like Zod or typebox. Request bodies must be sanitized before touching domain handlers, and responses must be explicitly projected through output transfer schemas to avoid leaking sensitive internal fields.

TYPESCRIPT
// Strict input schema validation with Zod
export const CreateOrderSchema = z.object({
  idempotencyKey: z.string().uuid(),
  warehouseId: z.string().min(1),
  items: z.array(z.object({
    sku: z.string(),
    quantity: z.positive().int(),
  })).min(1),
});

Idempotency for Mutating Operations

Network timeouts are inherently ambiguous: did the server fail before processing the request, or did the response get lost on the return path? Without idempotency, clients retrying a failed HTTP POST risk creating duplicate orders or double payments.

Implement an idempotency layer using an atomic distributed lock (such as Redis SETNX or a PostgreSQL unique constraint on an idempotency key). If an identical key arrives while the operation is in flight, return HTTP 409 Conflict. If it arrives after completion, return the cached result payload.

Structured Error Responses (RFC 7807)

Never return raw stack traces or plain text strings when an API call fails. Standardize on RFC 7807 (Problem Details for HTTP APIs), providing consistent machine-readable fields such as type, title, status, detail, and instance.

This empowers consumer applications to programmatically distinguish validation errors from transient infrastructure faults and display meaningful feedback to end users.

Related Engineering Notes

/avoiding-n-plus-one

Avoiding N+1 Database Queries

Techniques for eliminating silent database query amplification in ORMs through query planning, batching, and join projection.

/response-projection

API Response Projection & Data Security

Preventing inadvertent data leaks by establishing intentional serialization boundaries between database entities and public API responses.

← Back to engineering notes