API Design Fundamentals: Resources, Errors, Concurrency and Contracts


System Design Phase 8: APIs & Service Communication
Core Lesson 39 of 86 18 min read Updated Nov 30, 2026

A partner integration goes live on a Monday. By Wednesday your support queue has 340 tickets. The partner’s code treats every non-200 response as “retry”, so a validation error on a malformed postcode gets retried 5 times per order. Your error body is a plain string, "Something went wrong", so their engineers cannot tell a bad postcode from a database outage. Two of their warehouse workers edited the same order at the same time and the second save silently overwrote the first, so 41 parcels shipped to an old address.

None of this is a scaling problem. The servers were at 12% CPU the whole week. It is an API design problem: the contract did not tell clients what happened, what to do next, or how to avoid stepping on each other. Fixing it after launch means a new version and a six month migration for every partner.

The decisions that prevent this are cheap on day one and expensive forever after. This article walks through them in the order you meet them when designing a real API, then designs an orders API end to end.

What API design is

An API is a contract between a team that owns data and the teams that use it. API design is choosing that contract on purpose: what the nouns are, what operations exist on them, what every success and failure looks like on the wire, and which changes you promise never to make.

A good contract has three properties. It is predictable: a developer who has used two of your endpoints can guess the third. It is honest about failure: every error says what went wrong, whether retrying helps, and which field to fix. It is evolvable: you can add features for years without breaking the clients you already have.

This article assumes you know HTTP methods, status code classes and caching headers. Those are covered in HTTP semantics, HTTP/2 and HTTP/3. Here we use them to build contracts. Whether you should use REST at all, or GraphQL or gRPC, is the subject of REST vs GraphQL vs gRPC; most of what follows applies to all three.

How it works

Resource modeling and naming

Start from the domain, not the database. List the nouns a client cares about (orders, line items, shipments, refunds) and the relationships between them. Each noun becomes a collection (/orders) and each instance a resource (/orders/ord_8f2k).

Conventions that pay off:

  • Plural nouns for collections, lowercase, hyphenated: /orders, /shipping-labels. No verbs in paths for CRUD.
  • Nest only for true ownership, one level deep. /orders/ord_8f2k/items is fine because an item cannot exist without its order. /customers/c1/orders/ord_8f2k/items/i9/refunds is not; give refunds their own top-level collection and filter by order.
  • Opaque, prefixed, non-sequential IDs. ord_8f2k... tells a human reading a log what kind of object it is, and a random ID does not leak your order volume or invite enumeration. Sequential integers let anyone count your orders by creating one a day apart.
  • Actions that are not CRUD get a sub-resource with POST, not a verb soup: POST /orders/ord_8f2k/cancel is clearer and easier to authorise than PATCH with status=cancelled, because cancelling has side effects (refunds, stock release) that a field update hides.
  • One naming case for JSON fields across the whole API. Pick snake_case or camelCase once. Timestamps in RFC 3339 UTC (2026-11-30T09:15:00Z). Money as an integer of minor units plus a currency code (amount: 4999, currency: "INR"), never a float.

Methods: a short recap

GET and HEAD are safe; GET, PUT and DELETE are idempotent; POST and PATCH are neither by default. Those properties are what make retries and caches safe, and they are covered in HTTP semantics. The design consequence: anything a client may retry after a timeout needs to be idempotent, so either use PUT with a client-chosen ID or accept an Idempotency-Key header on POST. That mechanism has its own article, idempotency; the short version is that the server stores the key with the first response and replays it for duplicates.

Status codes that carry meaning

Clients branch on status codes, so the code must answer “whose fault is it, and will retrying help?” Use a small, consistent set:

Code Use it for Client should
200 / 201 / 204 Success, created (with Location), success with no body Proceed
202 Accepted Work queued, result later Poll the status resource
400 Bad Request Malformed syntax, unparseable JSON Fix the request, do not retry
401 / 403 Not authenticated / authenticated but not allowed Re-authenticate / give up
404 Not Found No such resource, or hidden from this caller Do not retry
409 Conflict State conflict (already cancelled, duplicate in flight) Read current state, decide
412 Precondition Failed If-Match ETag did not match Re-read, merge, retry
422 Unprocessable Content Well-formed but fails validation Fix the listed fields
429 Too Many Requests Rate limited Wait for Retry-After
500 / 502 / 503 / 504 Server or upstream failure Retry with backoff if idempotent

Teams argue about 400 vs 422 for validation. Either is defensible; what matters is that you pick one and document it. Returning 200 with "success": false in the body is the one choice that is never defensible, because every proxy, retry library, dashboard and alert in between reads the status code and sees success.

