RecapsKayavak

Kayavak / Recaps / Production Deployment

Recaps · Volume 16

Production Deployment

The revision sheet of every chapter, on one page: the key ideas, the numbers worth knowing, the pitfalls and the words. Use it before an interview, after a chapter, or to find which chapter to reread. Each title opens its chapter; below each sheet are its exercises, companion and TiffinBox stage, and the misconceptions the companion corrects.

Open the volume

187

The Application Lifecycle

Key ideas

  • The lifecycle is a chain of artefacts and gates: idea/brief → requirements → design (ADRs, contracts) → code → tests → build → release → operate → learn → evolve or retire.
  • Walking skeleton first: the thinnest end-to-end slice, deployed, with the pipeline in place.
  • One pipeline, all stages: contract checks, lint, type check, tests, build once, scan, sign, promote by digest, deploy, smoke test, progressive rollout.
  • Order gates cheapest and fastest first; fail fast; parallelise where independent.
  • Repository layout and conventions that make the pipeline obvious.
  • Operate and learn: SLOs, incidents, postmortems, product metrics feed the next iteration.
  • Retire deliberately: deprecate, migrate users and data, remove infrastructure and access.

Numbers to remember

  • Lab: skeleton pipeline ≈ 6 s; type error caught in 0.11 s at stage 2.
  • Lab: a boundary bug passed all six stages until a test at exactly 20:00 was added.

Pitfalls

  • Building features for weeks before the first deploy.
  • Gates that don't test edges.
  • Tool configuration that differs between laptops and CI.
  • Rebuilding artefacts per environment.
  • Forgetting the lifecycle's end: zombie services nobody owns.

Glossary

  • Walking skeleton: minimal end-to-end implementation through all stages.
  • Gate: an automated or human check a change must pass.
  • Smoke test: a quick check that a deployment basically works.
  • Promotion: moving a tested artefact to the next environment.
  • Retirement: planned shutdown of a system.

188

Reference Production Architecture

Key ideas

  • The map: DNS → CDN → TLS termination → WAF/bot management → load balancer/API gateway → front end → app tier → cache, database, queue/event bus, search → workers → AI/RAG/tool layer → model providers.
  • Each component has a job, a failure mode and a degradation plan.
  • Latency budget: distance (RTTs) and round-trip count first; then handshakes; then per-component costs; budget p99, not just p50.
  • Failure domains: instance, zone, region, provider; design so one domain's loss has a bounded blast radius.
  • Stateless app tier; state in managed stores; async work on queues; idempotent workers.
  • Map components to providers (AWS, GCP, Azure, Cloudflare and others) without changing the design.
  • Read the architecture as a request: follow one user action through every box, including what happens when each fails.

Numbers to remember

  • Lab: proxy hop ~0.3 ms; new TLS connection ~1.5 ms CPU; cache hit 0.8 ms vs query 2.1 ms (p99 1.4 vs 5.5).
  • New HTTPS connection ≈ 3 RTT before the response; reused ≈ 1 RTT.

Pitfalls

  • Serving users from a far region without a CDN or edge caching.
  • Opening a new connection per request (client to server or server to database).
  • Chains of sequential calls on the request path.
  • No degraded mode when the cache or a third party is down.
  • Latency budgets set on medians.

Glossary

  • TLS termination: decrypting HTTPS at the edge or load balancer.
  • API gateway: entry point with routing, auth, rate limiting.
  • Failure domain: a set of components that can fail together.
  • Latency budget: allocation of an end-to-end latency target across components.
  • Connection pool: reused connections to a backend.

189

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.

190

Environment Strategy

Key ideas

  • Environments isolate risk: dev, CI, preview, staging/pre-prod, production (plus sandbox, perf, DR as needed).
  • Twelve-factor: one codebase, build once, configuration in the environment; promote immutable artefacts by digest.
  • Configuration layering with a typed schema validated at start-up; no environment-specific code branches.
  • Secrets: a secrets manager per environment, short-lived credentials, least privilege, rotation, scanning and push protection.
  • Data isolation: synthetic or masked data outside production; tightly controlled exceptions.
  • Promotion and approvals: automated gates, manual approval for production where needed, audit trail.
  • Parity: same versions, same topology shape, infrastructure as code per environment.
  • Preview environments per pull request, with automatic teardown and cost limits.

