CapstoneVol. 19 · Part XIX
0 / 0

Trails / Capstone

CP·211G

The Platform Layer

TiffinBox's infrastructure and delivery built to the capstone's list: minimal non-root container images, Kubernetes workloads spread across zones with correct probes and graceful shutdown, Terraform or OpenTofu modules for every resource, cloud IAM with workload identity and no static keys, private networking, a CDN with the right caching rules, TLS managed end to end, and a pipeline that builds once, scans, signs, deploys by GitOps, canaries and rolls back; with a lab measuring how much a CDN shields the origin (including during an outage) and what a TLS handshake costs.

22 topics · ~12 min read · 16-question quiz
Updated Suggest a correction

Start here: from source to users, safely

Everything in chapters 211B–211F has to run somewhere and get there safely. The platform layer is that somewhere and that path:

Requirement What it gives TiffinBox
Docker the same, minimal, scanned artefact in every environment
Kubernetes scheduling, self-healing, rolling updates and scaling for the API, workers and tracking gateway
Terraform / OpenTofu every cloud resource defined in code, reviewed and reproducible
cloud IAM each workload and person with only the access they need, and no long-lived keys
private networking databases, caches and brokers unreachable from the internet
CDN static files and cacheable pages served near users, shielding the origin
TLS encrypted, authenticated connections with certificates that renew themselves
CI/CD with tests, image build and signing every change proven and traceable from commit to running pod
deployment, canary, rollback changes reach users gradually and can be undone in minutes

The CDN and TLS, measured

The lab put nginx in front of an "origin" serving 1,000 JavaScript files, and sent 20,000 requests with realistic popularity (a few files very popular, most rarely requested):

Requests reaching the origin During an origin outage
edge without caching 20,000 every request failed (502)
edge with caching 895 (4.5%) every cached file still served, even after it went stale

And on the same machine, the cost of encryption:

Connection handling Requests per second
HTTP, connection reused ~130,000
HTTPS, connection reused ~110,000
HTTPS, a new TLS handshake for every request ~1,900–2,300

Encrypting data on an established connection is cheap; setting up a TLS connection is the expensive part (about 50× fewer requests per second here). That's why connection reuse, session resumption and HTTP/2 matter more than worrying about encryption itself.

How deep to go

Volume 17 defines six mastery levels. For the platform layer:

Level What you can do
L1 Name each platform requirement and why it exists
L2 Build images, manifests, Terraform modules and the pipeline
L3 Explain scheduling, probes, IAM evaluation, routing, caching and TLS from first principles
L4 Debug crash loops, throttling, permission denials, cache misses and certificate failures
L5 Design environments, networks, identity, delivery and rollback, and defend the trade-offs
L6 Run it: upgrades, cost, incidents, compliance, multi-region

Volumes 6, 7, 8 and 16 teach the topics in depth (chapters 79–96 and 187–193).

