# Progressive Delivery for Multi-Tenant SaaS

APIs outlive screens. Staff engineers model stable domain resources, ship additive changes with telemetry on deprecated fields, require idempotency on money-moving mutations, and enforce authorization on the server—so Expo clients and partner integrations upgrade on different calendars without surprise semantics.

Published: 2026-09-10

## Model the domain, not the screen

Interfaces change faster than the concepts behind them. An API built around a specific screen tends to expose presentation state and force duplicate endpoints as new clients appear—web, mobile, admin, partner webhooks.

Start with stable domain resources, their lifecycle, and the operations the business recognizes. This does not require theoretical purity. A product-facing API can aggregate data for a journey, but the aggregation should have a clear purpose, owner, and deprecation path when the journey changes.

Avoid leaking database tables directly. Storage structure is an implementation detail that will eventually need to change; consumers should depend on resource semantics, not column layouts. Supabase and Postgres MVPs often expose row shapes early—wrap them before external clients depend on primary keys as business identifiers.

For AI features, separate prompt orchestration from the domain resource the user cares about—an order, a ticket, a document. Otherwise model refactors become breaking API changes disguised as internal refactors.

Document which resources are public contract versus internal admin-only. Staff teams reject endpoints that exist only because one React component needed a join—those become permanent coupling.

When you sketch a new journey, write the resource diagram before the route list: which identifiers are stable, which operations are idempotent, and which events downstream systems consume. That diagram becomes the review artifact for security and mobile leads, not a slide that rots in a deck. If two screens need the same aggregate today, expose one named aggregate with explicit fields rather than two endpoints that diverge when product tweaks copy on only one surface.

## Compatibility is a feature

Consumers deploy on different schedules, especially mobile applications and external integrations. Additive changes are usually safer: new optional fields, new resources, and new enum values with tolerant readers. Removing or redefining existing behavior requires a migration plan, telemetry, and a published end date.

Versioning is useful when semantics genuinely diverge, but version numbers do not replace compatibility discipline. A versioned API can still surprise consumers through changed ordering, error behavior, rate limits, or authorization. Maintain a machine-readable schema and test representative consumers against it in CI.

| Change type | Default stance | Required evidence before ship |
| --- | --- | --- |
| New optional field | Allow | Schema diff + consumer smoke |
| New enum value | Allow with tolerant readers | Client parser audit |
| Rename field | Avoid; alias instead | Deprecation metrics at zero |
| Semantic change | New resource or epoch | Contract tests + comms plan |

Treat unknown enum values safely on clients—ignore or map to "unknown," never crash parsers. Document nullability and defaults in the schema, not only in prose docs that drift.

Measure deprecated-field usage before removal. If telemetry cannot answer "who still reads this field," the field is not ready to die—regardless of sprint pressure.

Ship schema diffs in pull requests the same way you ship SQL migrations: reviewers should see nullable changes, new enums, and default shifts in one place. Partner integrations often parse JSON by hand; a renamed key without an alias breaks silently until finance reconciles numbers. Publish a compatibility matrix in release notes—server version, minimum mobile build, and whether the change is additive-only—so support can answer tickets without paging backend on every store rollout.

## Mutations need identity

Retries are unavoidable across unreliable networks and background task queues. For important mutations, accept an idempotency key scoped to the caller and operation. Store the result so a repeated request returns the original outcome rather than performing the action again.

Long-running work should return an operation resource with explicit states. Clients can poll or subscribe without holding a fragile HTTP connection open. This also improves support: the system can explain whether work is queued, active, completed, or failed and why.

```typescript
export async function createPayment(req: Request) {
  const key = req.headers.get("Idempotency-Key");
  if (!key) return jsonError(400, "missing_idempotency_key");
  const tenantId = deriveTenant(req);
  const existing = await store.findPaymentIntent(tenantId, key);
  if (existing) return json(existing, { status: existing.httpStatus });
  const created = await processor.charge(/* … */);
  await store.savePaymentIntent(tenantId, key, created);
  return json(created, { status: 201 });
}
```

Expo and React Native apps should generate idempotency keys in the client for user-initiated actions and reuse the same key on retry until a terminal response arrives. Document key format and TTL in public API guides.

Pair idempotency with offline-first outbox patterns: queued mutations replay with the same key when sync drains—otherwise duplicate charges appear after airplane mode.

## Authorization belongs in the contract

Authentication establishes identity; authorization decides whether that identity may perform an operation on a resource. Enforce this on the server at the narrowest meaningful boundary. Hiding a button in the client is interface behavior, not access control.

