Skip to main content

Cloud-Native, Kubernetes & Deployment Strategies

Learning objectives
  • Apply the twelve-factor principles to a Go service and explain which ones matter most in regulated environments
  • Configure the Kubernetes primitives that determine availability: Deployment, Service, Ingress, HPA, PDB, probes, topology spread
  • Choose between rolling, blue/green, canary, feature flags and dark launches for a given change
  • Describe a GitOps and Terraform workflow, including how config and secrets are handled
  • Design a hybrid cloud / on-prem deployment that satisfies a bank's data-residency and core-integration constraints

TL;DR​

  • Twelve-factor: one codebase, explicit dependencies, config in the environment, stateless disposable processes, logs as streams, dev/prod parity. It is the contract that makes services schedulable by Kubernetes.
  • Kubernetes availability is configuration: replicas spread across zones, readiness/liveness/startup probes, graceful shutdown, a PodDisruptionBudget, sensible requests/limits, and an HPA. Missing any one of these causes outages during routine operations.
  • Rolling updates are the default; blue/green gives instant rollback at double cost; canary limits blast radius with metric-based promotion; feature flags decouple deploy from release; dark launches test in production without user impact.
  • GitOps (Argo CD, Flux): Git is the source of truth; an agent in the cluster pulls and continuously reconciles. Terraform/OpenTofu manages the infrastructure underneath with plans reviewed in PRs.
  • Secrets never live in Git in plain text; use a secret manager (Vault, cloud KMS-backed stores) with rotation, and HSMs for cryptographic keys in banks.
  • Banks run hybrid: core and card data on-prem or in a private cloud, digital channels and analytics in public cloud where regulation permits, with a consistent platform layer and private connectivity.

Why it matters​

Many production incidents are not caused by code bugs but by deployments: a rollout that killed all pods at once, a liveness probe that restarted a service during a slow database failover, a node drain during a sale that took the cart service below capacity, a configuration change pushed straight to production. For an e-commerce company deploying dozens of times a day, the deployment system is the reliability system. For a bank, it is also the change-control evidence auditors examine: who approved what, when it was deployed, and how it was rolled back.

Interviewers increasingly expect architects to talk fluently about this layer: "How would you deploy this payment service with zero downtime?", "How do you roll out a risky change to the pricing engine before 11.11?", "How do you handle secrets?", "What runs on-prem vs cloud and why?"

Core concepts​

The twelve-factor app​

#FactorMeaningArchitect's note
ICodebaseOne codebase per app, many deploysMonorepo is fine; one deployable per build target
IIDependenciesDeclare and isolatego.mod, pinned base images, SBOMs for audit
IIIConfigStore config in the environmentNever in the image; differs per environment
IVBacking servicesTreat DBs, queues, caches as attached resourcesSwap via config; enables DR failover
VBuild, release, runStrictly separate stagesImmutable, signed artifacts; release = build + config
VIProcessesStateless, share-nothingSession state in Redis/DB, not in memory
VIIPort bindingExport services via a portSelf-contained HTTP/gRPC server
VIIIConcurrencyScale out via processesHorizontal scaling with HPA
IXDisposabilityFast startup, graceful shutdownCritical for rolling deploys and autoscaling
XDev/prod parityKeep environments similarSame images, Testcontainers, IaC for all envs
XILogsTreat logs as event streamsstdout JSON; collector ships to storage
XIIAdmin processesRun one-off tasks as processesMigrations as Jobs, with audit trail

Containers​

  • Immutable images: build once, promote the same digest through environments. Tag with version and pin by digest in production manifests.
  • Small, minimal images: multi-stage builds with a static Go binary on a distroless or scratch base reduce the attack surface and the vulnerability-scan noise that bank security teams care about.
  • Supply chain: scan images (Trivy, Grype), produce SBOMs, sign images (Sigstore cosign), and enforce signature verification at admission.
  • Resource awareness: Go 1.25+ sets GOMAXPROCS from the container's CPU limit; on older versions use go.uber.org/automaxprocs. Set GOMEMLIMIT a bit below the memory limit to make the GC work before the OOM killer does.
