TExcelTAD

Production Hardening

linkly now builds, ships, deploys and reports on itself. "Production-ready" is the list of things that go wrong after that: at 2 a.m., during a node upgrade, when traffic triples, when someone finds the API. This lesson walks the list area by area, models the two problems that are easiest to get subtly wrong, and adds the manifests that close the remaining gaps.

The checklist

Area Item Where in this course
Lifecycle SIGTERM drains; preStop sleep; app deadline < grace period Running linkly, The Production Chart, model below
readiness fails only for hard dependencies; liveness depends on nothing The Source
rollouts surge before removing (maxUnavailable: 0); PDB; spread across nodes The Production Chart
Capacity requests and memory limits sized from metrics; HPA owns replicas The Production Chart
connection pools sized against the database's max_connections model below
timeouts on every dependency call and on the HTTP server The Source
Security non-root, read-only root filesystem, no capabilities, seccomp, no service account token The Production Chart
NetworkPolicy; only the Gateway and Prometheus reach the pod The Production Chart
image by digest; image scanned in CI; image signed and verified at admission The CI Workflow, manifests below
secrets from a secret manager, never in Git, values or state Cloud Track
TLS at the Gateway with automatic certificates; HTTP redirects to HTTPS manifests below
abuse: authentication for POST /links, rate limits, a blocklist for malicious URLs discussion below
Data migrations run once per release, before the new pods, not in every pod's startup manifests below
backups and a tested restore: CloudNativePG backups to object storage, or RDS automated backups and snapshots discussion below
Operations SLO alerts with runbooks; dashboard; on-call routing SLO Alerts & Dashboards
rollback is a git revert; teardown is written down Deploy, Roll Back & Tear Down

Model 1: why the preStop sleep exists

When a pod is deleted, the kubelet starts the shutdown and, in parallel, the endpoint change propagates to every node's kube-proxy and to the Gateway's proxies. Each proxy learns about it at a different moment. Until it does, it keeps sending new requests to the pod. The model sends one request every 100 ms from each of four proxies and counts requests that hit a pod that has stopped accepting connections:

python · try it yourself
# When does each proxy stop routing to the terminating pod? (seconds after the pod is deleted)
proxy_updates = [0.4, 1.3, 2.6, 3.9]

def failed_requests(stops_listening_at, interval=0.1):
    failed = 0
    for updated_at in proxy_updates:
        t = 0.0
        while t < updated_at:                 # this proxy still sends traffic to the pod
            if t >= stops_listening_at:
                failed += 1
            t = round(t + interval, 1)
    return failed

for label, stop in [("no preStop: SIGTERM at once, Shutdown() closes the listener", 0.0),
                    ("preStop sleep 2s", 2.0),
                    ("preStop sleep 5s (the chart's default)", 5.0)]:
    print(f"{label:<60} failed requests: {failed_requests(stop)}")
