API Design Principles for Long-lived Systems
Design APIs that survive years: explicit versioning, consistent pagination, idempotency for safety, clear errors, and hypermedia links for discoverability.
On this page
- Introduction
- Versioning: Make Breaking Changes Explicit
- Pagination: One Consistent Way to Page
- Idempotency: Retries Must Not Duplicate Work
- Errors That Tell the Consumer What to Do
- Hypermedia and Discoverability (HATEOAS)
- Consistency Is the Principle Above All
- Rate Limiting, Quotas, and the OpenAPI Contract
- Conclusion
Introduction
An API is a contract, and a long-lived system is one whose contract must evolve without breaking its consumers. The APIs that age well were designed with that evolution in mind: they are versioned, so a breaking change is a new version rather than a surprise; they paginate consistently, so a consumer does not write custom logic for each list endpoint; they are idempotent where it matters, so a retried request does not double-charge; and they return errors that tell the consumer what to do. The APIs that age poorly were designed for the first consumer and patched for each subsequent one, accumulating special cases and inconsistencies until nobody can predict the shape of the next response. This article covers the principles that make an API durable.
Versioning: Make Breaking Changes Explicit
A breaking change — removing a field, changing a type, altering the semantics of a parameter — is inevitable over the life of an API. The question is not whether you will make one but how you make it. The durable answer is versioning: the breaking change lives in a new version of the API, and the old version continues to work (possibly deprecated, possibly frozen) until consumers migrate. The version is in the URL path (/v2/users) or in a header (Accept: application/vnd.example.v2+json); the path version is more visible and easier to route, the header version is more REST-pure. Choose one and be consistent.
// Route by version; the old version stays available and deprecated.
router.use("/v1", v1Routes); // deprecated, still served
router.use("/v2", v2Routes); // current
Deprecate loudly: when a consumer hits a deprecated version, return a Deprecation header and a Sunset header announcing the end-of-life date, and log the consumer so you can contact them. A silent deprecation is a future outage you have not planned for. Never make a breaking change in place and hope nobody notices — somebody is depending on the field you removed, and they will notice in production.
Pagination: One Consistent Way to Page
Every list endpoint should paginate the same way, with the same parameters and the same response envelope. The two sound strategies are offset/limit (?offset=20&limit=10) and cursor (?after=cursor&limit=10). Offset pagination is intuitive but slow on large tables (the database skips N rows) and unstable if rows are inserted between pages (a new row shifts every page). Cursor pagination uses an opaque token that encodes the position; it is stable under insertion and fast because it uses an index seek. For any list that can grow large or that is paginated while new data arrives, prefer cursors.
// Cursor pagination with a consistent envelope.
interface Page<T> {
data: T[];
nextCursor: string | null; // null when there is no more data
hasMore: boolean;
}
async function listUsers(req: Request): Promise<Page<User>> {
const limit = Math.min(Number(req.query.limit ?? 50), 100); // cap the page size
const cursor = req.query.after ? decodeCursor(req.query.after) : null;
const rows = await db.users.findMany({ take: limit + 1, skip: cursor ? 1 : 0, cursor: cursor ?? undefined, orderBy: { id: "asc" } });
const hasMore = rows.length > limit;
const data = hasMore ? rows.slice(0, limit) : rows;
return { data, nextCursor: hasMore ? encodeCursor(data[data.length - 1].id) : null, hasMore };
}
The envelope is the contract: data is the page of items, nextCursor is the token for the next page or null at the end, hasMore is the convenience flag. Every list endpoint returns this shape, so a consumer writes one pagination helper and reuses it. Cap the page size server-side so a consumer asking for limit=1000000 does not fetch the whole table.
Idempotency: Retries Must Not Duplicate Work
A retry is a fact of networked life, and for operations that change state — creating a charge, sending an email, transferring money — a retry that performs the operation twice is a bug. Idempotency means the same request, sent more than once, has the same effect as sending it once. The mechanism is an idempotency key: the client sends a unique key with the request, the server uses the key to deduplicate, and a retried request with the same key returns the result of the first rather than performing the operation again.
router.post("/charges", async (req, res) => {
const key = req.headers["idempotency-key"] as string | undefined;
if (!key) return res.status(400).json({ error: "Idempotency-Key required" });
const existing = await idempotency.get(key);
if (existing) return res.status(existing.status).json(existing.body); // replay the original result
try {
const result = await createCharge(req.body);
await idempotency.set(key, { status: 201, body: result }, { ttl: 86400 });
res.status(201).json(result);
} catch (err) {
await idempotency.set(key, { status: 500, body: { error: "failed" } }, { ttl: 600 });
throw err;
}
});
Store the idempotency result keyed by the client’s key with a TTL, and replay it on a repeat. Only store the result on success or a definitive failure — never on a transient failure, because the consumer will retry and you want the retry to actually attempt the operation. GET, PUT, and DELETE are idempotent by HTTP definition; POST is not, and that is where the key matters.
Errors That Tell the Consumer What to Do
An API error is a message to a developer, and a good one is actionable: it identifies the problem, points at the field if there is one, and suggests the fix. The shape should be consistent across the API, with a machine-readable code and a human-readable message.
// Consistent error envelope.
interface ApiError {
code: string; // machine-readable, e.g. "validation_failed"
message: string; // human-readable
details?: Array<{ field: string; code: string; message: string }>;
requestId: string; // for support correlation
}
// 422 with field-level details.
res.status(422).json({
code: "validation_failed",
message: "The request was invalid.",
details: [{ field: "email", code: "already_taken", message: "That email is already registered." }],
requestId: req.id,
});
Use the correct status code: 400 for a malformed request, 422 for a well-formed but invalid one, 409 for a conflict, 404 for a missing resource, 401 for no authentication, 403 for insufficient permission. The distinction matters to consumers — a client that retries on 5xx should not retry on 422, and a client that prompts for login on 401 should not do so on 403. Never return a 200 with an error body; it breaks every generic HTTP client and forces consumers to special-case your API.
Hypermedia and Discoverability (HATEOAS)
Hypermedia As The Engine Of Application State — HATEOAS — means the API response includes the links to the next available actions, so the consumer follows links rather than constructing URLs. A user resource returns a links object with self, update, and deactivate URLs; the consumer that wants to deactivate the user follows the deactivate link rather than knowing that the endpoint is DELETE /users/:id. This decouples the consumer from the URL structure: you can restructure your routes without breaking consumers, because they follow the links the API gives them.
function userResource(user: User, req: Request) {
return {
...user,
links: {
self: `${req.baseUrl}/users/${user.id}`,
update: { href: `${req.baseUrl}/users/${user.id}`, method: "PATCH" },
deactivate: { href: `${req.baseUrl}/users/${user.id}`, method: "DELETE" },
},
};
}
HATEOAS is not universally adopted — many APIs skip it and document the URL structure instead — but it is the mechanism that makes an API genuinely evolvable, because the consumer is driven by the links the server provides rather than by hardcoded URLs the server must then preserve forever. Adopt it at least for the actions that change, and you buy yourself the freedom to move them.
Consistency Is the Principle Above All
The thread through every principle here is consistency. The same pagination shape on every list, the same error envelope on every failure, the same versioning scheme across the API, the same idempotency header on every state-changing endpoint. Consistency lets a consumer learn the API once and predict the rest; inconsistency forces them to read the documentation for every endpoint and to write custom handling for each. When you add an endpoint, make it look like the existing ones; when you are tempted to add a special case, make it a general rule instead. The long-lived API is the consistent one, because consistency is what lets it grow without surprising its consumers.
Rate Limiting, Quotas, and the OpenAPI Contract
An API without a rate limit is an API that one consumer can deny to all the others. Rate limiting protects the service from abuse and from a misbehaving client, and it is the fair-use policy that makes a shared API viable. The two models are per-consumer (a token or API key may make N requests per minute) and global (the service accepts N requests per minute total, across all consumers). Per-consumer limits fairness; global limits protect capacity. Apply both: a per-consumer limit that is well under the global limit, so a single client cannot exhaust the global budget.
// A sliding-window rate limiter backed by Redis.
async function rateLimit(key: string, limit: number, windowMs: number): Promise<boolean> {
const now = Date.now();
const member = `${now}:${crypto.randomUUID()}`;
const tx = redis.multi();
tx.zremrangebyscore(key, 0, now - windowMs); // drop entries outside the window
tx.zadd(key, now, member);
tx.zcard(key); // count entries in the window
tx.pexpire(key, windowMs);
const results = await tx.exec();
const count = results[2] as number;
return count <= limit; // false -> 429 Too Many Requests
}
Return 429 Too Many Requests with the Retry-After header (seconds until the next request is allowed) and, for transparency, the X-RateLimit-Limit, X-RateLimit-Remaining, and X-RateLimit-Reset headers so the client can pace itself. A rate limit without Retry-After forces the client to guess when to retry, which produces either hammering or excessive backoff. Distinguish a rate limit (transient, retry later) from a quota (a total budget over a longer period, like 10,000 requests per month) in the status code and the headers, so the client handles each correctly — a rate limit is retried, a quota is surfaced to the user as “upgrade your plan.”
The OpenAPI contract is the machine-readable description of the API, and it is the single source of truth that ties together the implementation, the client, the documentation, and the tests. Generate the OpenAPI spec from the route definitions (with a library like @asteasolutions/zod-to-openapi or the framework’s built-in support) so the spec cannot drift from the implementation. From the spec, generate a typed client for the consumers, so they get the same types the server uses. From the spec, render the documentation (with Swagger UI or Redoc), so the docs cannot drift either. The spec is the hub; everything else is a spoke.
// Generate the OpenAPI spec from the Zod schemas that define the routes.
import { createDocument } from "zod-openapi";
const doc = createDocument({
openapi: "3.1.0",
info: { title: "Example API", version: "1.0.0" },
paths: {
"/users/{id}": {
get: {
parameters: [{ name: "id", in: "path", required: true, schema: { type: "string" } }],
responses: { "200": { description: "A user", content: { "application/json": { schema: UserSchema } } } },
},
},
},
});
Contract testing closes the loop between the spec and the implementation. A contract test asserts that the API’s actual responses match the spec — that a GET /users/{id} returns an object that satisfies UserSchema. Run it against the running server in CI, and a response that drifts from the spec (a field renamed, a type changed) fails the test before it reaches a consumer. This is the test that catches the breaking change the developer did not realize was breaking, because the spec is the authority and the test compares the reality to it. With the spec generated from the implementation, the docs generated from the spec, the client generated from the spec, and the contract test comparing the implementation to the spec, every artifact is consistent by construction, and the API’s contract is a living, enforced thing rather than a document that drifts.
Conclusion
An API that survives years is versioned so breaking changes are explicit, paginated consistently so consumers reuse one helper, idempotent where state changes so retries are safe, errored with an actionable, consistent envelope, and discoverable through hypermedia links so consumers follow the API rather than memorizing it. Above all it is consistent — the same shapes and conventions everywhere — because consistency is what lets a consumer learn the contract once and trust it as it evolves. Design for the second consumer and the fifth year, not the first consumer and the launch date, and the API will age into an asset rather than a liability.
Report a problem with this articleOpens a pre-filled issue on GitHub.