FROM golang:1.25 AS build
WORKDIR /src
COPY go.mod go.sum ./
RUN go mod download
COPY . .
RUN CGO_ENABLED=0 go build -trimpath -ldflags="-s -w" -o /out/payment-api ./cmd/payment-api

FROM gcr.io/distroless/static-debian12:nonroot
COPY --from=build /out/payment-api /payment-api
USER nonroot:nonroot
ENTRYPOINT ["/payment-api"]

The kernel mechanisms underneath (namespaces, cgroups) are covered in Linux Containers.

Kubernetes primitives that decide availability​

PrimitiveWhat it doesGets you in trouble when
PodOne or more containers sharing network and volumesYou run singletons as bare pods
DeploymentDesired state for stateless pods; rolling updates via ReplicaSetsmaxUnavailable too high, or too few replicas to survive a zone loss
StatefulSetStable identity and storage per podYou run a database on it without operational expertise
ServiceStable virtual IP/DNS and load balancing to ready podsYou expect per-request balancing for gRPC (it balances connections)
Ingress / Gateway APIL7 routing from outside into ServicesOne shared ingress controller with no capacity planning for peak
HPAScales replicas on CPU, memory or custom metricsScaling on CPU for an I/O-bound service; max replicas exhausts DB connections
PDBCaps how many pods voluntary disruptions (drains, upgrades) can removeMissing (node drain kills all replicas) or too strict (maxUnavailable: 0 blocks node upgrades forever)
ProbesStartup, readiness, liveness health checksLiveness checks dependencies, so a DB blip restarts every pod
Requests / limitsScheduling guarantees and capsNo requests (noisy neighbours); tight CPU limits causing throttling and latency spikes
ConfigMap / SecretInject configuration and credentialsSecrets assumed encrypted (they are base64 unless encryption at rest is enabled)

Probes, precisely:

  • Startup probe — "has the app finished starting?" Liveness and readiness are not checked until it passes. Use for slow-starting apps instead of long initial delays.
  • Readiness probe — "should this pod receive traffic now?" Failing removes it from Service endpoints without restarting. It may check critical local dependencies briefly, but avoid making every pod unready because a shared dependency is down (that turns a partial outage into a total one).
  • Liveness probe — "is the process stuck beyond repair?" Failing restarts the container. Keep it cheap and independent of downstream dependencies.

A production-grade manifest​

apiVersion: apps/v1
kind: Deployment
metadata:
name: payment-api
labels:
app: payment-api
spec:
replicas: 6
strategy:
type: RollingUpdate
rollingUpdate:
maxSurge: 25%
maxUnavailable: 0 # never drop below desired capacity during a rollout
selector:
matchLabels:
app: payment-api
template:
metadata:
labels:
app: payment-api
spec:
terminationGracePeriodSeconds: 40
topologySpreadConstraints:
- maxSkew: 1
topologyKey: topology.kubernetes.io/zone
whenUnsatisfiable: DoNotSchedule
labelSelector:
matchLabels:
app: payment-api
containers:
- name: app
image: registry.example.com/payments/payment-api:1.42.0
ports:
- containerPort: 8080
env:
- name: GOMEMLIMIT
value: "450MiB"
- name: DB_DSN
valueFrom:
secretKeyRef:
name: payment-api-db
key: dsn
resources:
requests:
cpu: "500m"
memory: "256Mi"
limits:
memory: "512Mi"
startupProbe:
httpGet:
path: /healthz
port: 8080
periodSeconds: 2
failureThreshold: 30
readinessProbe:
httpGet:
path: /readyz
port: 8080
periodSeconds: 5
failureThreshold: 2
livenessProbe:
httpGet:
path: /healthz
port: 8080
periodSeconds: 10
failureThreshold: 3
---
apiVersion: policy/v1
kind: PodDisruptionBudget
metadata:
name: payment-api
spec:
maxUnavailable: 1
selector:
matchLabels:
app: payment-api
---
apiVersion: autoscaling/v2
kind: HorizontalPodAutoscaler
metadata:
name: payment-api
spec:
scaleTargetRef:
apiVersion: apps/v1
kind: Deployment
name: payment-api
minReplicas: 6
maxReplicas: 40
metrics:
- type: Resource
resource:
name: cpu
target:
type: Utilization
averageUtilization: 60
behavior:
scaleUp:
stabilizationWindowSeconds: 0
policies:
- type: Percent
value: 100
periodSeconds: 30
scaleDown:
stabilizationWindowSeconds: 300
policies:
- type: Percent
value: 10
periodSeconds: 60

