Skip to content
All articles
· 15 min read

Scaling an API to 1M Users: From Traffic Math to Failure Testing

A practical guide to capacity planning, database performance, caching, horizontal scaling, durable jobs, and failure testing—with original architecture diagrams.

On this page

One million registered users is a product milestone. The engineering problem starts with a different set of questions: how many requests arrive each second, what does each request cost, and what happens when a dependency gets slow?

This guide develops a worked design for a read-heavy API with one million accounts. The traffic estimates, latency targets, and replica capacities below are illustrative planning inputs. They are not measurements from a production system I operated. Replace them with measurements from your own application.

The goal is an API that stays responsive, preserves correctness, and fails predictably when demand exceeds capacity.

1. Translate users into a workload

Start with an explicit model rather than a server count. For this example, assume:

InputIllustrative value
Registered accounts1,000,000
Daily active users100,000, or 10% of accounts
API requests per active user per day20
Read / write mix90% / 10%
Peak-to-average multiplier20×
Short burst allowance above peak2×

The arithmetic is straightforward:

Daily requests = 100,000 × 20 = 2,000,000
Average RPS    = 2,000,000 / 86,400 ≈ 23.1
Peak RPS       = 23.1 × 20 ≈ 463
Burst RPS      = 463 × 2 ≈ 926
Planning target, rounded up: 1,000 requests/second

Demand model: one million accounts become one hundred thousand daily users, two million daily requests, about 23 average RPS, and an illustrative burst target of 1,000 RPS.Original illustration · Open full-size diagram

A million concurrent users would be a very different workload. Long-lived WebSockets also need a separate model for open connections, memory per connection, reconnect bursts, and messages per second. Neither case is covered by the account-count calculation above.

Record the distribution across endpoints. A cached product lookup, an authenticated account summary, and a PDF export can have radically different costs. Include payload size, geographic distribution, polling intervals, bots, and the busiest tenant. If your model treats all requests as identical, a single expensive endpoint can invalidate it.

For a rough concurrency check, use Little’s Law at a stable operating point: average in-flight requests equal arrival rate multiplied by mean response time. At 1,000 RPS and 200 ms mean latency, roughly 200 requests are in flight. At two seconds, that becomes 2,000. This relationship explains why a slow dependency can exhaust resources before request volume changes.

2. Define what good service means

Choose a user-visible objective before tuning infrastructure. A starting contract for this example might be:

  • 99.9% successful eligible requests over a rolling 30-day window.
  • p95 response latency below 250 ms and p99 below 800 ms for interactive endpoints.
  • Separate completion-time objectives for exports and other asynchronous operations.
  • A documented freshness limit for cacheable data.

These are design choices, not universal targets. Define which requests count, where latency is measured, and how rejected or timed-out requests affect the objective. Do not quietly exclude overload responses from the success metric.

Track errors and latency by route and tenant class, alongside CPU, memory, event-loop lag, database pool waits, and queue age. An aggregate average can hide a broken checkout flow behind thousands of fast health checks. Google’s Managing Load chapter is useful context for combining traffic management with reliability goals.

3. Begin with a small, measurable architecture

A modular API application, a relational database, and a controlled deployment are a reasonable starting point. Separate code by domain, keep the request path observable, and make it possible to deploy multiple identical API instances.

Add components when they solve an observed problem. A cache reduces repeated read work. A queue separates slow work from interactive requests. A load balancer spreads requests across healthy replicas. Each also creates a new failure mode and something the team must operate.

Example architecture: clients pass through an edge and load balancer to six API replicas across three zones. Redis handles cache-aside reads, bounded pools protect a PostgreSQL primary and failover standby, and an outbox feeds a durable queue and workers.Original illustration · Open full-size diagram

The drawing represents a later stage of the example, after those needs have been established. It does not mean every API should launch with six replicas or three zones. The API capacity calculation appears below; cache, database, worker, and load-balancer failure capacity must each be validated separately.

Keep request-serving state outside an individual API process. Shared records belong in the database, durable files in object storage, and durable jobs in a queue or outbox. Local memoization can be useful, but a different replica must be able to handle the next request correctly.

4. Make each database request cheaper

Scaling API replicas while leaving expensive queries unchanged often just sends more simultaneous work to the database. First inspect slow routes and remove unnecessary work: repeated ORM lookups, N+1 queries, unbounded result sets, and fields the caller does not use.

