Design web services around stable resource contracts, explicit versioning, and observable behavior rather than around your current database schema or framework. That single choice—treating the API surface as a product contract that evolves deliberately—drives most of the practical best practices: consistent resource naming, correct HTTP semantics, stateless request handling, pagination and filtering conventions, defensible error formats, security at the edge and between services, and measurable service-level objectives. The rest of this guide turns those principles into an ordered design process you can actually run, with checkpoints for each stage and the failure modes that show up when a step gets skipped.
Start with boundaries and consumers, not endpoints
Before you name a single URI, decide what the service owns and who calls it. Two questions shape everything downstream: is this a public-facing API, a partner API, or an internal service-to-service API, and what is the contract's blast radius if it breaks? Public APIs need long compatibility windows, careful documentation, and tolerant deprecation policies. Internal APIs can move faster but still need explicit semantics because independent teams will build against them and won't coordinate releases with you.
Domain boundaries matter here. A service should own a coherent slice of business capability—orders, billing, inventory—rather than a technical layer like "the user table." When boundaries follow data tables instead of business capabilities, every cross-table query becomes a chatty call between services, and your latency budget dies by a thousand round trips. The classic failure is a "user service" that returns raw rows and forces every consumer to reimplement the same validation and business rules.
Write down, in a short design document, the consumers, their critical use cases, expected request volumes, latency targets, and the data each consumer genuinely needs. You'll use that list later to check whether your resource model and payloads actually serve real callers.
Checkpoint: you can state in one sentence what the service owns, what it explicitly does not own, and which three consumer scenarios must work on day one.
Model resources and use HTTP semantics correctly
REST-style design works because it gives clients a predictable mental model: resources are nouns identified by URIs, and HTTP methods carry the verbs. Keep that mapping honest:
GET retrieves a representation and must not change server state. It should be safe and, where practical, cacheable. POST creates a subordinate resource or triggers a non-idempotent action, and should return 201 with a Location header when it creates something. PUT replaces a resource at a known URI and is idempotent—sending it twice yields the same end state. PATCH applies a partial modification; define the patch media type (JSON Merge Patch or JSON Patch) explicitly rather than leaving it ambiguous. DELETE removes a resource and is idempotent; a second delete should return 404 or 204 consistently, but never a 500.
Name resources with plural nouns and stable identifiers: /orders/1, /orders/1/line-items. Avoid verbs in paths for ordinary CRUD; reserve action-style sub-resources for operations that genuinely don't map to create/read/update/delete, such as /orders/1/cancel. Avoid exposing internal primary keys if they leak volume or sequencing information; a UUID or opaque identifier is often the better public key.
Return representations in a familiar format—JSON is the default expectation—with consistent field naming (pick camelCase or snake_case and never mix), consistent date formats (ISO 8601 with time zone), and explicit units in field names when ambiguity is possible (durationMs, amountCents, currency).
A subtle but important rule: use status codes for what they mean, not as generic success/failure flags. A validation failure is 400 with a machine-readable error body; a missing resource is 404; a duplicate create with a unique constraint is 409; rate limiting is 429 with a Retry-After header. Returning 200 with {"success": false} throws away HTTP's caching, monitoring, and client-library behavior.
Checkpoint: every endpoint has an explicit method, a documented success status, its error statuses, and idempotency behavior written down.
Design the contract for evolution from day one
Loose coupling means the client and service can change independently; that only happens if the contract is versioned and additive changes are the default. Practical rules:
Make additive changes freely: new optional response fields, new optional query parameters, new endpoints. Treat removals, renames, type changes, and tightened validation as breaking changes that require a new major version or a migration window. Never change the meaning of an existing field while keeping its name. Publish a machine-readable contract—OpenAPI for REST—and treat it as the source of truth for documentation, client generation, and contract tests.
Versioning strategy is a genuine trade-off rather than a universal answer. URI versioning (/v1/orders) is easy to route, cache, and explain, at the cost of some URI churn. Header or media-type versioning keeps URIs stable but is harder to test with a browser and easier to misconfigure in proxies and CDNs. For most teams, URI major versions plus additive evolution inside a version is the simplest workable default; the important part is consistency and a written deprecation policy with timelines and communication.
Deprecation deserves engineering effort: emit a Deprecation or Sunset header on responses from deprecated endpoints, document the migration path, and instrument usage so you know when it's actually safe to remove the old surface.
Checkpoint: you can demonstrate, with a diff of two contract versions, that a recent change was additive, and you have a documented rule for what counts as breaking.
Decide statelessness, identity, and session handling deliberately
Keep each request self-contained: authentication credentials, tenant context, and any needed parameters travel with the request. Statelessness lets you scale horizontally, retry safely, and route requests to any instance without sticky sessions. Where you need server-side state—shopping carts, multi-step workflows—store it in a shared, durable backing store keyed by an identifier the client carries, not in process memory.
Identity propagation is part of the contract. Use short-lived tokens (OAuth 2.0 bearer tokens, or workload identity for service-to-service calls) and pass a correlation identifier such as traceparent or an X-Request-Id in headers so logs across services can be joined. Do not put secrets or sensitive personal data in URLs—URLs land in access logs, browser history, and referrer headers.
A common mistake is conflating authentication with authorization. Authenticate the caller at the edge, then authorize per resource using scopes, roles, or policy checks inside the service. If an endpoint returns another tenant's object because it looked up by ID without an ownership check, that's an object-level authorization bug, and it's one of the most frequently exploited classes of API flaw. Test for it explicitly with a different-tenant token.
Set conventions for collections, pagination, and filtering
Collections are where APIs quietly become unusable. Decide and document:
Pagination: cursor-based pagination (opaque token in the response) scales better for large or changing datasets; offset/limit is simpler and fine for small, stable collections. Either way, define a default and maximum page size and enforce them. Filtering and sorting: use query parameters with a documented grammar (?status=open&sort=-createdAt), validate the allowed fields, and reject unknown sort keys with a clear error rather than silently ignoring them. Field selection: for heavy resources, support sparse fieldsets or a documented expansion parameter so mobile clients aren't forced to download nested objects they never render. Response envelope: either return a bare array with pagination metadata in headers or a wrapped object with items and paging links. Wrapping is easier to extend; bare arrays are simpler but hard to evolve. Pick one and apply it everywhere.
Document the maximum payload size and behavior when it's exceeded. Returning a 413 with a helpful message beats truncating data silently.
Standardize errors and make them actionable
An error body should let a competent client developer fix the problem without reading your source. A workable shape includes a stable machine-readable code, a human-readable message, the specific field or parameter at fault when applicable, and a correlation ID for support. Avoid leaking stack traces, SQL fragments, or internal hostnames.
Separate the categories of failure so clients can respond differently: transient failures (retry with backoff), rate limits (retry after the stated interval), authentication failures (refresh credentials), authorization failures (don't retry), validation failures (fix the request), and conflicts (resolve state). Map them consistently to 4xx and 5xx statuses, and make sure your gateway and service agree—nothing confuses consumers more than a 502 emitted by a proxy where the service would have returned 400.
Checkpoint: you can trigger each error category in a test environment and show the exact response body a client would receive.
Treat performance and reliability as design constraints
Latency targets should be stated in the design document and designed for, not measured after launch. Practical decisions that follow from a target:
Prevent chatty interfaces by shaping responses around consumer use cases (but avoid returning unbounded nested graphs by default). Use caching: Cache-Control, ETag, and conditional requests for GET endpoints, and a shared cache or CDN for public read-heavy APIs. Support idempotency for retry-prone writes. Accept an Idempotency-Key header on POST endpoints that create resources, store the key and result for a defined window, and return the original result on replay. This is what lets clients retry safely after a timeout. Apply rate limits and quota policies at the edge, return 429 with Retry-After, and document limits per consumer tier. Set timeouts and bounded retries everywhere; unbounded retries from clients against a struggling service create retry storms that finish the job.
Load-shedding and backpressure belong in the design, not the incident review. If the service cannot meet its latency objective under overload, decide in advance what it rejects and how it signals that.
Decide sync versus async communication per interaction
Not every operation should be a synchronous request. Ask whether the caller needs the result immediately to proceed. If it does—reading a record, validating a form—use a synchronous API. If it's a long-running process, a fan-out notification, or a workflow that can take minutes, accept the request, return 202 with a status resource, and process asynchronously, or publish an event for consumers to react to.
Events introduce their own contract problems: schema evolution, ordering, duplicate delivery, and consumer lag. Document the delivery semantics (at-least-once is the realistic default), include an event ID and timestamp, version the event schema, and tell consumers how to handle duplicates and out-of-order arrivals.
Synchronous chains are also a risk: a request that fans out to five services with no timeouts and no circuit breaking can take down everything when one dependency degrades. Set timeouts, use circuit breakers for unreliable dependencies, and prefer graceful degradation (partial response or cached fallback) over total failure where the business allows it.
Secure the service across its whole surface
Security is not a layer you add later. The design should specify authentication mechanisms, authorization model, transport encryption (TLS everywhere, including internal traffic), input validation and output encoding, and how sensitive data is handled in logs and errors.
Practical checklist items that catch real vulnerabilities:
Validate every input against an allowlist of expected types and ranges; reject unknown fields on write endpoints or document that they're ignored. Enforce authorization on every object access, not just at the route level. Require TLS, set HSTS, and disable weak protocol versions at the edge. Never return secrets, tokens, or full personal records in list endpoints; use masked or separate detail endpoints. Log security-relevant events (auth failures, permission denials, admin actions) with correlation IDs but without credentials or sensitive payloads. Keep dependencies patched and track known vulnerabilities; an expired TLS certificate or a forgotten debug endpoint is a failure the design review should have prevented.
The CMS SOA service design guidance frames this well: consider security early, as part of the design process rather than a gate at the end. You can read the CMS web services and SOA design principles for a service-oriented framing that includes standardized contracts, abstraction, reusability, and autonomy alongside security.
Operate the service with observability built in
A web service design isn't finished until you can tell whether it's working. Specify from the start:
Structured logs with consistent fields (timestamp, service, trace ID, request ID, status, latency) that never include raw credentials or full personal data. Metrics per endpoint: request rate, error rate by status class, and latency percentiles (p50, p95, p99). Percentiles matter more than averages because averages hide the tail that users feel. Distributed tracing across service hops, using a standard propagation format so the trace survives gateways and async boundaries. Service-level objectives with error budgets, so reliability trade-offs are explicit rather than debated in incidents.
A worked example makes the value concrete. If your orders API serves 2 million requests a day and 99.9% of them must respond within 300 ms, that's roughly 2,000 requests a day—about one every 43 seconds—permitted to exceed 300 ms over a 24-hour window. That budget is what justifies the cost of caching, connection pooling, and replicas. It also tells you when to stop optimizing: spending engineering time to shave 20 ms off a p50 already inside budget is often misallocated.
Put the process together: an ordered design workflow
Here's the sequence that makes the earlier sections operational. It's deliberately front-loaded with decisions that are expensive to reverse.
Prerequisites: a documented list of consumers and critical use cases; the service's ownership boundary; a latency and availability target; an identity and authorization model; and a team agreement on API style (REST with OpenAPI, or an explicitly chosen alternative).
1: Write the design document: boundary, consumers, use cases, non-functional targets. Review it with a consumer. 2: Draft the resource model and URI structure as a diagram and a list of endpoints with methods and statuses. 3: Draft the request and response schemas, including error bodies, pagination shape, and versioning scheme. 4: Write the OpenAPI contract and a set of contract tests that encode the rules above (field naming, required headers, error formats). 5: Prototype the two or three riskiest endpoints and check the design against a real consumer's code path. 6: Implement authentication, authorization, rate limiting, timeouts, and idempotency before exposing any endpoint externally. 7: Instrument logs, metrics, and tracing; define the SLOs and dashboards. 8: Run a security and contract review, then publish the documentation and a deprecation policy.
Success check: a consumer team can build an integration against the OpenAPI document and documentation alone, without asking you questions about field meanings, error handling, or versioning. If they can't, the contract isn't finished.
Stop conditions: if the review uncovers an object-level authorization gap, a breaking change already shipped without a version, or a dependency with no timeout in the critical path, stop release and fix it—these are the defects that turn into incidents.
The trade-offs you'll actually argue about
Best practices aren't free, and the arguments are worth having explicitly rather than by accident.
Granularity versus chatiness. Fine-grained resources and endpoints are reusable and easy to reason about, but consumers often need composite views. A cautious default is coarse-grained read endpoints for consumer screens plus fine-grained resources for updates. The cost of coarse endpoints is duplication and potential over-fetching; the cost of fine endpoints is latency and client complexity.
Strictness versus tolerance. Strict validation with unknown-field rejection catches client bugs early but breaks consumers who send extra fields. Tolerance (ignore unknown fields on input, add fields on output freely) maximizes compatibility but lets typos pass silently. A reasonable split: reject unknown fields on writes, ignore unknown fields on reads, and always accept additive additions.
Versioning cost versus stability. Every major version carries a maintenance and support burden, so teams are tempted to avoid them and instead make "small" breaking changes. That's usually a false economy—the migration debt shows up later, in production, with no deprecation notice.
Synchronous simplicity versus asynchronous resilience. Synchronous calls are easier to reason about and debug; asynchronous flows decouple availability but add eventual consistency, duplicate handling, and operational complexity. Choose per interaction, not per organization.
REST versus RPC style. REST's resource model fits CRUD-heavy domains with clear entities. For action-heavy or highly transactional domains, an RPC-style interface (or GraphQL for flexible client-driven queries) can be clearer. The design principles in this article—versioning, error consistency, security, observability—apply regardless of style; only the surface conventions change.
Where designs most often fail
Reviewing your own design against these failure modes is faster than learning them in production:
Leaky abstractions: returning database rows with internal columns, or exposing internal enum values that then must never change. Inconsistent errors: different endpoints using different error shapes, or the gateway and service disagreeing on status codes. No pagination limits: an endpoint that returns all records until one day it doesn't. Version drift: a documented versioning scheme that nobody follows after the first breaking change. Missing authorization checks on nested resources, like /orders/1/line-items/5 fetched with a token for a different order owner. No idempotency on writes: clients retry after a timeout and create duplicate records. Unbounded fan-out: a single request that calls five services sequentially with default timeouts. Observability afterthoughts: no trace correlation across services, so an incident investigation stalls at the first service boundary.
Each of these is cheaper to prevent at design time than to remediate after consumers depend on the behavior.
FAQ
Should I always use REST? No. REST is a strong default for resource-oriented domains and HTTP-based public APIs. Action-heavy domains may fit an RPC style better, and client-driven data needs may favor GraphQL. Keep the contract, versioning, security, and observability discipline regardless of style.
How many API versions should we maintain at once? There's no universal number, but a practical policy is to support the current major version plus at most one predecessor, with a published sunset date and usage monitoring to confirm the old version is actually drained before removal.
Is statelessness incompatible with server-side sessions? Not incompatible, just displaced. Store session state in a shared durable store and key it by a token the client carries, so any instance can serve any request without sticky routing.
What's the minimum viable observability for a new service? Structured logs with trace and request IDs, per-endpoint latency and error-rate metrics, and distributed trace propagation across hops. That's enough to diagnose most incidents without guesswork.