Numbers to remember

  • Lab: identical source → different wheel hashes until SOURCE_DATE_EPOCH was pinned.
  • Lab: validation stopped prod with a missing key and debug on.
  • Lab: gitleaks found 1 secret in the tree, 3 in history; missed a low-entropy password.

Pitfalls

  • Rebuilding per environment; deploying mutable tags like latest.
  • if env == "prod" branches in code.
  • Secrets in images, repos, CI logs or chat.
  • Production data copied to staging casually.
  • Staging that has drifted from production.

Glossary

  • Artefact promotion: moving one built artefact through environments.
  • Image digest: content hash identifying an exact image.
  • Reproducible build: identical inputs produce bit-identical outputs.
  • Configuration drift: unintended differences between environments.
  • Push protection: blocking pushes that contain detected secrets.

191

Database Deployment Safety

Key ideas

  • Schema changes are the least reversible and most locking part of a deploy.
  • Lock modes: reads take ACCESS SHARE; many ALTER TABLE forms take ACCESS EXCLUSIVE; locks queue FIFO, so a waiting DDL blocks everyone behind it.
  • Always set lock_timeout (and statement_timeout) for migrations; retry with back-off.
  • Expand → migrate (dual-write, backfill) → switch → contract, each step a separate deploy compatible with the previous code.
  • Backfills in key-range batches, committed, throttled, resumable; watch replica lag and WAL volume.
  • Safe recipes: CREATE INDEX CONCURRENTLY; constant defaults; NOT VALID constraints then VALIDATE; new tables instead of risky type changes.
  • Migration tools (Flyway, Liquibase, Alembic, Atlas, sqitch) plus linters in CI.
  • Rollback: forward fixes usually; backups and PITR for data loss; validate data after migrations (counts, checksums, invariants).

Numbers to remember

  • Lab: a 3 s open transaction turned an instant ALTER into a 3 s stall for all reads; lock_timeout=200ms capped it at 0.2 s.
  • Lab: CREATE INDEX blocked inserts for 477 ms on 2 M rows; CONCURRENTLY didn't.
  • Lab: volatile default rewrote 2 M rows in 4.5 s vs 0.01 s for a constant default.
  • Lab: single-statement backfill stalled updates up to 8.7 s; batches capped stalls at 0.3 s.

Pitfalls

  • Migrations without lock timeouts.
  • Renames and drops in the same release as the code change.
  • Volatile defaults or type changes that rewrite large tables.
  • One-shot backfills.
  • Leaving INVALID indexes after a failed concurrent build.

Glossary

  • ACCESS EXCLUSIVE: the lock mode that conflicts with every other mode.
  • Expand/contract (parallel change): staged, backward-compatible schema evolution.
  • Backfill: populating new columns or tables for existing rows.
  • NOT VALID constraint: added without checking existing rows; validated later with a weaker lock.
  • Lock queue: the FIFO line of sessions waiting for conflicting locks.

192

Zero-Downtime Deployment

Key ideas

  • Deploys break through: killed in-flight requests, traffic to stopping instances, cold starts, incompatible versions, schema changes, cache and queue format changes, connection-pool storms.
  • Rolling (maxSurge/maxUnavailable), blue/green (switch whole environments), canary (small traffic share with automated analysis).
  • Probes: startup (slow boot), readiness (in rotation?), liveness (restart if stuck); never make liveness depend on downstream dependencies.
  • Graceful shutdown: on SIGTERM, fail readiness, wait for propagation, stop accepting, finish in-flight work, close pools; bound by a termination grace period.
  • Compatibility: N and N−1 must coexist: additive API changes, tolerant readers, versioned events, expand/contract schemas.
  • Feature flags separate deploy from release; kill switches; clean up stale flags.
  • Release runbook: pre-checks, canary with metrics gates, promotion, rollback criteria, communication.