Multi-tenant systems need tenant context that cannot be freely supplied and trusted by the client. Derive scope from verified membership, validate ownership on every resource access, and log administrative actions with enough context for audit and investigation.

Error responses should distinguish forbidden from not-found when safe—without enabling enumeration attacks on sensitive resources. Consistent error shapes matter more than clever HTTP status trivia; document which codes clients should retry.

Row-level security in Supabase is not a substitute for API authorization when clients talk to custom Workers or edge routes. One policy layer must be authoritative; staff teams test cross-tenant access attempts in CI, not only happy paths.

AI tool-calling endpoints need the same tenant binding as CRUD routes. A model-invoked tool that accepts raw tenant ids from the prompt is a future incident.

## Pagination, limits, and useful errors

Consistent naming, predictable pagination, useful errors, examples, and a clear change log reduce integration time more than clever protocol choices. Cursor pagination beats opaque offsets for large tables; document stable sort keys and tie-breakers.

Rate limits and quota headers should appear in the contract with retry guidance. Mobile clients backoff differently than server batch jobs—publish separate limits when necessary.

Errors carry machine-readable codes, human messages safe to show users, and optional detail objects for support. Avoid leaking stack traces or internal ids in production responses.

Include request correlation ids in responses and logs so support can trace a mobile report to server spans without asking users to reproduce in web only.

Publish maximum payload sizes and field counts early. AI endpoints that accept large JSON tool payloads need explicit limits to prevent accidental denial of service from verbose prompts.

For list endpoints, document default page size, maximum page size, and whether filters are stable across pages. Clients that cache the first page during background refresh should not see duplicate rows when sort keys change mid-pagination. Expose `hasMore` or cursor tokens rather than relying on empty pages alone—mobile list virtualization behaves poorly when totals jump without explanation.

Standardize problem details for validation errors: field path, constraint code, and a safe message. Integrators map those codes to localized UI strings; free-text-only errors force string matching that breaks on punctuation edits.

## Optimize for consumer understanding

An API is successful when consumers can use it correctly without learning its internal history. Design reviews should include client engineers and operational scenarios—on-call, support, and partner integration—not only backend implementers.

Maintain a changelog aimed at integrators: what changed, who is affected, and what action they must take. Link changelog entries to schema diffs and minimum client versions when mobile stores lag server deploys.

Contract tests run from consumer repositories against recorded fixtures—or against a staging schema gate—catch ordering and nullability surprises unit tests miss. Prioritize tests for payment, identity, and data-export flows.

For public APIs used by mobile clients, align with explicit API epoch headers or path prefixes documented in versioning guides. Shadow deprecated epochs in staging before enforcing blocks in production.

Staff engineers treat breaking-change requests as product decisions with dates, not as "just change the JSON." The interface will live longer than the first implementation—spend precision on identifiers, semantics, authorization, and lifecycle.

## Operational checklist for evolving APIs

Publish OpenAPI or protobuf schemas in the repo; CI fails when handlers violate the published contract for each active epoch.

Require idempotency keys on every mutation that moves money, sends messages, or writes irreversible state.

Instrument deprecated fields and enum values; block removal until usage crosses an agreed threshold for two measurement windows.

Run cross-tenant authorization tests on every pull request that touches resource access helpers.

Include mobile and web consumer representatives in API review for new resources—not only backend owners.

Document pagination, limits, and error codes in the same doc set as authentication—integrators read both on day one.

When adding AI routes, version prompt and tool schemas alongside HTTP resources so clients know which tool definitions match which server epoch.

Schedule quarterly client skew reviews: compare minimum app versions in the wild against deprecated API epochs still serving traffic.

Finally, delete unused endpoints deliberately: telemetry-first sunset, comms, then removal—never silent 404s on paths partners still poll.

Review API diffs in weekly demos with mobile and partner engineers so ordering and error-shape drift is caught before charts move.

Treat one-off query parameters as contract negotiations: promote them to documented optional fields with tests, or offer a supported aggregate—ad hoc params become permanent.

Prefer `Deprecation` and `Sunset` headers on HTTP responses so client CI can fail before users hit runtime surprises.

Log API epoch and app build id on Worker errors to separate stale-client incidents from authorization regressions.

Document browser-cookie versus service-token audiences on each route so CORS, CSRF, and rate limits stay coherent.

Run tabletops for removing a field while a double-digit share of mobile users lag two versions—product should already have comms templates.

Keep a living integration guide with curl examples, auth flows, and common failure modes—docs drift slower when they ship beside the schema in the same repository.