Error contracts with Problem Details

RFC 9457 (July 2023, replacing RFC 7807) standardises an error body with media type application/problem+json. The core members are type (a URI that identifies the problem kind and doubles as documentation), title (short human summary, stable per type), status, detail (this occurrence) and instance (a URI for this occurrence, handy for support). You may add extension members.

{
  "type": "https://api.example.com/problems/validation-error",
  "title": "Request validation failed",
  "status": 422,
  "detail": "2 fields failed validation",
  "instance": "/orders/req_7Hc2",
  "errors": [
    { "pointer": "/shipping/postcode", "detail": "must be 6 digits" },
    { "pointer": "/items/0/quantity", "detail": "must be at least 1" }
  ],
  "trace_id": "4bf92f3577b34da6a3ce929d0e0e4736"
}

Three rules make error contracts useful. Clients branch on type (machine readable, stable), never on title or detail (human readable, may change). Every validation error lists all failing fields at once, using JSON Pointer paths, so a form can highlight everything in one round trip. And every error carries a trace or request ID so a partner’s ticket can be matched to your logs in seconds.

Optimistic concurrency with ETag and If-Match

The lost update in the opening story happens because two clients read version 1, both modify it, and the last write wins. Locking a row while a human edits a form is not an option over HTTP. Instead, the server returns an ETag (a version token) with every read, and the client sends it back in If-Match on writes. If the resource changed in between, the server refuses with 412.

sequenceDiagram
participant A as Worker A
participant API as Orders API
participant B as Worker B
A->>API: GET /orders/ord_8f2k
API-->>A: 200, ETag "v7"
B->>API: GET /orders/ord_8f2k
API-->>B: 200, ETag "v7"
A->>API: PATCH address, If-Match "v7"
API-->>A: 200, ETag "v8"
B->>API: PATCH address, If-Match "v7"
API-->>B: 412 Precondition Failed
B->>API: GET /orders/ord_8f2k (re-read v8, merge)

On the server this is one conditional update: UPDATE orders SET ..., version = version + 1 WHERE id = $1 AND version = $2. Zero rows updated means someone else won. If you want to force clients to use it, reject unconditional writes with 428 Precondition Required. The same ETag also enables cheap reads: If-None-Match on GET returns 304 Not Modified with no body when nothing changed, which is how CDNs and browsers revalidate.

Long-running operations

Some work takes longer than any sane request timeout: generating a 2 GB export, provisioning a database, running a fraud review. Holding the HTTP connection open for minutes ties up a worker, dies on the first load balancer idle timeout, and gives the client nothing to resume from. The standard shape is 202 plus a status resource.

sequenceDiagram
participant C as Client
participant API as API
participant W as Worker
C->>API: POST /exports (Idempotency-Key k1)
API-->>C: 202 Accepted, Location /operations/op_91
API->>W: enqueue job op_91
C->>API: GET /operations/op_91
API-->>C: 200 status running, progress 40, Retry-After 5
W->>API: job done, result /exports/exp_3
C->>API: GET /operations/op_91
API-->>C: 200 status succeeded, result link

The operation resource has a small state machine (queued, running, succeeded, failed, cancelled), a progress hint, and on completion either a link to the result or a Problem Details error. Keep operation records for a documented period (for example 7 days) so a client that crashed can resume polling. For clients that cannot poll, add a completion webhook; the trade-offs between polling, webhooks and push are in real-time communication. Google’s public API guidelines (AIP-151) and Microsoft’s Azure REST guidelines both document this pattern, which is a good sign it works at scale.

Bulk operations and partial failure

Creating 10,000 products one request at a time costs 10,000 round trips. A bulk endpoint fixes that, but it raises a question single-item endpoints never had: what if item 4,312 fails?

You have two honest choices. All or nothing: validate everything, apply in one transaction, return 422 listing every bad item. Simple for clients, but one bad row blocks 9,999 good ones, and large transactions hold locks. Per-item results: apply each item independently and return a result array aligned with the input, each entry carrying its own status and, for failures, a Problem Details object. The HTTP status then describes the batch request itself (200 if it was processed, even with item failures), and clients must inspect every entry. Some APIs use 207 Multi-Status from WebDAV for this; plain 200 with a documented results array is more common and works with every client.

Whichever you choose: cap batch size (100 to 1,000 items is typical), require a client-supplied ID or idempotency key per item so a retried batch does not duplicate the items that already succeeded, and move large batches to the long-running pattern above.