no preStop: SIGTERM at once, Shutdown() closes the listener  failed requests: 82
preStop sleep 2s                                             failed requests: 25
preStop sleep 5s (the chart's default)                       failed requests: 0

srv.Shutdown is correct: it stops accepting new connections and waits for in-flight requests. The problem is purely timing: without a pause, the listener closes while proxies still route to it. Five seconds covers typical propagation; measure yours (count 502/503 responses at the Gateway during a rollout) and adjust preStopSleepSeconds. Keep SHUTDOWN_GRACE + preStop + margin ≤ terminationGracePeriodSeconds, which the chart computes for you.

Model 2: connection pools against max_connections

pgxpool opens up to max(4, runtime.NumCPU()) connections per pod by default, and NumCPU is the node's CPU count as seen by the process, not the pod's CPU request. On 16-vCPU nodes, each linkly pod may open 16 connections. Multiply by the HPA's maximum and compare with PostgreSQL's limit (100 by default):

python · try it yourself
def budget(pods, per_pod, max_connections=100, reserved=10):
    """reserved: superuser slots, the operator, backups, migrations, your psql session."""
    need = pods * per_pod
    free = max_connections - reserved
    verdict = "OK" if need <= free else f"FAILS: {need - free} connections short"
    return f"{pods:>2} pods x {per_pod:>2} conns = {need:>3} of {free} usable -> {verdict}"

print("pgxpool default on 16-vCPU nodes:")
for pods in (3, 6, 12):
    print("  " + budget(pods, 16))
print("pool_max_conns=5 in DATABASE_URL:")
for pods in (3, 6, 12):
    print("  " + budget(pods, 5))
pgxpool default on 16-vCPU nodes:
   3 pods x 16 conns =  48 of 90 usable -> OK
   6 pods x 16 conns =  96 of 90 usable -> FAILS: 6 connections short
  12 pods x 16 conns = 192 of 90 usable -> FAILS: 102 connections short
pool_max_conns=5 in DATABASE_URL:
   3 pods x  5 conns =  15 of 90 usable -> OK
   6 pods x  5 conns =  30 of 90 usable -> OK
  12 pods x  5 conns =  60 of 90 usable -> OK

At minimum scale the default fits, so it passes every test, and the first traffic spike that scales the HPA out makes new pods fail with too many clients exactly when you need them. Set the pool size explicitly in the connection string (…/linkly?pool_max_conns=5, a pgx parameter) or in code, size it from the database's limit divided by the HPA's maxReplicas, and add a connection pooler (PgBouncer; CloudNativePG has a Pooler resource) when that division gets too small. Also set GOMAXPROCS if the Go version you run doesn't already follow the container's CPU limit.

Closing the gaps: TLS, signatures, migrations

The session validates the manifests for three hardening steps against the Gateway API, cert-manager, Kyverno and Kubernetes schemas:

bash · try it yourself
cat > hardening.yaml <<'X'
# 1. HTTPS at the Gateway, certificates from Let's Encrypt via cert-manager, HTTP redirected
apiVersion: gateway.networking.k8s.io/v1
kind: Gateway
metadata:
  name: public
  namespace: gateway-system
  annotations: {cert-manager.io/cluster-issuer: letsencrypt}
spec:
  gatewayClassName: eg
  listeners:
    - name: http
      protocol: HTTP
      port: 80
    - name: https
      protocol: HTTPS
      port: 443
      hostname: lnk.example.com
      tls:
        mode: Terminate
        certificateRefs: [{name: lnk-example-com-tls}]
      allowedRoutes:
        namespaces:
          from: Selector
          selector: {matchLabels: {app.kubernetes.io/part-of: linkly}}
---
apiVersion: gateway.networking.k8s.io/v1
kind: HTTPRoute
metadata: {name: https-redirect, namespace: gateway-system}
spec:
  parentRefs: [{name: public, sectionName: http}]
  rules:
    - filters:
        - type: RequestRedirect
          requestRedirect: {scheme: https, statusCode: 301}
---
apiVersion: cert-manager.io/v1
kind: ClusterIssuer
metadata: {name: letsencrypt}
spec:
  acme:
    server: https://acme-v02.api.letsencrypt.org/directory
    email: platform@example.com
    privateKeySecretRef: {name: letsencrypt-account}
    solvers:
      - http01:
          gatewayHTTPRoute:
            parentRefs: [{name: public, namespace: gateway-system, kind: Gateway}]
---
# 2. Only images signed by linkly's release workflow may run in linkly's namespaces
apiVersion: kyverno.io/v1
kind: ClusterPolicy
metadata: {name: verify-linkly-images}
spec:
  webhookTimeoutSeconds: 30
  rules:
    - name: signed-by-ci
      match:
        any:
          - resources: {kinds: [Pod], namespaces: [linkly-staging, linkly-production]}
      verifyImages:
        - imageReferences: ["ghcr.io/acme/linkly*"]
          failureAction: Enforce
          mutateDigest: true
          attestors:
            - entries:
                - keyless:
                    issuer: https://token.actions.githubusercontent.com
                    subject: https://github.com/acme/linkly/.github/workflows/ci.yml@refs/tags/*
                    rekor: {url: https://rekor.sigstore.dev}
---
# 3. Migrations once per sync, before the new pods (needs a `linkly migrate` subcommand)
apiVersion: batch/v1
kind: Job
metadata:
  name: linkly-migrate
  annotations:
    argocd.argoproj.io/hook: PreSync
    argocd.argoproj.io/hook-delete-policy: BeforeHookCreation
spec:
  backoffLimit: 2
  activeDeadlineSeconds: 300
  template:
    spec:
      restartPolicy: Never
      securityContext: {runAsNonRoot: true, runAsUser: 65532, seccompProfile: {type: RuntimeDefault}}
      containers:
        - name: migrate
          image: ghcr.io/acme/linkly@sha256:4f53cda18c2baa0c0354bb5f9a3ecbe5ed12ab4d8e11ba873c2f11161202b945
          args: [migrate]
          env:
            - name: DATABASE_URL
              valueFrom: {secretKeyRef: {name: linkly-db-app, key: uri}}
          securityContext: {allowPrivilegeEscalation: false, readOnlyRootFilesystem: true, capabilities: {drop: [ALL]}}
X
kubeconform -strict -summary -n 1 hardening.yaml
yq -N '.kind + "/" + .metadata.name' hardening.yaml
Summary: 5 resources found in 1 file - Valid: 5, Invalid: 0, Errors: 0, Skipped: 0
Gateway/public
HTTPRoute/https-redirect
ClusterIssuer/letsencrypt
ClusterPolicy/verify-linkly-images
Job/linkly-migrate

TLS. cert-manager watches the Gateway's annotation, requests a certificate for the HTTPS listener's hostname and stores it in the lnk-example-com-tls Secret; the HTTP-01 challenge is answered through a temporary HTTPRoute on the same Gateway. cert-manager's Gateway API support must be switched on in its configuration. The redirect route attaches only to the http listener (sectionName), so plain HTTP gets a 301 and linkly's own route lives on HTTPS.

Signatures. The release job signs the pushed digest with cosign keyless signing: the GitHub Actions OIDC token proves which workflow, repository and tag built it, and the signature is recorded in the Rekor transparency log (Signing, Supply Chain Security). In CI that is one step after the push, with id-token: write permission:

yaml
      - run: cosign sign --yes ghcr.io/acme/linkly@${{ steps.push.outputs.digest }}

Kyverno then refuses any linkly Pod whose image wasn't signed by that workflow on a tag, and mutateDigest rewrites tags to digests at admission. A stolen registry token can push an image, but can't make it run.

Migrations. CREATE TABLE IF NOT EXISTS at startup was fine for one table. Real schema changes (adding a column, an index built concurrently) should run once, before new pods start, and fail the sync if they fail: an Argo CD PreSync hook Job does that. It needs linkly to accept a migrate argument (an Exercise), and the schema changes themselves must be backwards compatible with the version still running (expand, deploy, contract), because during a rollout old and new pods share the database.

Abuse, backups, and what else to decide

  • Who may create links? As written, anyone who can reach POST /links can turn your domain into a phishing redirector. Options: an API key or OIDC token checked by linkly, or authentication at the Gateway (Envoy Gateway's SecurityPolicy supports JWT and OIDC), plus a rate limit per client (BackendTrafficPolicy in Envoy Gateway). Redirects (GET /{code}) stay public.
  • Malicious targets. Check new URLs against a blocklist or a safe-browsing API before storing them, and give operators a way to disable a code.
  • Backups. CloudNativePG continuously archives WAL and takes base backups to object storage (S3, GCS, Azure Blob, or MinIO on the local track) through its backup plugin, and restores by creating a new Cluster from the backup. RDS takes automated daily snapshots plus transaction logs for point-in-time restore. A backup you haven't restored is a hope: schedule a restore drill into a scratch database and check the row count.
  • Redis is disposable by design (no persistence), so it needs no backup; losing it costs cache misses.

Test yourself

In model 1, why do requests fail without a preStop sleep even though srv.Shutdown drains in-flight requests?

  1. Shutdown drops in-flight requests
  2. Proxies keep routing new requests to the pod until the endpoint removal reaches them, and the listener is already closed
  3. The pod restarts
  4. The readiness probe is too slow

Why can pgxpool's default pool size pass every test and still fail in production?

  1. It is random
  2. It follows the node's CPU count, and the total only exceeds max_connections when the HPA scales out
  3. pgx ignores max_connections
  4. Tests use SQLite

What does the Kyverno verifyImages rule protect against?

  1. Vulnerable dependencies
  2. An image that was pushed to the registry but not built and signed by linkly's release workflow running
  3. Slow image pulls
  4. Missing resource limits