Containers

  • Multi-stage builds: compile in a full JDK or Node image; copy only the artefact into a minimal runtime image (distroless Java, or a slim JRE built with jlink; static files go to the CDN, not an image).
  • Pin base images by digest, rebuild on base-image updates, and scan in CI (Trivy or Grype) with a policy (no critical vulnerabilities with a fix available).
  • Run as non-root, with a read-only root filesystem and no extra Linux capabilities.
  • JVM in containers: set heap by percentage (-XX:MaxRAMPercentage=75), leave room for off-heap, and match CPU requests to the threads you expect.
  • Generate an SBOM (Syft or the build tool's plugin) and attach it to the image.

Kubernetes

Use a managed Kubernetes service; three node pools at most (general, workers, tracking).

Workload Kind Scaling Notes
api Deployment, ≥ 3 replicas HPA on CPU and request rate spread across zones
workers Deployment per consumer group KEDA on consumer lag idempotent; graceful stop commits offsets
tracking gateway Deployment HPA on open connections long connections: long termination grace, client reconnect with jitter
outbox relay Deployment, 1–2 replicas with leader election or SKIP LOCKED fixed
migrations Job run by the pipeline before rollout — lock timeouts

For each Deployment:

  • Probes: a startupProbe for slow starts (JVM warm-up), a readinessProbe reflecting "can serve" (including critical dependencies with short timeouts), a livenessProbe checking only the process (never the database).
  • Resources: CPU and memory requests from measured usage; memory limits to contain leaks; be cautious with CPU limits on latency-sensitive services (Volume 17's lab measured bursty load under a 0.5 CPU limit doubling latency through throttling).
  • Graceful shutdown: on SIGTERM, fail readiness, wait for the load balancer to stop sending traffic (a preStop sleep of a few seconds), finish in-flight requests, then exit; terminationGracePeriodSeconds longer than that sequence (Volume 16's lab: draining first gave 0 failed requests in a rolling deploy).
  • Availability: topologySpreadConstraints across zones, a PodDisruptionBudget (e.g. minAvailable: 2), anti-affinity for replicas.
  • Security: a dedicated ServiceAccount per workload with workload identity; NetworkPolicy allowing only the traffic each workload needs (default deny); Pod Security Standards at restricted.
  • Secrets: from the cloud's secret manager via the External Secrets Operator or a CSI driver, not committed, and rotated.

Infrastructure as code

  • Terraform or OpenTofu modules: network, cluster, database (managed PostgreSQL with HA and PITR), cache, Kafka, buckets, DNS, CDN, certificates, IAM, monitoring.
  • Environments (staging, production) compose the same modules with different variables; production in its own cloud account or project.
  • Remote state with locking, plans posted on pull requests, apply only from the pipeline, scheduled plan to detect drift.
  • Policy checks (Checkov, tfsec, or OPA/Conftest) for public buckets, open security groups, unencrypted storage, missing tags.
  • Tags on every resource (service, environment, owner, cost centre) so cost per component is visible.

Cloud IAM

  • Humans: single sign-on, short sessions, MFA, role assumption into least-privilege roles; production write access through the pipeline, with a logged break-glass role for emergencies.
  • Workloads: workload identity per ServiceAccount (EKS Pod Identity or IRSA, GKE Workload Identity, Azure Workload Identity), each with a narrow policy: the API can read its secrets and write to the receipts bucket prefix; the ingestion worker can read the documents prefix; nothing else.
  • The pipeline: OIDC federation from the CI system to the cloud (no static keys in CI), separate roles for plan and apply, and for staging and production.
  • Audit: cloud audit logs on, retained, and alerted for sensitive actions (IAM changes, key creation, public access changes).

Private networking

  • A VPC per environment spread over three zones; private subnets for the cluster nodes, database, cache and brokers; public subnets only for load balancers and NAT.
  • No public IPs on nodes or data stores; databases accept connections only from the cluster's subnets and specific security groups.
  • Egress through NAT with an allow-list (payment provider, model providers, email service), or private endpoints where the provider offers them; this also limits where a compromised pod can send data.
  • Operator access through the cloud's session manager or identity-aware proxy, not SSH bastions with keys.

CDN

Content Cache rule
hashed JS/CSS/fonts/images Cache-Control: public, max-age=31536000, immutable
index.html Cache-Control: no-cache (revalidate every time; cheap with ETags)
public catalogue API (menus) s-maxage=60, stale-while-revalidate=300, stale-if-error=86400
personalised API responses private, no-store (never cached at the edge)
  • Shield the origin: the lab's edge cache sent only 4.5% of requests to the origin and kept serving during an origin outage.
  • Turn on compression, HTTP/2 and HTTP/3, an origin shield tier, and a WAF with rate limits for login and expensive endpoints.
  • Purge by tag or path on deploys for anything not hash-named; never purge everything during peak.

TLS

  • Certificates from ACME (Let's Encrypt via cert-manager) or the cloud's certificate manager, renewed automatically, with expiry monitored independently (chapter 212B's lab detects an expired certificate before users do).
  • TLS 1.3 preferred, 1.2 minimum; ECDSA certificates (smaller, faster signing); HSTS with a long max-age once you're sure.
  • Keep connections alive: the lab measured ~50× lower throughput with a full handshake per request. Enable keep-alive at every hop, session resumption (tickets or cache) at the edge, and HTTP/2.
  • Inside the cluster: TLS to the database and broker; mutual TLS between services via a service mesh only if you need workload-to-workload authentication beyond NetworkPolicies.

CI/CD

Text
pull request: lint · unit tests · contract checks (OpenAPI, event schemas) · IaC plan + policy
merge to main:
  build once → integration tests (Testcontainers) → image build → SBOM → vulnerability scan
  → sign image (cosign, keyless via the CI's OIDC identity) → push by digest
  → GitOps commit: staging uses the new digest → migrations job → rollout
  → E2E tests + evaluation suite against staging
  → promote the same digest to production (another GitOps commit) → canary → full rollout
  • Build once, promote the digest: the image tested in staging is byte-for-byte the one in production.
  • Admission control in the cluster (Sigstore policy-controller or Kyverno) verifies signatures: unsigned images don't run.
  • Migrations run as a pipeline step before the new version, and are always backward-compatible with the running version (expand/contract).
  • Feature flags separate deploying code from releasing features, and give kill switches for risky features (the assistant's write tools).

Deployment, canary and rollback

  • GitOps (Argo CD): the cluster state is what's in the deploy repository; every change is a commit, every rollback a revert.
  • Canary (Argo Rollouts or Flagger): 5% of traffic → analysis → 25% → 50% → 100%, with automated analysis comparing the canary's error rate and latency against the stable version, aborting on failure. Chapter 211H's lab shows the statistics: a 5% canary catches a doubling of the error rate in ~3 minutes, but a small increase can take most of an hour.
  • Rollback: revert to the previous digest (minutes); never roll back the database schema in a hurry, roll forward instead, which is why migrations must be compatible in both directions during a release.
  • Deploy windows: avoid the lunch peak (10:30–14:00) for risky changes; automate the freeze.

Done when

  • Images are minimal, non-root, scanned, signed and SBOM-attached; the cluster rejects unsigned images.
  • Every workload spreads across zones, has correct probes, graceful shutdown, requests, a PDB, a NetworkPolicy and workload identity.
  • All infrastructure is in code; a fresh environment can be created from the README; drift is detected.
  • No static cloud keys anywhere (people, pipeline or pods); data stores have no public endpoints.
  • The CDN serves static assets with long caching and cacheable APIs with stale-if-error; certificates renew and are monitored.
  • A bad release is caught by the canary and rolled back automatically; a manual rollback takes under 5 minutes.

Common traps

  • Liveness probes that check the database.
  • CPU limits throttling latency-sensitive services.
  • Long-lived keys in CI or Kubernetes secrets.
  • Caching personalised responses at the CDN.
  • Rebuilding images per environment.
  • Schema rollbacks under pressure.

Lab: a CDN in front of the origin, and the price of a handshake

Setup. nginx on the lab machine (2 CPUs), in three roles:

  • an origin serving 1,000 files of 20 KB each with Cache-Control: public, max-age=60 (its own process, so it can be stopped);
  • an edge without caching that proxies every request to the origin;
  • an edge with caching (proxy_cache, proxy_cache_use_stale error timeout updating, proxy_cache_lock on, proxy_cache_background_update on).

A Python aiohttp client sent 20,000 requests at 50 concurrent connections, choosing files with a Zipf(1.2) distribution (a few files very popular, most rare). For TLS, nginx served a tiny response over HTTP and HTTPS (an RSA-2048 and an ECDSA P-256 certificate, session caching and tickets off), loaded with wrk (2 threads, 20 connections, 8 s) with and without Connection: close.

Experiment 1: origin offload

Edge Time for 20,000 requests p50 p99 Requests reaching the origin
no cache 2.8 s 7.05 ms 12.0 ms 20,000
cache 2.6 s 5.24 ms 11.8 ms 895

Experiment 2: origin outage

Situation Edge without cache Edge with cache
origin stopped; 5,000 requests for popular files (still fresh) 5,000 × 502 5,000 × 200
freshness shortened to 2 s (ignoring origin headers); origin stopped; requests 4 s later — cached files: 200, X-Cache: STALE; a file never cached: 502

Experiment 3: what TLS costs

Connection handling Requests/s p50
HTTP, keep-alive 129,772 0.16 ms
HTTPS (RSA-2048), keep-alive 110,361 0.12 ms
HTTP, new connection per request 59,925 0.21 ms
HTTPS (RSA-2048), new handshake per request 1,858 1.02 ms
HTTPS (ECDSA P-256), new handshake per request 2,343 1.74 ms

openssl speed on the same machine: RSA-2048 signs 3,606/s and verifies 67,429/s; ECDSA P-256 signs 52,588/s and verifies 16,644/s.

What it shows

  • Popularity skew makes edge caches powerful. The origin saw 895 requests instead of 20,000, roughly one per distinct file requested. On one machine the latency gain is small (origin and edge are both local); across the internet, cache hits near users save tens to hundreds of milliseconds.
  • Stale content beats an error page. With use_stale, files went on being served after they expired while the origin was down; only a file that had never been cached failed. That's what stale-if-error buys for menus during an outage.
  • Encryption is cheap, handshakes aren't. Reusing an HTTPS connection cost ~15% throughput versus plain HTTP; a full handshake per request cost ~98%. The server's private-key operation is the main cost: RSA signing is ~15× slower than ECDSA signing here. ECDSA only improved the handshake test by ~26% because the client (on the same CPUs) also has to verify the certificate, and ECDSA verification is slower than RSA's. In production the client's work happens on users' devices, so ECDSA's server-side savings show more fully.
  • Practical rule: keep connections alive at every hop, enable session resumption at the edge, and use HTTP/2 so one connection carries many requests.

Try it yourself

  1. Turn on ssl_session_cache shared:SSL:10m and ssl_session_tickets on, and test with a client that resumes sessions: how close to keep-alive throughput does it get?
  2. Change the Zipf exponent to 0.8 (flatter popularity) and measure origin offload again.
  3. Turn off proxy_cache_lock and send 500 simultaneous requests for one uncached file: how many reach the origin?
  4. Add Cache-Control: private to one route and confirm the edge never caches it.

Revision sheet: the platform layer

Key ideas

  • Minimal, non-root, digest-pinned, scanned, signed images with SBOMs.
  • Kubernetes: zone spread, startup/readiness/liveness used correctly, graceful shutdown, requests from measurements, PDBs, NetworkPolicies, workload identity, external secrets.
  • Everything in Terraform/OpenTofu; plans on PRs, applies from the pipeline, drift detection, policy checks, tags.
  • IAM: SSO and short sessions for humans, workload identity for pods, OIDC for CI, audit logs.
  • Private subnets for data; egress allow-lists; no bastion keys.
  • CDN: immutable hashed assets, revalidated HTML, stale-if-error for public APIs, never personalised data.
  • TLS: automatic renewal, independent expiry monitoring, TLS 1.3, ECDSA, keep-alive and resumption.
  • Pipeline: build once, sign, promote the digest, admission verifies signatures; GitOps; canary with automated analysis; rollback by digest; roll forward schemas.

Numbers to remember

  • Lab: cached edge sent 895 of 20,000 requests to the origin; stale content served during an outage.
  • HTTPS keep-alive ~110k/s vs new handshake per request ~1.9–2.3k/s; RSA-2048 sign 3.6k/s vs ECDSA P-256 52.6k/s.

Pitfalls

  • Dependency-checking liveness probes; CPU throttling; static keys; caching personalised data; per-environment builds; hurried schema rollbacks.

Glossary

  • PDB: PodDisruptionBudget.
  • Workload identity: short-lived cloud credentials bound to a Kubernetes ServiceAccount.
  • Admission controller: cluster component that can reject workloads (e.g. unsigned images).
  • stale-if-error: serve expired cached content when the origin fails.
  • cosign: Sigstore tool to sign and verify container images.