Suppose a tenant-scoped endpoint lists recent orders. A cursor query could look like this:

-- Illustrative schema: id is a bigint, created_at is NOT NULL.
CREATE INDEX orders_tenant_created_id_idx
  ON orders (tenant_id, created_at DESC, id DESC);

SELECT id, status, total_cents, created_at
FROM orders
WHERE tenant_id = $1
  AND (created_at, id) < ($2::timestamptz, $3::bigint)
ORDER BY created_at DESC, id DESC
LIMIT 50;

For the first page, omit the cursor predicate. The ID provides a deterministic tie-breaker for orders with the same timestamp. Take the tenant ID from the authenticated context, validate the cursor, and enforce the limit on the server. Cursor pagination avoids increasingly large offsets, but concurrent updates still require a clear pagination contract.

Use representative data and EXPLAIN (ANALYZE, BUFFERS) to inspect the actual plan, row estimates, and I/O. ANALYZE executes the query; use controlled environments when investigating statements with side effects. PostgreSQL’s multicolumn index guidance and EXPLAIN documentation explain the underlying behavior. An index is not free: it consumes storage and adds maintenance to writes. Measure the whole workload before keeping it.

Also watch transaction length and lock waits. A small query inside a transaction that waits on a remote API can hold a connection and locks for far longer than the query itself. Keep external calls out of database transactions where the business workflow allows it.

5. Treat database connections as a shared budget

Every process does not get an independent claim on the database’s full connection limit. Count API replicas, worker processes, scheduled jobs, migration tools, and overlapping deployments together.

Example backend connection budget: 200
Reserve for administration and other clients: 40
API allocation: 120
Worker allocation: 40

At 6 API replicas: API pool cap = 120 / 6 = 20 per replica
At 12 overlapping replicas:    = 120 / 12 = 10 per replica

Those numbers illustrate allocation, not a recommendation to set PostgreSQL to 200 connections. Find the useful database concurrency under load; more active queries can make throughput worse once CPU, I/O, or locks saturate.

Put a deadline on acquiring a connection and observe the wait time. If the wait queue grows without a bound, latency can increase even when the database appears healthy. A pooler such as PgBouncer can multiplex connections, but it does not make queries cheaper. Its pooling modes have different semantics; transaction pooling requires checking compatibility with session-level features in your driver and application.

6. Cache the work that can safely be reused

Choose cache candidates by repeated cost and an explicit freshness policy. Public catalog data might tolerate 30 seconds of staleness. An authorization decision or a balance immediately after a write might not.

For an application-level cache-aside read, the API authorizes the request, builds a scoped key, checks Redis, and fetches from the database on a miss. It then stores the result with an expiry. The cache remains a derived copy of the durable data.

Cache-aside flow: authorize, look up a scoped key, return a cache hit, or coalesce misses before a bounded database read and cache fill with TTL jitter.Original illustration · Open full-size diagram

Use keys that include the tenant, resource, schema version, and any dimensions that change the representation. Decide whether permissions affect the result. Avoid sharing a cached personalized response across users. For HTTP caches, understand private, no-store, Vary, and authenticated-response rules before enabling a shared edge cache. RFC 9111 defines these semantics.

A hot key expiring can send many simultaneous misses to the database. Coalesce equivalent work and vary expiry times so unrelated keys do not all expire together. Process-local coalescing only deduplicates within one replica; limiting fleet-wide fills requires shared coordination or an equivalent refresh design. Redis describes these tradeoffs in its cache-layer architecture guide.

Expiry is only one part of correctness. A write followed by invalidation can race with an older in-flight reader that repopulates stale data. For stricter requirements, use versioned data or a consistency-aware refresh strategy, or bypass the cache. Decide what the caller is allowed to observe.

Set a memory limit and an eviction policy appropriate for a disposable cache; monitor hit ratio, evictions, and fill latency. Do not mix an evictable cache with indispensable job or coordination state without understanding the consequences. The Redis eviction documentation covers the available policies.

Finally, load-test cache failure. If normal traffic depends on a 95% hit rate, allowing every request to fall through can overwhelm the database. A cache outage may require tighter admission limits or degraded responses, rather than unrestricted fallback.

7. Scale API replicas with failure headroom

Measure safe per-replica throughput using the real endpoint mix and the intended resource limits. Suppose one replica can sustain 250 RPS while meeting the latency objective, with the database and dependencies still healthy.