Numbers to remember

  • Lab: kill -9 → 194 failures; SIGTERM only → 166; drain then SIGTERM → 0 (of ~4,600).
  • Drain wait > load balancer detection time (check interval × fall count, plus propagation).

Pitfalls

  • SIGTERM handled as "exit now".
  • Liveness probes that call the database (cascading restarts).
  • Breaking API or event changes in one release.
  • Relying on load-balancer retries for non-idempotent requests.
  • Flags that are never removed.

Glossary

  • Readiness / liveness / startup probe: traffic eligibility / restart signal / boot allowance.
  • preStop hook: a Kubernetes hook run before SIGTERM, often a short sleep for draining.
  • Connection draining: letting existing work finish while sending no new work.
  • Canary analysis: comparing canary and baseline metrics to decide promotion.
  • Kill switch: a flag that disables a feature instantly.

193

Disaster Recovery

Key ideas

  • Redundancy ≠ recovery: replicas and multi-AZ protect against hardware failure, not deletion, corruption, ransomware or bad deploys.
  • RPO/RTO per system, agreed with the business; tiers by criticality.
  • Disaster catalogue: data loss, corruption, zone/region outage, provider outage, credential compromise, ransomware, key loss, human error.
  • Backups: logical (dumps), physical (base backups, snapshots) + continuous WAL/binlog archiving for PITR; encrypt, verify, retain, and keep them isolated (separate account, immutable storage, different credentials); follow 3-2-1.
  • DR strategies: backup and restore → pilot light → warm standby → active-active (cost rises, RTO/RPO fall).
  • Failover mechanics: DNS/traffic manager, promoting replicas, fencing the old primary, data reconciliation, failback.
  • Dependencies: third parties fail too; degrade gracefully, queue, fail over providers.
  • Runbooks, drills, game days, then blameless postmortems with action items.

Numbers to remember

  • Lab: dump restore lost 25,000 orders (everything since the dump); PITR lost none before the accident.
  • Lab: 1 M rows: dump 0.85 s, base backup 1.4 s, restore 0.9 s, PITR 1.0 s; production scale is hours.
  • RPO with WAL archiving ≈ archive interval (seconds to minutes).

Pitfalls

  • Never testing restores.
  • Backups readable and deletable with production credentials.
  • Restoring over production instead of beside it.
  • RTO assumed rather than measured.
  • Failover without fencing (two primaries, split brain).

Glossary

  • RPO / RTO: recovery point / time objective.
  • PITR: point-in-time recovery from base backup plus log replay.
  • WAL archiving: shipping completed write-ahead log segments to durable storage.
  • Fencing: guaranteeing the old primary can't accept writes after failover.
  • 3-2-1 rule: three copies, two media types, one off-site (often plus one immutable).

CS

Case Study — Launch Week Game Day

Key ideas

  • Game days rehearse failure on purpose: readiness review → plan → injected failures → scoring → postmortem → launch decision.
  • Mitigate first (stop or roll back the change), then diagnose; look at locks, not just app dashboards, when a migration coincides with an outage.
  • Canary analysis must compare against a baseline and stop automatically on clear harm.
  • Third-party outages need timeouts, queues, degraded modes and honest messaging.
  • Accidental deletions are recovered with PITR into a separate instance and selective copy-back; the deeper fix makes them impossible (least privilege, append-only ledgers).
  • Score detection, mitigation and recovery times and the quality of decisions; turn every action item into an automated check where possible.

Numbers to remember

  • Case: injection A mitigated in 10 minutes (0 with lock_timeout); injection D detected in 11 minutes, recovered in 58.
  • Lab: an append-only trigger made the deletion fail instantly; the linter flagged 3 of 4 migrations.

Pitfalls

  • Investigating dashboards while the bad change keeps running.
  • Migrations fetched from mutable paths instead of the versioned artefact.
  • Support roles with direct write access to financial tables.
  • Action items that stay as wiki text instead of becoming checks.