Filtering, sorting and field selection

List endpoints need conventions as much as anything else. Common, readable choices:

  • Filters as query parameters named after fields: GET /orders?status=paid&created_after=2026-11-01T00:00:00Z. For richer needs, a small documented filter grammar (Google’s AIP-160 is one example) beats letting clients send raw SQL fragments.
  • Sorting with a single parameter and a minus for descending: sort=-created_at,id. Always append a unique tiebreaker so order is deterministic.
  • Field selection or expansion for heavy objects: fields=id,status,total to trim, expand=customer to embed a related object and save a round trip.
  • Only allow filters and sorts that are backed by an index. Every new combination is a query plan you have to support at full table size.

Pagination is its own topic with real performance traps; see pagination patterns for why deep offsets are slow and how cursors work.

Contract first: OpenAPI and AsyncAPI

Contract-first means writing the API description before the code, reviewing it like a design doc, and generating server stubs, client SDKs, mock servers and documentation from it. OpenAPI 3.1 aligned its schema dialect with JSON Schema 2020-12, which means the same schema can validate requests at runtime and generate types. OpenAPI 3.2 shipped in September 2025 as a backward-compatible update (streaming media types, hierarchical tags, more HTTP methods), so a 3.1 document upgrades by changing the version string. AsyncAPI (version 3.0 since late 2023) does the same for event-driven interfaces: channels, messages and their schemas for Kafka topics, webhooks or WebSocket streams.

The practical payoff is in CI. Lint the spec for your conventions (naming, error format, pagination) with a tool such as Spectral, and diff it against the main branch to block breaking changes before they merge. What counts as breaking is covered in API versioning and evolution.

Security basics every API needs

Authentication (who is calling) and authorization (what they may do) get a full treatment later in AuthN vs AuthZ and OAuth 2.1 and OpenID Connect. At design time, three things matter.

Authorise every object, not just every endpoint. The OWASP API Security Top 10 (2023), still the current edition, ranks Broken Object Level Authorization first: GET /orders/ord_123 works for the right user, and also for any other logged-in user who guesses the ID. The rest of the list is a good design review checklist: broken authentication, broken object property level authorization (mass assignment, over-exposed fields), unrestricted resource consumption (no page size caps or rate limits), broken function level authorization, unrestricted access to sensitive business flows, SSRF, security misconfiguration, improper inventory management (forgotten old versions) and unsafe consumption of third-party APIs.

Return only fields the caller may see, from an explicit response schema, never by serialising the database row. And accept only fields the caller may set; an allowlist stops a client from sending "role": "admin" in a profile update.

Understand CORS. Cross-Origin Resource Sharing is a browser rule, not server security. It decides whether JavaScript on app.example.com may read responses from api.example.com. Allow specific origins, never reflect the Origin header back with Access-Control-Allow-Credentials: true, and remember that curl ignores CORS entirely, so it protects your users’ browsers, not your API.

Compatibility rules from day one

Clients will depend on everything you ship, including things you did not mean to promise. Two defaults keep you out of trouble: only make additive changes (new optional fields, new endpoints, new optional parameters), and tell clients to ignore unknown fields. Versioning strategy, deprecation headers and what really counts as breaking live in API versioning and evolution.

Worked example: designing an orders API

Where it breaks

Leaking the database schema. Exposing tables one to one feels fast, but now a column rename is an API break and your internal normalisation becomes every partner’s problem. Model the resource the client needs; map it to storage in code.

Chatty APIs. If rendering one screen takes 14 calls, mobile clients on a 150 ms round trip spend 2 seconds waiting even with parallelism limits. Use expand, composite read endpoints, or a client-specific aggregation layer (the backend-for-frontend pattern in API gateway patterns).

Inconsistent conventions. One team returns createdAt, another created_on, a third a Unix integer. Each looks harmless in isolation. Together they force every SDK to special-case every endpoint. A linted style guide in CI is the only cure that sticks.

Errors that lie. A 500 for a validation failure triggers client retries and pages your on-call. A 404 for an authorization failure is sometimes right (do not reveal that the object exists), but a 404 for “your token expired” sends developers hunting for a missing record.

PATCH ambiguity. Does "note": null mean “clear the note” or “not provided”? JSON Merge Patch (RFC 7396) says null deletes. JSON Patch (RFC 6902) uses explicit operations. Pick one, declare it with the Content-Type, and document it.

Unbounded everything. No page size cap, no batch cap, no limit on expand depth. One client asking for limit=1000000 is a denial of service you wrote yourself. OWASP calls this unrestricted resource consumption.