Design notes: six replicas across three zones survive the loss of one zone with four remaining; maxUnavailable: 0 keeps capacity during rollouts; the PDB lets node upgrades proceed one pod at a time; scale-up is aggressive and scale-down is slow to avoid flapping after a flash-sale spike; maxReplicas: 40 must be checked against the database connection budget (40 pods × pool size ≤ what Postgres or its pooler can handle).

Graceful shutdown in Go​

When a pod is deleted, Kubernetes sends SIGTERM and, in parallel, removes the pod from endpoints — but proxies and load balancers take a few seconds to notice. The app should keep serving briefly, stop accepting new work, finish in-flight requests, then exit.

package main

import (
"context"
"errors"
"log"
"net/http"
"os"
"os/signal"
"sync/atomic"
"syscall"
"time"
)

func main() {
ctx, stop := signal.NotifyContext(context.Background(), syscall.SIGTERM, os.Interrupt)
defer stop()

var draining atomic.Bool
mux := http.NewServeMux()
mux.HandleFunc("/healthz", func(w http.ResponseWriter, _ *http.Request) {
w.WriteHeader(http.StatusOK)
})
mux.HandleFunc("/readyz", func(w http.ResponseWriter, _ *http.Request) {
if draining.Load() {
http.Error(w, "draining", http.StatusServiceUnavailable)
return
}
w.WriteHeader(http.StatusOK)
})
// mux.Handle("/v1/transfers", ...) — business handlers

srv := &http.Server{Addr: ":8080", Handler: mux, ReadHeaderTimeout: 5 * time.Second}
go func() {
if err := srv.ListenAndServe(); err != nil && !errors.Is(err, http.ErrServerClosed) {
log.Fatalf("listen: %v", err)
}
}()

<-ctx.Done()
draining.Store(true)
time.Sleep(5 * time.Second) // let endpoint removal propagate to proxies

shutdownCtx, cancel := context.WithTimeout(context.Background(), 25*time.Second)
defer cancel()
if err := srv.Shutdown(shutdownCtx); err != nil {
log.Printf("graceful shutdown incomplete: %v", err)
}
// Then: stop Kafka consumers (commit offsets), close DB pools, flush telemetry.
}

The total (5 s + up to 25 s) must fit inside terminationGracePeriodSeconds (40 s above).

Deployment strategies​

StrategyHowRollbackCostBest for
RecreateStop all old, start newRedeploy oldLowestDev, batch workers that must not overlap
RollingReplace pods graduallyRoll back graduallyLowDefault for stateless services
Blue/greenFull new environment, switch routerInstant switch back2× capacity during releaseBig-bang changes, banks' weekend releases with fast rollback
CanarySend a small % of traffic to new version, promote on metricsShift traffic backLow–mediumHigh-traffic services where metrics detect problems quickly
Feature flagsCode deployed dark; behaviour enabled per user/segmentToggle offCode complexity, flag debtDecoupling deploy from release, gradual exposure, kill switches
Dark launch / shadow trafficNew version receives copies of real traffic; responses discardedN/A (not serving)Extra capacityValidating performance and correctness of a rewrite