Target peak load:               1,000 RPS
Measured safe replica capacity:   250 RPS
Minimum serving replicas:      ceil(1,000 / 250) = 4
Survive one replica loss:       5 replicas total

The architecture diagram uses a different failure allowance: six replicas, two in each of three zones. Losing one zone leaves four replicas, which would provide 1,000 RPS under the assumed per-replica capacity. This is conditional arithmetic. A zone loss can also affect the database, cache, network, or queue, so test the complete failure path.

Scale before resources saturate. CPU may work for compute-heavy routes; in-flight requests, pool waits, and event-loop lag can be better signals for an I/O-bound API. Keep a minimum warm fleet for bursts that arrive faster than new instances start. Limit the maximum fleet size according to downstream capacity.

Use readiness checks, stop routing new requests to draining instances, and give in-flight work a bounded time to finish. During rolling deployments, include temporary replicas in both the connection budget and the cost model. Load-balancing capacity alone does not guarantee useful capacity at the database.

8. Move slow work behind a durable boundary

Email delivery, report generation, image processing, and outbound webhooks usually do not need to finish before the interactive response returns. Accept an operation, persist its state, and return a job identifier with a status endpoint when that matches the product’s behavior.

The hard part is committing the business change and reliably handing off the job. Writing a row and then publishing a message creates a gap: the process can fail between those operations. An outbox records the business change and the event in the same database transaction. A relay publishes committed events later.

Transactional outbox: one database transaction saves a business row and an outbox event; a relay publishes to a durable queue; an idempotent worker applies the effect and acknowledges after success.Original illustration · Open full-size diagram

Expect duplicates if the relay crashes after publishing but before marking the event, or a worker fails before acknowledging. Use stable event IDs and make effects idempotent. For a database-only effect, record the processed event and the mutation atomically. For an external effect, pass a stable idempotency key to a provider that supports one, and reconcile ambiguous outcomes. AWS’s transactional outbox guidance discusses the dual-write problem and duplicate delivery.

A queue buffers work; it does not create processing capacity. If jobs arrive at 120 per second and workers complete 100, the backlog grows by 20 every second. Track the oldest job’s age, set retry limits, and move poison jobs to an inspectable dead-letter queue. Bound worker concurrency so scaling consumers does not overwhelm the database or a vendor.

9. Bound the damage during overload

There should be a limit on request body size, page size, fan-out, in-flight work, connection waits, and execution time. Choose those bounds from measured behavior and product requirements.

Apply rate limits per authenticated identity or tenant where possible, with additional coarse protection at the edge. A fleet-wide quota needs coordinated enforcement; a per-process counter alone multiplies the allowed traffic as replicas increase. Return a meaningful 429 for a quota violation. Capacity protection can reject work with 503 when appropriate, rather than accepting an unlimited backlog. Consider Retry-After where the delay can be meaningfully estimated.

Prioritize core workflows over optional work. If a recommendation service is slow, an account page may still work without recommendations. Rejecting excess work early can preserve capacity for requests you can complete; AWS’s load-shedding discussion explains why merely increasing connection limits is insufficient.

Carry a deadline through downstream calls and cancel work when it is no longer useful. Use bounded retries for selected transient failures, exponential backoff, and jitter. A timeout does not prove a write failed, so retries of mutations require idempotency. Avoid independent retry loops at every layer: they multiply attempts. Timeouts, retries, and backoff with jitter gives the reasoning behind these controls.

10. Test the workload, then test the failure

Run load tests against an environment you control, with representative data volume, authorization, tenant skew, and background activity. A health endpoint or a tiny empty database will give misleading confidence.

Here is a focused k6 example for one authenticated catalog route. It schedules 1,000 iterations per second, with one request per iteration. It is an initial route test; expand it into the read/write mix from the capacity model before drawing system-wide conclusions.

import http from 'k6/http';
import { check } from 'k6';

const baseURL = __ENV.BASE_URL;
const token = __ENV.API_TOKEN;
if (!baseURL || !token) {
  throw new Error('Set BASE_URL and API_TOKEN for your test environment');
}

export const options = {
  scenarios: {
    catalog: {
      executor: 'constant-arrival-rate',
      rate: 1000,
      timeUnit: '1s',
      duration: '10m',
      preAllocatedVUs: 300,
      maxVUs: 1000,
    },
  },
  thresholds: {
    http_req_duration: ['p(95)<250', 'p(99)<800'],
    http_req_failed: ['rate<0.001'],
    checks: ['rate>0.999'],
    dropped_iterations: ['count==0'],
  },
};

