A SaaS API is a product boundary, not a thin route to a database table. Each endpoint makes a promise about who may call it, what input it accepts, which state changes together, which side effects follow, and what the caller sees when something fails. When those promises are vague, the bugs show up later as data leaks between tenants, duplicate charges, and support tickets nobody can trace.
I use this backend API design checklist before adding an endpoint and when reviewing a feature that crosses the frontend and backend. It is deliberately independent of REST, GraphQL, or RPC. The style matters less than whether each operation is safe, comprehensible, and observable.
The request path every operation should follow
Most API problems come from skipping or reordering one of a few steps. A write operation in a multi-tenant product should follow roughly this sequence:
flowchart LR
accTitle: Safe SaaS API write path
accDescr: A request is authenticated, its tenant and membership are resolved, the operation is authorized, input is validated, and an idempotency key is checked. A single transaction writes durable state and an outbox event. The response carries a request identifier, and asynchronous work happens after commit.
R["Request"] --> AU["Authenticate"]
AU --> T["Resolve tenant and membership"]
T --> AZ["Authorize operation"]
AZ --> V["Validate input"]
V --> I{"Idempotency key seen?"}
I -->|"Yes"| P["Return stored result"]
I -->|"No"| TX["Transaction"]
TX --> S[("Durable state")]
TX --> O[("Outbox event")]
TX --> RS["Response with request id"]
O --> W["Async work after commit"]
Read operations skip the idempotency and outbox steps but keep the same order for identity, tenant, and authorization.
Contract and ownership
An endpoint’s contract should describe a business action, not an implementation.
- Name the operation after a business action, not an internal table or function.
- Define request and response schemas at the boundary and validate against them.
- State which fields the caller may set and which the server owns, such as ids, timestamps, status, and tenant.
- Use stable, opaque identifiers rather than exposing sequential database ids where enumeration is a risk.
- Document what the operation does when the target already exists, is archived, or is missing.
- Decide which module owns the business rule, and keep it out of the route handler.
For example, POST /projects/:projectId/members should define who may add whom, whether adding an existing member is a no-op or a conflict, which role is assigned by default, and whether an invitation email follows. It should not expose an insertMember helper with whatever fields the table happens to have.
Mass assignment is a common contract failure. If the handler passes the request body straight into an update, a caller can set role, tenantId, or isAdmin. Map allowed fields explicitly.
Authentication and authorization
Authentication answers who is calling. Authorization answers whether that identity may perform this operation on this resource right now.
- Every non-public operation requires authentication on the server.
- Authorization is checked per operation and per resource, not only per route group.
- Authorization runs on the server even when the frontend hides the action.
- Role and membership changes take effect on existing sessions within a known time.
- Service accounts and API keys have the narrowest scopes that work.
- Sensitive actions such as role changes, exports, and deletions are recorded in an audit log.
Keep authorization rules in one place, such as a policy module, rather than scattering if (user.role === ...) checks across handlers. Duplicated checks drift, and drift is how removed members keep access.
Test the API directly with missing, expired, and insufficient credentials. A test that only clicks through the UI cannot prove the boundary.
Tenant isolation
In a multi-tenant SaaS, the most damaging bug is one tenant reading or changing another tenant’s data.
- Resolve the tenant from the authenticated context or a verified path parameter, never from an unchecked body field.
- Confirm membership in that tenant before loading tenant-owned data.
- Scope every query by tenant, preferably through a shared data-access layer that makes omission difficult.
- Include the tenant key in relevant unique constraints and indexes.
- Return “not found” rather than “forbidden” for resources in other tenants when existence itself is sensitive.
- Test cross-tenant access explicitly: a valid user of tenant A requesting a resource id from tenant B.
Database-level protections such as row-level security can add a second layer, but they do not replace a clear tenant model in the application. The database schema review checklist covers how tenant keys belong in constraints and indexes.
Validation and business rules
| Layer | What it checks | Example |
|---|---|---|
| Schema validation | Shape, types, required fields, lengths | email is a string and a valid address |
| Business validation | Rules that depend on current state | The project is not archived; the plan allows another seat |
| Database constraints | Invariants that must hold under concurrency | Email is unique within the organization |
All three layers matter. Schema validation gives clients fast, specific errors. Business validation enforces product rules. Database constraints catch the race conditions that application checks miss: two requests that both “check then insert” at the same moment will both pass the check.
Transactions and side effects
Decide explicitly which state must change together.
- Group writes that must succeed or fail together in one transaction.
- Keep slow external calls outside the transaction where possible.
- Do not perform an irreversible vendor call before knowing whether the local write will commit.
- Record follow-up work in an outbox within the same transaction.
- Return a status the client can follow when work completes asynchronously.
A frequent bug: the handler charges a card, then the database write fails, and the customer is charged for an order that does not exist. Reverse the order where the provider allows it, or create a pending local record first, call the provider with an idempotency key, and reconcile.
For asynchronous follow-up work, the handoff must be durable. See how to design background jobs that do not lose work for the outbox pattern and retry policy.
Idempotent writes
Networks retry. Browsers double-submit. Mobile clients resend after reconnecting. Workers run again after a timeout.
For operations where duplication is harmful, such as charging, inviting, creating an order, or triggering a workflow:
- Accept an
Idempotency-Keyheader or an equivalent client-generated operation id. - Store the key, a fingerprint of the request, and the first successful response.
- Return the stored response for repeated requests with the same key.
- Reject a reused key with a different request body.
- Expire stored keys after a period that covers realistic client retries.
- Back the logic with a database constraint on the business identity.
Natural idempotency is even better when available. PUT that sets a final state, or “add member” that is a no-op when the member exists, needs no key.
Errors a client can handle
Use one error shape across the API:
{
"error": {
"code": "member_already_exists",
"message": "This person is already a member of the project.",
"details": [{ "field": "email", "issue": "duplicate" }],
"requestId": "req_7f3a9c"
}
}
- Stable, machine-readable codes that clients switch on.
- Clear distinction between invalid input, unauthenticated, forbidden, not found, conflict, rate limited, and server error.
- Field-level details for validation failures.
- A request identifier in every response, also present in server logs.
- No stack traces, SQL, or internal hostnames in responses.
Clients should never parse the message text to decide what to do. Messages change; codes should not.
Lists, pagination, and filtering
- Every list endpoint is paginated from the first release.
- Use cursor pagination for large or frequently changing collections.
- Define a stable sort order that includes a unique tiebreaker.
- Set a maximum page size on the server.
- Allow filtering only on fields with supporting indexes.
An unpaginated list works in development with ten rows and times out in production with a large tenant. Adding pagination later is a breaking change.
Versioning and change management
- Additive changes, such as new optional fields, are the default.
- Never change the meaning or type of an existing field.
- Removing a field or endpoint follows a deprecation period with usage monitoring.
- External or partner APIs have an explicit versioning strategy.
- Generated types or an OpenAPI schema keep clients and server in sync.
For an API consumed only by your own frontend, deploying both together reduces versioning needs, but long-lived browser tabs and mobile apps still run old clients. Design changes to be backward compatible for at least one release.
Rate limits and abuse protection
- Limits per user, per API key, and per tenant for expensive operations.
- Stricter limits on authentication, password reset, and invitation endpoints.
- A clear rate-limit error with a retry hint.
- Request size limits and timeouts on uploads and imports.
Operational visibility
Every operation should be traceable after the fact.
- Log the request id, operation name, actor, tenant, outcome, and latency.
- Never log passwords, tokens, full card data, or raw request bodies with personal data.
- Track error rate and latency per operation, not only per service.
- Propagate the request id into jobs, events, and outbound calls.
When support asks “why did this customer’s invitation fail?”, the answer should take minutes. The production logging and observability checklist covers which fields and alerts to start with.
Review questions for every new endpoint
Before merging, ask:
- Who may call this, and where is that enforced on the server?
- Which tenant owns the data, and can a caller from another tenant reach it?
- What state must commit together?
- What happens if the response is lost and the client retries?
- What happens if an external call times out after succeeding?
- Which module owns the business rule?
- What does the client see for each failure, and can it act on it?
- How will support trace one failed request?
Those questions expose more risk than arguments about REST versus GraphQL. For the wider system context, use the full-stack architecture review checklist.
Backend API design checklist summary
- Business-shaped operation with explicit request and response schemas.
- Server-owned fields mapped explicitly; no mass assignment.
- Authentication, tenant resolution, membership, and authorization on the server.
- Cross-tenant access tested.
- Schema, business, and database-level validation.
- Clear transaction boundary; side effects after commit through an outbox.
- Idempotency for harmful duplicate writes.
- Consistent error shape with stable codes and request ids.
- Paginated lists with stable ordering and a maximum page size.
- Additive versioning and a deprecation path.
- Rate limits on expensive and sensitive operations.
- Structured logs and per-operation metrics with safe fields only.
A good API makes the safe path the easy path for every client, including the frontend you build next year and the integration a customer builds without asking you first.
Frequently asked questions
What should a backend API design checklist cover?
It should cover the operation's business contract, request and response schemas, authentication and authorization, tenant isolation, validation, transaction boundaries, idempotency for retried writes, error format, pagination, versioning, rate limits, and the logs and identifiers support needs to trace a request.
Is REST or GraphQL better for a SaaS API?
Either can work. Authorization, tenant isolation, idempotency, error handling, and observability cause more production problems than the choice of style. Pick the style your clients and team can support, then apply the same checklist to every operation.
How do you make API writes safe to retry?
Accept an idempotency key for operations where duplication is harmful, store the key with the first successful result in the same transaction as the change, return that stored result for repeated requests, and back the logic with database constraints.
Where should authorization happen in a SaaS API?
On the server, for every operation, after resolving the caller's identity, tenant, and membership and before loading or changing tenant-owned data. Hiding a button in the frontend is not authorization.
How should API errors be structured?
Use one consistent shape with a stable machine-readable code, a human-readable message, field-level details for validation errors, and a request identifier that appears in server logs. Clients should never need to parse message text to decide what to do.
Keep reading
- Architecture, DevOps & Delivery How to Design Background Jobs That Do Not Lose Work
- Architecture, DevOps & Delivery Event-Driven Architecture for SaaS: Where It Helps and Where It Adds Risk
- Architecture, DevOps & Delivery Full-Stack Architecture Review Checklist: Frontend, API, Database, and Deployment