Practical points:

  • Canary analysis must include business metrics — payment success rate, add-to-cart rate — not just HTTP 5xx. Tools: Argo Rollouts, Flagger, or a service mesh's traffic splitting.
  • Database changes must be backward compatible across two versions running simultaneously (expand → migrate → contract). See Zero-Downtime Schema Migrations.
  • Feature flag types (Pete Hodgson): release toggles (short-lived), ops toggles / kill switches (long-lived: "disable recommendations on 11.11"), experiment toggles, permission toggles. Remove release toggles quickly; flag debt is real. OpenFeature is a CNCF vendor-neutral flag API.
  • Shadow traffic for payments is dangerous: the shadow must never move money or call real external systems. Use it for read paths or with stubbed side effects; for money, prefer a parallel run comparing results.
  • Freeze windows: e-commerce often freezes risky changes a few days before 11.11 / Black Friday; banks freeze around month-end, year-end closing and Tết. Plan capacity changes before the freeze.

GitOps​

OpenGitOps principles: the desired state is declarative, versioned and immutable, pulled automatically by agents, and continuously reconciled. Benefits for banks: every production change is a reviewed, approved Git commit — a ready-made audit trail and change record; rollback is git revert; the cluster has no inbound CI credentials (pull model). Watch out for secrets (do not commit them) and for emergency changes (break-glass procedure that is also recorded).

Infrastructure as code (Terraform / OpenTofu)​

terraform {
backend "s3" {
bucket = "bank-tfstate-prod"
key = "payments/postgres.tfstate"
region = "ap-southeast-1"
encrypt = true
use_lockfile = true # S3-native state locking (Terraform 1.10+); older setups use DynamoDB
}
}

resource "aws_db_instance" "payments" {
identifier = "payments-prod"
engine = "postgres"
engine_version = "16"
instance_class = "db.r6g.xlarge"
allocated_storage = 500
storage_encrypted = true
kms_key_id = aws_kms_key.payments.arn
multi_az = true
backup_retention_period = 35
deletion_protection = true
performance_insights_enabled = true
db_subnet_group_name = aws_db_subnet_group.private.name
vpc_security_group_ids = [aws_security_group.payments_db.id]
}

Workflow: terraform plan runs on every PR and is posted for review; apply runs from CI after approval, never from laptops; state is remote, encrypted and locked; policy as code (OPA/Conftest, Sentinel, Checkov) blocks non-compliant resources (unencrypted storage, public buckets); scheduled plans detect drift. Use modules for repeatable patterns (a "PCI-compliant Postgres" module). OpenTofu is the open-source fork of Terraform with a compatible language.

Config and secrets​

TypeWhereNotes
Non-sensitive configEnv vars / ConfigMaps in the config repoValidate at startup; fail fast on missing config
Credentials (DB passwords, API keys)Secret manager (HashiCorp Vault, AWS Secrets Manager, GCP Secret Manager, Azure Key Vault) synced via External Secrets Operator or the Secrets Store CSI driverRotate automatically; prefer short-lived dynamic credentials (Vault DB engine)
Secrets in GitOnly encrypted (Sealed Secrets, SOPS)Key management becomes the critical part
Cryptographic keys for payments (PIN, card keys, signing)HSM (on-prem or cloud HSM)Keys never leave the HSM; required by PCI PIN / scheme rules
Workload identityCloud IAM roles for service accounts / SPIFFE identitiesRemoves static credentials entirely

Kubernetes Secret objects are base64-encoded, not encrypted; enable encryption at rest (KMS provider) and restrict RBAC on them.

Hybrid cloud and on-prem in banks​