Real-world systems

  • Stripe uses prefixed IDs (ch_, cus_), integer minor-unit amounts, Idempotency-Key on POST, expand[] for embedding related objects, and a structured error object with type, code and param fields.
  • GitHub REST API returns ETags and supports conditional requests; its docs note that a 304 Not Modified response to an authorised conditional request does not count against the primary rate limit. Pagination uses the Link header.
  • Google’s API Improvement Proposals (aip.dev) document resource-oriented design, standard methods, long-running operations (AIP-151) and a filtering grammar (AIP-160). They are the most complete public API style guide and worth reading whole.
  • Zalando’s RESTful API guidelines are another public, detailed style guide, and they recommend Problem Details for errors.

How to apply it

A design review checklist for any new endpoint:

  1. Is the path a plural noun, at most one level of nesting, with an opaque ID?
  2. Can every write be safely retried (PUT with a client ID, or an idempotency key)?
  3. Does every update that a human or two systems could race on require If-Match?
  4. Does every error return Problem Details with a stable type, all field errors, and a trace ID?
  5. Is any call slower than a few seconds at p99? Make it 202 plus an operation resource.
  6. Are list endpoints capped, cursor paginated, and filtered only on indexed fields?
  7. Does the response schema explicitly list fields, and does authorization check the object, not just the route?
  8. Is the change additive? If not, it needs a version plan before it merges.

Interview angle

Interview questions

Q1: Two support agents edit the same customer record and one change is lost. How do you fix it in the API?

Use optimistic concurrency. Every GET returns an ETag derived from a version column. Updates must send If-Match with that ETag; the server runs a conditional update (WHERE id = ? AND version = ?) and returns 412 Precondition Failed if zero rows changed. The client re-reads, shows the agent what changed, and lets them merge. Optionally return 428 for updates without If-Match so no client can skip the check. Pessimistic locks are a poor fit because HTTP clients can hold them indefinitely and vanish.

Q2: Your report generation endpoint takes 2 to 6 minutes. Clients see timeouts. What do you change?

Make it asynchronous. POST /reports validates input, enqueues a job and returns 202 Accepted with a Location header pointing to an operation resource such as /operations/op_91. The client polls that resource, guided by Retry-After, until it reaches succeeded (with a link to the report) or failed (with a Problem Details error). Accept an idempotency key so a retried POST does not start a second job. Offer a completion webhook for clients that prefer push. Keep operation records long enough for crashed clients to resume.

Q3: A bulk endpoint accepts 500 items and 3 fail validation. What should the response look like?

It depends on the documented contract, and the important part is that there is one. With all-or-nothing semantics, return 422 with Problem Details listing the 3 failures by index and apply none. With independent semantics, apply the 497, return 200 with a results array aligned to the input where 3 entries carry their own error objects, and require per-item idempotency keys so that resubmitting the corrected 3 (or the whole batch) does not duplicate the 497. Never return 200 with a single “partial success” flag that clients cannot act on.

✅ Key takeaways

  • Model resources from the client’s domain, with plural nouns, shallow nesting and opaque prefixed IDs. Never expose tables directly.
  • Status codes must tell the client whose fault it is and whether a retry helps. Errors use RFC 9457 Problem Details with a stable type, every failing field, and a trace ID.
  • Prevent lost updates with ETag plus If-Match (412 on conflict), and make every retryable write idempotent.
  • Slow work returns 202 with an operation resource. Bulk work needs explicit all-or-nothing or per-item semantics, caps and per-item idempotency.
  • Write the contract first in OpenAPI or AsyncAPI, lint it in CI, authorise every object (OWASP API1), and only make additive changes.

🧠 Check your understanding

0 / 4
  1. 1A PATCH arrives with If-Match set to an ETag the server no longer has, because another client updated the resource. What should the server return?

  2. 2Which field in an RFC 9457 Problem Details body should client code branch on?

  3. 3An export takes about 4 minutes. What is the best API shape?

  4. 4Which statement about CORS is correct?

Where to go next

  • REST vs GraphQL vs gRPC: when the resource model above should be expressed as a REST API, a graph, or a set of RPCs.
  • Pagination patterns: why OFFSET gets slow and how to design cursors that are fast and tamper-proof.
  • API versioning and evolution: what counts as a breaking change and how to retire old behaviour without breaking clients.
  • Idempotency: the server-side mechanics behind the idempotency keys used throughout this article.

Finished this lesson?

Mark it complete to track your progress across the roadmap.