export default function () {
  const response = http.get(`${baseURL}/v1/catalog?limit=20`, {
    headers: { Authorization: `Bearer ${token}` },
    timeout: '2s',
  });
  check(response, { 'catalog returns 200': (r) => r.status === 200 });
}

The arrival-rate model keeps offered traffic independent of response time while enough virtual users are available. Check dropped_iterations: a generator that cannot produce the requested rate has not tested that rate. Grafana’s constant-arrival-rate documentation explains this behavior. Do not add a sleep to pace this executor.

Build up the experiment in stages:

  1. Establish a low-load baseline, then increase offered load until the latency or error objective breaks.
  2. Run a steady peak and a longer soak test to expose leaks, pool exhaustion, and accumulating queue lag.
  3. Send burst traffic with the real hot-key and tenant distribution.
  4. Test cold caches and a cache outage, with fallback admission controls enabled.
  5. Remove an API replica and then exercise the zone-loss plan. Slow a database dependency or vendor independently.
  6. Test a rolling deployment and database migration under load, then verify the service recovers after overload ends.

Capture the generator’s achieved rate, latency histogram, errors, pool waits, database work, cache behavior, queue age, and replica count together. Compare repeated runs with the same dataset and configuration. A ten-minute success is useful evidence, not proof of a monthly availability objective.

11. Protect correctness while adding capacity

Read replicas can help with suitable read workloads, but replication lag affects what callers see. Route freshness-sensitive reads appropriately, and define how read-your-writes is provided. Synchronous and asynchronous replication trade latency, availability, and potential data loss differently; consult PostgreSQL’s standby and replication documentation for the actual deployment mode.

A standby is not a backup. Define recovery-point and recovery-time objectives, keep recoverable backups, and rehearse restores and failover. Verify what happens to connections and in-flight transactions when the primary changes.

For API writes, validate inputs, enforce tenant isolation at every data access, and use database constraints for uniqueness and invariants. An idempotency record should be scoped to the caller and operation, store a request fingerprint, and reject the same key with a different payload. Persist the business effect and replayable outcome consistently. An in-memory flag does not provide that guarantee across replicas or restarts.

Deploy changes incrementally. Use backward-compatible schema changes, canary new versions, and retain a rollback path. Keep secrets and personal data out of logs; use request IDs and trace context to connect symptoms to the work that caused them.

12. A practical order of operations

StageEvidence to collectChange to consider
Establish demandEndpoint mix, peak RPS, payloads, objectivesA written capacity model
Reduce request costQuery plans, fan-out, allocation profilesIndexes, bounded pagination, fewer queries
Remove repeat workRepeated expensive reads, freshness needsScoped cache, explicit invalidation
Add serving capacitySafe RPS per replica, dependency headroomStateless replicas and bounded pools
Isolate slow workRequest time spent on noninteractive tasksDurable jobs and an outbox
Prove resilienceFailure tests, recovery time, error-budget useHeadroom, admission control, safer rollouts

Extract a service when a domain needs independent scaling, ownership, or fault isolation and the team can operate it. Consider sharding after measuring a storage or write bottleneck that simpler changes cannot address. Tenant-aware partitioning brings its own problems: hot tenants, cross-shard queries, rebalancing, and recovery. A million accounts alone is not a reason to take those on.

Track cost per successful request and per completed job as the system changes. Include database, cache, queue, observability, and network costs, as well as the engineering effort to operate them. Fewer requests and less work per request are often the most durable capacity gains.

The useful deliverable is a measured operating envelope: how much traffic the API can serve within its objectives, which failure it can absorb, and how it behaves beyond that boundary. Keep that envelope current as endpoints, data, and user behavior change.

Sources and diagram notes

The linked references are primary documentation and engineering guidance from PostgreSQL, PgBouncer, Redis, AWS, Google SRE, the IETF, and Grafana. They support the mechanisms discussed; the account model, capacity arithmetic, targets, and architecture choices are the worked example in this article.

All four diagrams were drawn specifically for this guide as SVGs. No diagram or image was copied from the reference material. Their editable generator lives in the portfolio repository at scripts/generate-api-diagrams.mjs.

Questions about this article? Get in touch.