Production DeploymentVol. 16 · Part XVI
0 / 0

Shelves / Production Deployment

DP·189

Production Readiness

What "ready for production" means, made checkable: the production readiness review (PRR) and who runs it; the six dimensions in depth — functional (error states, edge cases, migrations), performance (baselines, load tests with k6, capacity from Little's law and utilisation, caching, bottleneck analysis), security (authentication, authorisation, secrets, dependency scanning, security headers, threat model), reliability (timeouts, retries with backoff and jitter, failover, backups and restores, rollback), observability (logs, metrics, traces, SLO burn-rate alerts, dashboards) and operations (runbooks, on-call, deployment and incident procedures); a machine-checkable readiness manifest with a scorer, a retry policy in Go, Java, Rust and Python, a security-header checker, and the readiness review of TiffinBox's skip flow.

23 topics · ~26 min read · 31-question quiz
Updated Suggest a correction

Start here: is it ready for real users?

"It works on my machine and the tests pass" means a feature is done. Production readiness asks a different question: can this service be run safely for real users, at real load, by people who didn't write it, at 3 a.m.? A readiness review checks six areas before launch:

Area The question Example evidence
functional does it do the right thing, including errors? acceptance tests, tested error states, a kill switch
performance does it hold up at peak, with headroom? a load test at 2× expected peak
security can it be abused? threat model, authorisation tests, secrets in a manager, security headers
reliability does it fail safely and recover? timeouts, retry budgets, a tested restore, a rehearsed rollback
observability will we know when it's broken? SLOs, burn-rate alerts, dashboards, traces
operations can on-call fix it? runbooks, trained on-call, a deploy procedure

Finding the real capacity

The lab load-tested a menu endpoint by sending requests at a fixed arrival rate, the way real users arrive, regardless of how fast the server answers:

Requests per second offered Median latency p95 Served per second
300 1.7 ms 2.5 ms 300
600 2.3 ms 6.5 ms 600
800 10 ms 46 ms 799
1,000 463 ms 507 ms 819

Up to about 600 per second, nothing happened. Somewhere above 800 the service saturated: it could only serve about 820 per second, the rest queued, and latency jumped 200-fold. With an expected peak of 300 per second, the service passes a "2× peak" gate with plenty of margin; but the cliff is sudden, so you want to know where it is before users find it.

Claims versus evidence

A readiness checklist where people tick boxes says what people believe. The lab compared a manifest's claims with automatic checks against the running service: it claimed security headers and a defined SLO; probing found neither. Readiness gates should check evidence (a header present, a restore log less than 30 days old, a load-test result file) wherever possible.

How deep to go in production readiness

Volume 17 defines six mastery levels; for production readiness they look like this:

Level You can…
L1 name the readiness areas and why each matters
L2 complete a readiness review for your service with evidence
L3 run open-model load tests, set SLOs and alerts, and explain queueing behaviour
L4 find the gaps a review missed from incidents and near-misses
L5 design readiness gates and launch reviews for a product line
L6 run readiness as an organisational standard with tooling and audits

Why readiness is a gate

A feature that works on a laptop and in staging can still fail in production in ways that have nothing to do with its logic: it falls over at 06:55 when everyone skips at once; a dependency times out and threads pile up; a migration locks a table; nobody knows it's broken until customers complain; the person on call has never seen it. Production readiness is the discipline of checking, before launch, that a service can be operated: that it performs under real load, fails safely, can be observed, can be secured, and can be fixed at 3 a.m. by someone who didn't write it.

Google's SRE practice formalised this as the Production Readiness Review (PRR): before SREs take on a service (or before a significant launch), the service team and reviewers walk a checklist, file gaps as launch blockers or follow-ups, and agree on SLOs. Most organisations adapt it as a launch checklist owned by the team, reviewed by a platform/SRE peer.

The roadmap's six dimensions:

readiness reviewevidence, not claims functionalerrors · edges · migrations performancebaseline · load · capacity securityauthn/z · secrets · scans reliabilitytimeouts · backups · rollback observabilitylogs · metrics · traces · SLOs operationsrunbook · on-call · incidents
The six dimensions of production readiness. Functional correctness, performance, security, reliability, observability and operations each have their own checks; a launch needs evidence in all six, since a gap in any one is how production incidents happen. The review produces blockers that must be closed before launch and follow-ups with owners and dates.

Functional readiness

Requirements met: the acceptance tests from chapter 185 pass in an environment like production, not only on developer machines.

Error states. Every failure a user can hit has a designed response (Volume 15, chapter 184): validation errors with field-level messages; business-rule refusals (past cut-off → 409 with a human message); dependency failures (payment provider down → "we'll retry, the study plan is safe"); and unexpected errors (500 → a generic message with a correlation id, never a stack trace). APIs return consistent problem details (RFC 9457). Check: list every endpoint × every error class and confirm there's a test.

Edge cases. Boundaries (exactly 07:00:00 IST; the last day of a plan; leap years; months with five Fridays), empty states (no deliveries yet), large inputs (an office admin with 300 employees), concurrency (two taps on Skip; skip while the 07:00 lock job runs), time zones and DST (India has no DST, but servers in UTC and users travelling do), Unicode names, idempotent retries. Property-based tests (chapter 185) find the ones you didn't think of.

Migrations. Schema changes are backward-compatible with the currently deployed version, tested against a production-sized copy, and reviewed for locks (chapter 191). Data backfills are resumable and throttled. Rollback for each migration is planned (often "roll forward with a fix" plus the expand/contract pattern so app rollback doesn't need schema rollback).

Feature flags. Risky behaviour ships dark behind a flag, with a kill switch tested in staging (chapter 192).

Performance readiness

Baseline

Measure the current system before changing it: request rate by endpoint and time of day, latency percentiles (p50, p95, p99), error rate, resource use (CPU, memory, DB connections, IOPS), and the shape of the daily curve. TiffinBox's curve has two spikes: 06:30–07:00 (skips, before cut-off) and 12:00–13:30 (tracking).

Capacity from first principles

Little's Law: in a stable system, the average number of requests in flight L equals arrival rate λ times average time in system W:

L = λ × W

It's distribution-free and tells you how much concurrency (threads, connections) you need. Utilisation ρ = λ / (c × μ) for c servers each completing μ requests per second; as ρ → 1, queueing delay grows without bound (for an M/M/1 queue, the mean time in system is 1/(μ − λ), so going from 50% to 90% utilisation multiplies it by five). Keep steady-state utilisation well below saturation and size for peak plus headroom.

Python
# Capacity plan for the 06:45–07:00 skip rush (projected for 60,000 subscribers)
subscribers         = 60_000
skip_share_rush     = 0.18          # share of subscribers who interact in the rush window
calls_per_session   = 6             # app open, schedule, skip, balance, ...
window_s            = 15 * 60
peak_factor         = 3.0           # within the window, the last 3 minutes are ~3x the average

avg_rps  = subscribers * skip_share_rush * calls_per_session / window_s
peak_rps = avg_rps * peak_factor
print(f"average {avg_rps:.0f} rps, peak {peak_rps:.0f} rps")

service_time_s = 0.030              # p50 server time per call (measured)
in_flight = peak_rps * service_time_s           # Little's law: L = λW
print(f"in-flight requests at peak (L = λW): {in_flight:.1f}")

per_pod_capacity_rps = 220          # measured in a load test at 70% CPU with p95 within SLO
pods_needed = peak_rps / per_pod_capacity_rps
zones = 3
# survive one zone loss: remaining zones must carry peak, so scale by zones/(zones-1)
pods_with_zone_headroom = pods_needed * zones / (zones - 1)
import math
print(f"pods for peak: {pods_needed:.1f}; with one-zone-loss headroom: {math.ceil(pods_with_zone_headroom)}"
      f" (round up to a multiple of {zones}: {math.ceil(pods_with_zone_headroom / zones) * zones})")

db_conn_per_pod = 10
print("DB connections at that size:", math.ceil(pods_with_zone_headroom / zones) * zones * db_conn_per_pod,
      "(check against max_connections / the pooler)")

# M/M/1 intuition: mean time in system 1/(mu - lambda) relative to service time 1/mu
for rho in (0.5, 0.7, 0.8, 0.9, 0.95):
    print(f"utilisation {rho:.0%}: time in system = {1/(1-rho):.1f} x service time")
Text
average 72 rps, peak 216 rps
in-flight requests at peak (L = λW): 6.5
pods for peak: 1.0; with one-zone-loss headroom: 2 (round up to a multiple of 3: 3)
DB connections at that size: 30 (check against max_connections / the pooler)
utilisation 50%: time in system = 2.0 x service time
utilisation 70%: time in system = 3.3 x service time
utilisation 80%: time in system = 5.0 x service time
utilisation 90%: time in system = 10.0 x service time
utilisation 95%: time in system = 20.0 x service time

The numbers say TiffinBox's traffic is modest: three pods (one per zone) suffice for the projected rush. Production minimums are set by availability, not capacity: at least one replica per zone, and enough that a rolling deploy (one pod down) plus a zone loss still serves peak. Many systems are like this, and the plan saves money by not over-provisioning.

Load testing

A load test verifies the capacity model and NFRs with realistic traffic. Types: load (expected peak), stress (beyond peak until it breaks, to find the bottleneck and see how it fails), spike (sudden jump, as at 06:57), soak (hours at moderate load to find leaks and slow degradation). Use production-like data volumes (a query that's fast on 1,000 rows may be slow on 10 million) and an environment sized like production or scaled proportionally.

JavaScript
// load/skip-rush.js — k6 scenario: ramp to the 06:57 spike, assert NFRs as thresholds
import http from "k6/http";
import { check, sleep } from "k6";
import { randomIntBetween } from "https://jslib.k6.io/k6-utils/1.4.0/index.js";

export const options = {
  scenarios: {
    rush: {
      executor: "ramping-arrival-rate",          // open model: arrival rate independent of response time
      startRate: 50, timeUnit: "1s", preAllocatedVUs: 200, maxVUs: 1000,
      stages: [
        { target: 72,  duration: "5m" },          // average rush rate
        { target: 216, duration: "1m" },          // spike to peak
        { target: 432, duration: "2m" },          // 2x peak headroom check
        { target: 50,  duration: "2m" },
      ],
    },
  },
  thresholds: {
    "http_req_duration{name:skip}": ["p(95)<800"],   // NFR from chapter 185 (server + network in test region)
    "http_req_failed": ["rate<0.001"],
    "checks": ["rate>0.999"],
  },
};

export default function () {
  const sub = randomIntBetween(1, 60000);
  const key = `${__VU}-${__ITER}`;
  const res = http.post(`${__ENV.BASE}/v1/subscriptions/${sub}/deliveries/2026-11-05/skip`, null, {
    headers: { Authorization: `Bearer ${__ENV.TOKEN}`, "Idempotency-Key": key },
    tags: { name: "skip" },
  });
  check(res, { "200 or 409": (r) => r.status === 200 || r.status === 409 });
  sleep(Math.random());
}

Caching and bottlenecks

Find the bottleneck by measuring under load, not guessing: the first resource to saturate (CPU, DB connections, a lock, a downstream rate limit, the connection pool, GC pauses, a single-threaded component) sets the ceiling. Tools: profilers (async-profiler, pprof, py-spy), EXPLAIN (ANALYZE, BUFFERS) and pg_stat_statements, traces showing where time goes, USE metrics (utilisation, saturation, errors) per resource. Caching fixes read hot spots (Volume 3); it doesn't fix write contention or slow queries on cache misses, and adds invalidation complexity, so add it where measurements show the need.

Security readiness

Volume 10 covers each in depth; readiness checks evidence for each:

  • Authentication: standard protocols (OIDC/OAuth 2.1 for users, workload identity for services), short-lived tokens, MFA for admins, brute-force protection (rate limits, lockouts with care), secure session handling (HttpOnly, Secure, SameSite cookies).
  • Authorisation: every endpoint has an explicit policy (deny by default); object-level checks (can user 1234 skip subscription 77? Broken object-level authorisation is OWASP API Security #1); tests for cross-tenant access (an office admin must not see another office).
  • Secrets: none in code, images, logs or environment files committed to Git; delivered at runtime from a secret manager; rotated; scoped per environment (chapter 190); secret scanning in CI (gitleaks, GitHub secret scanning) and pre-commit.
  • Dependency and image scanning: SCA (Dependabot/Renovate, npm audit, OWASP Dependency-Check, govulncheck, cargo audit), container scanning (Trivy, Grype), with a policy (no critical with a fix available) and an SBOM.
  • Security headers on web responses.
  • Threat model: STRIDE or attack trees for the feature, reviewed; abuse cases tested (credit farming by skipping and un-skipping repeatedly — chapter 185's idempotency rule defends it).
  • Data protection: PII inventory, encryption at rest and in transit, retention, India's DPDP Act obligations (consent, purpose limitation, breach notification).

A header checker that runs in CI against staging:

Python
# Security-header check against a response's headers (run in CI against staging with real responses)
REQUIRED = {
    "strict-transport-security": lambda v: "max-age=" in v and int(v.split("max-age=")[1].split(";")[0]) >= 15552000,
    "content-security-policy":   lambda v: "default-src" in v and "'unsafe-inline'" not in v.split("script-src")[-1].split(";")[0],
    "x-content-type-options":    lambda v: v.lower() == "nosniff",
    "referrer-policy":           lambda v: v in {"strict-origin-when-cross-origin", "no-referrer", "same-origin"},
    "permissions-policy":        lambda v: "camera=()" in v,
}
FORBIDDEN = {"server": lambda v: any(ch.isdigit() for ch in v), "x-powered-by": lambda v: True}

def check(headers):
    h = {k.lower(): v for k, v in headers.items()}
    problems = [f"missing {k}" for k in REQUIRED if k not in h]
    problems += [f"weak {k}: {h[k]!r}" for k, ok in REQUIRED.items() if k in h and not ok(h[k])]
    problems += [f"leaks {k}: {h[k]!r}" for k, bad in FORBIDDEN.items() if k in h and bad(h[k])]
    return problems

staging = {
    "Strict-Transport-Security": "max-age=31536000; includeSubDomains",
    "Content-Security-Policy": "default-src 'self'; script-src 'self'; img-src 'self' https://img.tiffinbox.in",
    "X-Content-Type-Options": "nosniff",
    "Referrer-Policy": "strict-origin-when-cross-origin",
    "Server": "nginx/1.27.3",
}
for p in check(staging): print("FAIL", p)
# FAIL missing permissions-policy
# FAIL leaks server: 'nginx/1.27.3'

Reliability readiness

Timeouts

Every network call has a timeout, and they're nested: the client's timeout > the gateway's > the service's total budget > each downstream call's timeout. Without timeouts, a slow dependency holds threads/connections until the pool is exhausted and the service stops serving everything (a slow failure is worse than a fast one). Set connect timeouts short (≈ 1 s in-region), request timeouts from the latency budget (chapter 188), and propagate deadlines (gRPC deadlines, or a header carrying the remaining budget) so downstream work stops when the caller has given up.

Retries with backoff and jitter

Retry only transient failures (connection reset, 503, 429 with Retry-After, timeouts on idempotent operations), only idempotent operations (or ones made idempotent with keys), with exponential backoff and jitter (randomness prevents synchronised retry waves), a cap on attempts, and a retry budget (e.g. retries ≤ 10% of requests, so retries can't multiply load during an outage; retries at every layer multiply: 3 retries at each of 3 layers is up to 27× load on the bottom service). Pair with circuit breakers that stop calling a failing dependency for a cool-off period.

// Retry with "full jitter" exponential backoff, respecting a context deadline
package retry

import (
	"context"
	"errors"
	"math/rand/v2"
	"time"
)

var ErrPermanent = errors.New("permanent")

func Do(ctx context.Context, attempts int, base, maxDelay time.Duration, op func(context.Context) error) error {
	var err error
	for i := 0; i < attempts; i++ {
		if err = op(ctx); err == nil || errors.Is(err, ErrPermanent) {
			return err
		}
		ceiling := min(maxDelay, base<<i)                       // base * 2^i, capped
		sleep := time.Duration(rand.Int64N(int64(ceiling) + 1)) // full jitter: uniform in [0, ceiling]
		select {
		case <-time.After(sleep):
		case <-ctx.Done():
			return errors.Join(err, ctx.Err())                  // caller's deadline wins
		}
	}
	return err
}

Failover, backups, restore, rollback

  • Failover: the database has a standby in another zone with automatic failover; tested (trigger a failover in staging and measure the client-visible outage; RDS Multi-AZ typically fails over in about a minute, and clients must reconnect: connection pools need validation and short DNS caching).
  • Backups: automated, encrypted, in another account/region (so a compromised production account can't delete them), with point-in-time recovery.
  • Restore: tested. A backup you haven't restored is a hope, not a backup. Regular automated restore drills measure restore time against RTO (chapter 193).
  • Rollback: every release can be rolled back in minutes by one documented action (Argo Rollouts abort, helm rollback, flag off), and the team has done it. Schema changes are compatible with N−1 so app rollback is safe (chapter 191).
  • Graceful degradation: if Redis is down, serve from Postgres (slower) rather than fail; if search is down, show the plain menu; if the AI assistant's provider is down, show help links.
  • Load shedding: under overload, reject low-priority work early (429/503) to keep high-priority work (skips before cut-off) within SLO.

Observability readiness

From Volume 9, the evidence needed:

  • Logs: structured JSON, with trace id, user/tenant id (pseudonymous), request id; levels used consistently; no secrets or raw PII; retention set.
  • Metrics: RED (rate, errors, duration) per endpoint; USE for resources; business metrics (skips/min, deliveries locked, credits issued); saturation signals (pool usage, queue lag).
  • Traces: OpenTelemetry instrumentation across browser → gateway → api → DB → queue → worker, with sampling (tail-based for errors and slow traces).
  • SLOs on user journeys and burn-rate alerts (alert on the rate of error-budget consumption, not on every error).
  • Dashboards: one per service (golden signals) and one per journey; linked from alerts.
  • Alerts: each alert is actionable, has a severity, a runbook link, and was tested (fired in staging).
YAML
# Prometheus rules: SLO = 99.9% of skip requests succeed (non-5xx) over 30 days.
# Multi-window, multi-burn-rate alerts (Google SRE Workbook): page on fast burn, ticket on slow burn.
groups:
- name: skip-slo
  rules:
  - record: skip:error_ratio:rate5m
    expr: sum(rate(http_server_requests_seconds_count{uri=~".*/skip",status=~"5.."}[5m]))
          / sum(rate(http_server_requests_seconds_count{uri=~".*/skip"}[5m]))
  - record: skip:error_ratio:rate1h
    expr: sum(rate(http_server_requests_seconds_count{uri=~".*/skip",status=~"5.."}[1h]))
          / sum(rate(http_server_requests_seconds_count{uri=~".*/skip"}[1h]))
  - record: skip:error_ratio:rate30m
    expr: sum(rate(http_server_requests_seconds_count{uri=~".*/skip",status=~"5.."}[30m]))
          / sum(rate(http_server_requests_seconds_count{uri=~".*/skip"}[30m]))
  - record: skip:error_ratio:rate6h
    expr: sum(rate(http_server_requests_seconds_count{uri=~".*/skip",status=~"5.."}[6h]))
          / sum(rate(http_server_requests_seconds_count{uri=~".*/skip"}[6h]))
  - alert: SkipErrorBudgetFastBurn
    expr: skip:error_ratio:rate1h > (14.4 * 0.001) and skip:error_ratio:rate5m > (14.4 * 0.001)
    labels: { severity: page }
    annotations:
      summary: "Skip SLO burning 14.4x (2% of monthly budget per hour)"
      runbook_url: "https://runbooks.tiffinbox.in/skip-errors"
  - alert: SkipErrorBudgetSlowBurn
    expr: skip:error_ratio:rate6h > (6 * 0.001) and skip:error_ratio:rate30m > (6 * 0.001)
    labels: { severity: ticket }
    annotations:
      summary: "Skip SLO burning 6x (5% of monthly budget per 6h)"
      runbook_url: "https://runbooks.tiffinbox.in/skip-errors"

Why 14.4: a burn rate of 14.4 for one hour consumes 14.4 × (1 h / 720 h) = 2% of a 30-day budget; paging on that catches serious incidents quickly while the short window (5 m) makes the alert reset fast once fixed. For TiffinBox there's a wrinkle: traffic is concentrated in two daily windows, so low-traffic hours produce noisy ratios; add a minimum request-count condition, or alert on the rush windows specifically.

Operational readiness

Runbook per alert and per common operation (Volume 9): what the alert means, impact, first checks (dashboards, recent deploys), mitigations (rollback, flag off, scale up, fail over), escalation, and how to verify recovery. Template:

Markdown
# Runbook: SkipErrorBudgetFastBurn
**Meaning**: >1.44% of skip requests are failing (5xx) — users can't skip before the 07:00 cut-off.
**Impact**: users charged for meals they wanted to skip; credits disputes; support load. Severity: SEV-2 (SEV-1 if 06:30–07:00).
**First 5 minutes**
1. Open the Skip journey dashboard; check error rate by pod, by zone, by status code.
2. Check recent changes: Argo CD history (deploys in last 2 h), flag changes, migrations.
3. Check dependencies: Postgres (connections, locks: `SELECT * FROM pg_stat_activity WHERE wait_event_type = 'Lock'`), Redis, gateway.
**Mitigate**
- Recent deploy? Roll back: `kubectl argo rollouts undo api -n tiffinbox` (or abort a canary in progress).
- Lock contention from a migration? Cancel it: `SELECT pg_cancel_backend(pid)`.
- Near cut-off with no fix in sight: enable flag `cutoff_grace_15m` (extends cut-off for today; product owner approval in incident channel).
**Verify**: error ratio < 0.1% for 15 min; synthetic skip check green.
**Escalate**: API owner on-call → DB on-call → incident commander if not mitigated in 15 min.

On-call: a rotation exists with at least two people trained on this service, alert routing (PagerDuty, Opsgenie, Grafana OnCall), escalation policy, and a handover. Service ownership is recorded in a catalogue (Backstage) with links to repo, dashboards, runbooks.

Deployment procedure: documented and automated (chapter 192): how a release progresses, what's checked, who approves production, freeze windows (none in 06:30–07:00 or 12:00–13:30 for TiffinBox), and how to roll back.

Incident process: severity definitions, roles, communication templates (status page, support macros), postmortem within five working days, action items tracked.

A machine-checkable readiness manifest

Checklists in wikis rot. Put readiness as data in the repository, check it in CI, and render it in the service catalogue:

Python
# readiness.py — score a service's readiness manifest; blockers fail CI before a launch tag
manifest = {
    "service": "api", "launch": "skip-v2",
    "functional":    {"acceptance_tests": True, "error_states_tested": True, "migrations_reviewed": True, "kill_switch": True},
    "performance":   {"baseline_recorded": True, "load_test_peak_2x": True, "capacity_plan": True, "soak_test": False},
    "security":      {"threat_model": True, "authz_tests": True, "secrets_in_manager": True, "scans_clean": True, "headers": False},
    "reliability":   {"timeouts_everywhere": True, "retry_budget": True, "backup_restore_tested": False, "rollback_rehearsed": True},
    "observability": {"slo_defined": True, "burn_rate_alerts": True, "dashboards": True, "traces_end_to_end": True},
    "operations":    {"runbooks_linked": True, "oncall_trained": True, "deploy_procedure": True, "incident_process": True},
}
BLOCKERS = {"acceptance_tests", "migrations_reviewed", "load_test_peak_2x", "authz_tests", "secrets_in_manager",
            "backup_restore_tested", "rollback_rehearsed", "slo_defined", "runbooks_linked", "oncall_trained"}

def score(m):
    blockers, follow_ups = [], []
    for dim, checks in m.items():
        if not isinstance(checks, dict):
            continue
        done = sum(checks.values())
        print(f"{dim:<14}{done}/{len(checks)}")
        for name, ok in checks.items():
            if not ok:
                (blockers if name in BLOCKERS else follow_ups).append(f"{dim}.{name}")
    return blockers, follow_ups

blockers, follow_ups = score(manifest)
print("BLOCKERS:", blockers or "none")
print("follow-ups (owner + date required):", follow_ups)
raise SystemExit(1 if blockers else 0)
Text
functional    4/4
performance   3/4
security      4/5
reliability   3/4
observability 4/4
operations    4/4
BLOCKERS: ['reliability.backup_restore_tested']
follow-ups (owner + date required): ['performance.soak_test', 'security.headers']

The launch is blocked until someone restores last night's backup into an isolated environment and records the time (chapter 193); the soak test and Permissions-Policy header become dated follow-ups.

Lab: capacity and evidence for a readiness review

Setup. The FastAPI menu service from chapter 188's lab (one uvicorn process, a 4-connection psycopg pool, a PostgreSQL aggregate per request) on the lab machine; k6 1.3 with the constant-arrival-rate executor (10 s per step, up to 400 virtual users); nginx in front for the header checks. The expected TiffinBox peak for this endpoint is assumed to be 300 requests per second.

Experiment 1: the capacity curve

Offered (req/s) p50 p95 p99 Served (req/s) Dropped (couldn't start)
50 1.81 ms 2.41 ms 3.70 ms 50 0
100 1.82 ms 2.69 ms 3.48 ms 100 0
200 1.74 ms 2.63 ms 3.28 ms 200 0
300 1.67 ms 2.52 ms 3.61 ms 300 0
400 1.73 ms 2.78 ms 4.60 ms 400 0
600 (2× peak) 2.32 ms 6.54 ms 13.64 ms 600 0
800 10.01 ms 46.05 ms 58.99 ms 799 6
1,000 462.66 ms 507.33 ms 521.52 ms 819 1,517
1,200 475.83 ms 527.14 ms 537.06 ms 810 3,584
1,500 449.84 ms 495.11 ms 507.85 ms 849 6,193
  • Capacity ≈ 820 req/s. Beyond it, extra load didn't produce more throughput, only queueing and (in k6) iterations that couldn't start because all 400 virtual users were busy.
  • The knee is sharp: p95 went 2.5 → 6.5 → 46 → 507 ms between 300 and 1,000 req/s. Queueing theory predicts this (waiting ∝ 1/(1 − ρ)); a team that tested only at 300 req/s would see no warning.
  • Little's law checks the measurement: at saturation ~400 requests were in flight and ~820 completed per second, so W = 400/820 ≈ 0.49 s; measured medians were 0.45–0.48 s.
  • Readiness verdict for performance: 2× peak (600 req/s) met a 100 ms p95 SLO with a large margin, and the headroom to saturation is ~2.7× peak. Record the curve, the saturation point and the bottleneck (here a single process; adding processes or replicas moves the knee) in the review.

A closed-model test (virtual users waiting for each response before sending the next) at the same nominal load would have hidden most of this: as the server slowed, its users would have slowed too.

Experiment 2: claims versus evidence

A manifest claimed five checks; a script verified each against the running system:

Check Claimed Evidence How it was checked
health endpoint ✓ ✓ GET /health → 200
security headers ✓ ✗ strict-transport-security, content-security-policy, x-content-type-options all missing from the HTTPS response
load test at 2× peak ✓ ✓ result file: 600 req/s, p95 6.54 ms
backup restore tested ✓ ✓ restore log from chapter 193's lab: "redo done", 0 days old
SLO defined ✓ ✗ no slo.yaml in the repository

Two of five claims were wrong, both the kind that stay wrong for months because nobody looks. Make readiness checks executable where possible, run them in CI and on a schedule, and keep the human review for what machines can't judge (threat models, runbook quality, on-call training).

Try it yourself

  1. Run the same load with 4 uvicorn workers and find the new saturation point. Which resource is the bottleneck now?
  2. Rerun Experiment 1 with k6's constant-vus executor at 400 users and compare what it reports at overload.
  3. Add the three headers in nginx and make the evidence script pass; add it to CI.
  4. Write an slo.yaml (availability and latency SLOs) and a check that alerts exist for each SLO.

Revision sheet: production readiness

Key ideas

  • Readiness is a gate before launch and a standard afterwards: functional, performance, security, reliability, observability, operations.
  • Performance: baselines, open-model load tests to 2× peak and to saturation, soak tests, capacity plans; Little's law and queueing (1/(1 − ρ)) explain the knee.
  • Security: threat model, authorisation tests (BOLA), secrets management, dependency and image scans, security headers, abuse cases and rate limits.
  • Reliability: timeouts everywhere, retry budgets with jitter, idempotency, circuit breakers, load shedding, tested backups and rehearsed rollbacks.
  • Observability: SLIs/SLOs, multi-window burn-rate alerts, dashboards, end-to-end traces, structured logs.
  • Operations: runbooks linked from alerts, trained on-call, deploy and incident procedures.
  • Readiness as code: a manifest in the repo, evidence checks in CI, blockers vs dated follow-ups.

Numbers to remember

  • Lab: capacity ≈ 820 req/s; p95 2.5 ms at 300 req/s, 46 ms at 800, 507 ms at 1,000.
  • Little's law: L = λW (400 in flight / 820 per s ≈ 0.49 s).
  • M/M/1: time in system ∝ 1/(1 − ρ): 50% → 2×, 90% → 10×.
  • Burn rate 14.4 for 1 h = 2% of a 30-day error budget.
  • Lab: 2 of 5 readiness claims failed evidence checks.

Pitfalls

  • Closed-model load tests that hide overload.
  • Testing only at expected peak.
  • Checklists without evidence.
  • Retries without budgets or jitter.
  • "Backup tested" without a timed restore.

Glossary

  • Saturation: the point where throughput stops rising with load.
  • Coordinated omission: a load test slowing its own requests when the system slows.
  • Error budget: allowed unreliability under an SLO.
  • Load shedding: rejecting excess work to protect latency of the rest.
  • Readiness manifest: versioned, checkable record of launch criteria.