Why banks stay hybrid:

  • Regulation and data residency — central-bank rules on outsourcing, cloud and data location (in Vietnam, the State Bank of Vietnam's information-system security regulations; check the current versions) may restrict which data and systems can run in public cloud.
  • Core systems (mainframes, vendor cores, card switches, HSMs) live on-prem and need low-latency access from payment services.
  • Existing investment in data centres and long vendor contracts.

Patterns: a consistent platform across both sides (OpenShift is common in banks; also Anthos, Azure Arc, EKS Anywhere); classify data and place workloads by classification; private connectivity (Direct Connect, ExpressRoute, Cloud Interconnect) with redundancy; burst non-sensitive workloads (marketing campaigns, analytics) to public cloud; and the same GitOps/IaC pipeline for both, so controls and evidence are uniform.

Trade-offs​

ChoiceStrengthsWeaknessesChoose when
Managed Kubernetes (EKS/GKE/AKS)Control plane managed, fast to startCloud dependency, still complexCloud-first e-commerce
On-prem Kubernetes / OpenShiftData control, regulatory comfort, proximity to coreYou operate everything; capacity planning lead timesBanks' core-adjacent workloads
Serverless containers (Cloud Run, Fargate)No node managementLess control, networking limitsSmall teams, spiky services
RollingSimple, cheapMixed versions during rollout; slower rollbackDefault
Blue/greenInstant rollback, clean cutoverDouble capacity; DB must serve bothInfrequent, high-risk releases
CanarySmall blast radius, data-drivenNeeds good metrics and traffic routingHigh-traffic critical services
GitOps pullAudit trail, drift correction, no cluster creds in CILearning curve; secret handlingMost Kubernetes estates, especially regulated
CI push (kubectl apply)SimpleDrift, credentials in CI, weaker auditSmall, non-critical setups

In practice​

  • Rollout checklist for a payment service: replicas ≥ 2 per zone for critical services; PDB; startup/readiness/liveness probes with dependency-free liveness; graceful shutdown tested; maxUnavailable: 0; canary with payment-success-rate analysis; DB migration backward compatible; feature flag for new behaviour; runbook link in the release notes.
  • Pre-scaling for events: HPA reacts in tens of seconds to minutes (metrics scrape, pod start, image pull, node provisioning). For a flash sale at 20:00 sharp, raise minReplicas and pre-provision nodes beforehand. See Capacity Planning & Cost.
  • Cluster autoscaling (Cluster Autoscaler or Karpenter) adds nodes, but new nodes take time; keep a buffer of spare capacity (low-priority placeholder pods are a common trick).
  • Multi-cluster for blast radius and DR: one cluster per region or per environment tier; avoid one giant shared cluster for everything critical.

Common pitfalls​

  • Liveness probe calls the database. A 30-second DB failover restarts every pod, extending the outage. Keep liveness local.
  • No graceful shutdown. Every deploy produces a burst of 502s and broken in-flight payments.
  • No PDB / no topology spread. A node drain or zone outage removes most replicas at once.
  • CPU limits too tight. Throttling causes p99 spikes under load even when average CPU looks fine.
  • HPA max not reconciled with downstream limits. Scaling to 200 pods opens 4,000 DB connections and takes down Postgres.
  • Config drift via kubectl edit in production. Symptom: the next GitOps sync silently reverts an emergency fix, or the fix is never recorded.
  • Feature flag debt. Hundreds of stale flags; nobody knows which combinations are tested.

Interview angle​

  • For "deploy with zero downtime", cover: rolling with surge, readiness probes, graceful shutdown, PDB, backward-compatible DB migrations, canary with automatic rollback, and feature flags.
  • For a bank, mention change control: GitOps commits as change records, approvals in PRs, segregation of duties (the author cannot approve their own production change), and freeze windows.
  • For e-commerce peaks, mention pre-scaling, node buffers, kill switches for non-critical features, and load-tested HPA limits.
  • Expect: "What's the difference between readiness and liveness?", "Why might canary not catch a bug?" (low traffic, metric blind spots, bug only in a segment), "How do you handle secrets?", "What would you keep on-prem?"
  • Red flags: liveness checks on dependencies, "we just restart pods", secrets in ConfigMaps or Git, blue/green without thinking about the shared database.

Self-check​

1. Explain the difference between startup, readiness and liveness probes, and what goes wrong if liveness checks the database.

Startup: has the app finished starting (gates the other probes). Readiness: should it receive traffic now (failing removes it from endpoints, no restart). Liveness: is it irrecoverably stuck (failing restarts the container). If liveness checks the database, a brief DB failover makes every pod fail liveness and restart simultaneously, turning a short dependency blip into a full outage with cold starts.

2. Why does a PodDisruptionBudget matter during routine operations, and what is the risk of setting it too strictly?

Node drains for upgrades and autoscaler scale-downs are voluntary disruptions; without a PDB they may evict many replicas of a service at once. A PDB caps how many can be down. Too strict (e.g. maxUnavailable 0, or minAvailable equal to replicas) blocks drains indefinitely, stalling cluster upgrades and security patching.

3. When would you choose blue/green over canary for a release?

When the change is a large cutover that cannot easily run at a small percentage (e.g. a new major version with a different protocol), when you need instant, complete rollback, when traffic is too low for canary metrics to be meaningful, or for a scheduled weekend release at a bank with a fixed change window. You pay with double capacity and must ensure the database works for both versions.

4. Scenario: a flash sale starts at 20:00. The HPA scales on CPU at 60%. What can still go wrong, and what do you change?

Traffic jumps in seconds while HPA, pod startup and node provisioning take tens of seconds to minutes, so the first minutes are under-provisioned; new nodes may not exist; maxReplicas may exceed DB connection limits; image pulls may be slow. Pre-scale minReplicas and nodes before 20:00, keep a placeholder-pod buffer, pre-pull images, verify DB pooler limits, add kill switches for non-critical features and load-test the whole scale path.

5. What are the four OpenGitOps principles, and why do auditors like GitOps?

Declarative desired state; versioned and immutable; pulled automatically; continuously reconciled. Auditors like it because every change is a reviewed, approved commit with an author and timestamp, deployments are reproducible, drift is detected and corrected, and rollback is a traceable revert.

6. How should a bank handle the key used to sign payment messages to the national switch?

Generate and store it in an HSM (on-prem or a dedicated cloud HSM approved by policy) so the private key never leaves the device; services request signing operations via the HSM API with strong authentication; access is controlled with dual control and audited; keys are rotated per policy with a documented key ceremony. It must never be in a Kubernetes Secret, environment variable or Git.

7. Which workloads would you keep on-prem and which move to public cloud at a mid-size bank?

On-prem / private cloud: core banking, card and payment switching, HSMs, systems holding raw sensitive data, and services needing low latency to them. Public cloud (where regulation permits, in-country or approved regions): customer-facing channels and BFFs, marketing, analytics and ML on tokenized or masked data, dev/test environments with synthetic data. Connect via redundant private links and run one platform and pipeline for both.

🧠 Flashcards0/9 learned · 0 retries

Exercise​

Deploy the Go service from this page to a local cluster (kind or minikube):

  1. Write the Deployment, Service, PDB and HPA manifests above; add a /v1/slow endpoint that sleeps 3 s.
  2. Run a load generator (k6 or hey) against /v1/slow while doing kubectl rollout restart. Count failed requests with and without the graceful shutdown code.
  3. Make liveness depend on a fake "database" endpoint, break it, and observe the restart storm; then fix it.
  4. Install Argo Rollouts (or simulate with two Deployments and weighted routing) and run a canary at 10% → 50% → 100% with a manual gate.
  5. Write a one-page runbook: how to roll back, how to disable a feature via flag, and who approves production changes.

Done when: a rolling restart under load produces zero failed requests, and you can show the canary promotion steps in kubectl output.

Further reading​

  • Adam Wiggins, The Twelve-Factor App (12factor.net).
  • Kubernetes documentation (kubernetes.io): Deployments, Pod lifecycle and probes, Disruptions and PDBs, Horizontal Pod Autoscaling.
  • Kubernetes Patterns (2nd ed.) — Bilgin Ibryam & Roland Huß (O'Reilly, 2023).
  • Production Kubernetes — Rosso, Lander, Brand, Harris (O'Reilly, 2021).
  • Pete Hodgson, "Feature Toggles (aka Feature Flags)" (martinfowler.com, 2017).
  • OpenGitOps principles (opengitops.dev); Argo CD and Flux documentation.
  • Terraform: Up & Running (3rd ed.) — Yevgeniy Brikman (O'Reilly, 2022).
  • Accelerate — Forsgren, Humble, Kim (2018). Delivery performance metrics.
Finished this page?

Do the self-check first. Marking it complete schedules spaced reviews (1, 3, 7, 14, 30… days).