Book 9 · Volume VII — Cloud-Native Architecture & Multi-Region Systems · Topic 1.3
Immutable Infrastructure
Replace instead of patch: every change is a new, tested artifact
11 min readStage 4 · Production & architecture10 interview questions
Written byMaheshFounder · Senior Technical Architect
Chapter
Chapter 1 — Cloud-Native Architecture
Prerequisites
Topics 1.1–1.2; Volume V
You will be able to
Design immutable delivery for containers, nodes and VMs, build golden image pipelines with hardening and patch cadence, deploy by replacement, enforce runtime immutability, handle state and secrets, debug without mutation, and demonstrate audit benefits
Immutable infrastructure means servers, containers and other runtime units are never modified after deployment. To change anything — code, configuration of the image, OS patches — you build a new artifact, test it, and replace the running instances. The running environment therefore always matches a known, versioned, reproducible definition.
Figure 1 — Mutable vs immutable infrastructure
Figure 2 — Immutable delivery pipeline
Vocabulary
Meaning
Golden image
Hardened, pre-baked base image/AMI
Drift
Divergence between running state and definition
Instance refresh
Rolling replacement of instances with a new launch template
Read-only root filesystem
Container cannot modify its own image at runtime
Table 1 — Terms
2Why It Exists
Figure 3 — Configuration drift findings (monthly)
Mutable-world problem
Immutable answer
"Works on server 3 but not server 7"
All instances from the same image
Emergency hotfixes via SSH never recorded
No SSH; change = new artifact
Patch Tuesday breaks production
Patched image tested in staging first
Rollback means un-patching
Redeploy previous image
Attackers persist on long-lived hosts
Short-lived, replaced instances
Table 2 — Why
3Core Concepts — Immutable Infrastructure
Layer
Immutable unit
Replacement mechanism
Application
Container image (by digest)
Rolling update / Argo Rollouts
Node OS
Bottlerocket / EKS-optimised AMI
Karpenter drift, managed node group update
VM workloads
Golden AMI
ASG instance refresh / blue-green
Serverless
Lambda version + alias
Alias shift (CodeDeploy)
Infrastructure
Terraform module versions
Plan/apply creating replacements
Config
Git commit (ConfigMaps rendered)
Rollout triggered by hash annotation
Table 3 — Units per layer
4How It Works Internally — Golden Image Pipeline (ShopNow)
Stage
Tooling
Detail
Base selection
Chainguard/UBI minimal JRE, Bottlerocket
Minimal attack surface
Build
Docker BuildKit / EC2 Image Builder
Reproducible, pinned versions
Harden
CIS benchmarks, remove shells where possible
Distroless for apps
Scan
Trivy/Inspector
Block high/critical
Sign & attest
cosign + SBOM + provenance
Admission verifies
Publish
ECR / AMI catalog with version tags
Immutable tags
Rollout
Staging → prod progressive
Automatic cadence
Retire
Deregister images > 90 days (keep last N)
Hygiene
Table 4 — Pipeline
4ADeep Dive — Patch Cadence by Replacement
Component
Cadence
Mechanism
Base JRE images
Weekly rebuild + on critical CVE
Renovate PRs, CI rebuild of all services
Bottlerocket nodes
Weekly AMI release
Karpenter drift replaces nodes within disruption budgets
Golden AMIs (legacy EC2)
Monthly + critical
Image Builder pipeline → instance refresh
Managed services
Provider-managed
Maintenance windows / zero-downtime patching
Table 5 — Patching = replacing
4BDeep Dive — Runtime Immutability
Control
Effect
readOnlyRootFilesystem: true
No writes to image layers; writable emptyDir only where needed
runAsNonRoot, drop all capabilities
Limits mutation and escalation
No SSH, no shell in distroless images
No interactive changes
Kyverno policies enforcing the above
Guardrails
Drift detection (Argo CD self-heal)
Reverts manual kubectl edits
Table 6 — Enforce immutability at runtime
4CDeep Dive — State with Immutable Compute
State
Where
Databases
Managed services (Aurora, DynamoDB) — not on instances
# Karpenter NodePool: Bottlerocket nodes replaced on drift within a disruption budgetapiVersion: karpenter.sh/v1kind: NodePoolmetadata: { name: general }spec: template: spec: nodeClassRef: { group: karpenter.k8s.aws, kind: EC2NodeClass, name: bottlerocket } expireAfter: 336h # max node lifetime 14 days disruption: consolidationPolicy: WhenEmptyOrUnderutilized budgets: [{ nodes: "10%" }]
HCL
# Legacy EC2 fleet: new golden AMI → rolling instance refreshresource "aws_autoscaling_group" "reports" { name = "reports-asg" min_size = 2 max_size = 6 vpc_zone_identifier = var.private_subnets launch_template { id = aws_launch_template.reports.id version = aws_launch_template.reports.latest_version # AMI from Image Builder } instance_refresh { strategy = "Rolling" preferences { min_healthy_percentage = 90 } }}
6Practical Examples
6.1 Drift from 140 to 3
ShopNow's legacy EC2 fleet had 140 drifted resources per month from manual fixes. Golden AMIs and instance refresh cut it to 22; moving to EKS with Bottlerocket and Argo self-heal brought it to 3.
6.2 Log4Shell-style response
When a critical Java library CVE appeared, Renovate raised PRs, all services rebuilt on the pipeline and rolled out within 30 hours — without touching any running container.
6.3 Attacker persistence prevented
A penetration test achieved code execution in a pod but could not persist: read-only filesystem, no shell, and nodes replaced within 14 days.
6.4 Worked example — rollback by artifact
Step
Detail
Revert GitOps digest
Previous image restored in minutes
Table 10 — Rollback is redeploy
6.5 Worked example — image tagging
Rule
Reason
Deploy by digest; tags immutable in ECR
No tag hijacking
Table 11 — Immutable references
6.6 Worked example — node lifetime
Setting
Value
expireAfter
14 days
Table 12 — Short-lived hosts
6.7 Worked example — interview whiteboard
Prompt
Answer outline
"How would you implement immutable infrastructure?"
"Every layer versioned: app images by digest, Bottlerocket/golden AMIs for nodes/VMs, Lambda versions, Terraform modules, config in Git. Golden image pipeline: minimal base, reproducible build, hardening, scan, sign/attest, publish, progressive rollout, retirement. Patch by rebuilding and replacing on a cadence (Renovate, Karpenter drift, instance refresh). Runtime immutability: read-only root, non-root, no SSH/shell, policies, drift self-heal. State in managed stores, secrets injected. Debug with ephemeral containers/SSM. Rollback = previous artifact. Audit via digests and attestations."
Table 13 — Structured answer
6.8 Worked example — PayGrid PCI benefit
PCI control
Immutable evidence
Change control, hardening, patching
Pipeline records, AMI versions
Table 14 — Compliance by construction
6.9 Worked example — anti-patterns
Anti-pattern
Effect
kubectl exec to "quick fix"
Drift, unaudited
Mutable "latest" tags
Unknown versions
Long-lived nodes
Patch lag, persistence
Config edited in consoles
Drift
Table 15 — Common mistakes
6.10 Worked example — config change rollout
Mechanism
Detail
ConfigMap hash annotation on pod template
Config change triggers rolling replacement
Table 16 — Config treated immutably
6.11 Worked example — Image Builder for EC2
Component
Content
Recipe
Base AMI + hardening + agents
Tests
CIS checks, boot tests
Table 17 — Golden AMI factory
6.12 Worked example — blue-green for VMs
Step
Detail
New ASG with new AMI; switch ALB target group
Instant rollback by switching back
Table 18 — Replacement at fleet level
6.13 Worked example — immutable Lambda
Mechanism
Detail
Publish version; alias shift 10% → 100%
Versioned functions
Table 19 — Serverless immutability
6.14 Worked example — reproducible builds
Practice
Detail
Pinned base digests, Maven lockfile/enforcer, SOURCE_DATE_EPOCH
Same input → same output
Table 20 — Trustworthy artifacts
6.15 Worked example — cost
Concern
Reality
More image builds
Cheap vs incidents from drift
Table 21 — Economics favour immutability
6.16 Worked example — interview follow-ups
Follow-up
Answer
"How do you patch quickly?"
Automated rebuild and replacement pipeline
"What about databases?"
Use managed services; data outside compute
Table 22 — Common probes
6.17 Worked example — checklist
Item
✔
Versioned artifacts per layer
✔
Golden pipelines
✔
Replacement patching
✔
Runtime immutability policies
✔
No SSH
✔
Drift detection
✔
Table 23 — Immutable baseline
6.18 Worked example — NovaBank legacy VMs
Step
Detail
Freeze manual changes; golden AMIs; SSM only
First immutable step before containerising
Table 24 — Incremental adoption
6.19 Worked example — image retention
Policy
Detail
Keep last 20 prod digests; expire untagged after 14 days
Rollback + hygiene
Table 25 — Lifecycle rules
6.20 Worked example — emergency change
Path
Detail
Break-glass pipeline with post-review
Still immutable
Table 26 — No console hotfixes
6.21 Worked example — interview scenario
Question
Answer
"Ops wants SSH for troubleshooting"
Provide SSM/ephemeral debug with audit; changes via pipeline
Table 27 — Enable without mutation
6.22 Worked example — node patch SLA
Severity
Replace within
Critical kernel CVE
48 h
Table 28 — Measurable patching
6.23 Worked example — immutable config for Java
Practice
Detail
No runtime property edits via actuator/env endpoint
Disabled in prod
Table 29 — Close mutation paths
6.24 Worked example — drift report
Source
Output
AWS Config + Argo diff
Weekly drift report
Table 30 — Measure immutability
6.25 Worked example — immutability maturity
Level
Characteristic
1
Manual changes on long-lived servers
2
Golden images, manual deploys
3
Pipelines replace instances; SSH restricted
4
No SSH, drift auto-reverted, node lifetimes enforced
Table 31 — Where ShopNow sits: level 4 for EKS, level 3 for legacy EC2
6.26 Worked example — config hash trigger
YAML
# Kustomize configMapGenerator appends a content hash → pods roll when config changesconfigMapGenerator: - name: checkout-config files: [application.yaml]
^Config changes become new immutable versions
6.27 Worked example — immutable infrastructure and incidents
Incident step
Immutable advantage
"What changed?"
Digest/AMI diff answers precisely
Rollback
Previous artifact, minutes
Table 32 — Faster, safer incident response
6.28 Worked example — node replacement budget
Setting
Effect
Disruption budget 10% + PDBs
Safe continuous replacement
Table 33 — Immutability without outages
7Common Problems & Mistakes
Mistake
Fix
Manual hotfixes
Pipeline
Mutable tags
Digests
Long-lived hosts
Expiry
State on instances
Managed stores
Table 34 — Mistakes and fixes
Some failures only appear once immutability is enforced. Turning on readOnlyRootFilesystem breaks Java services that write to /tmp, Tomcat's work directory or JFR recordings, so each needs an explicit emptyDir mount with a size limit. Configuration injected as environment variables or subPath mounts never updates in running pods, so a ConfigMap edit appears to work while pods keep the old values until something restarts them; the hash-annotation pattern makes this explicit. Argo CD self-heal disabled "temporarily" during an incident and never re-enabled lets drift return quietly. Break-glass access that becomes routine is simply SSH by another name, so every use should open a review. Finally, deploying by digest is undermined if base images are rebuilt under the same tag without services being rebuilt, leaving fleets on stale layers.
8Performance & Production Considerations
Consideration
Practice
Replacement churn
Disruption budgets
Image pull time
Small images, caching
Rollout duration
Progressive, parallel
Table 35 — Operating immutability
Immutability turns patching into constant, controlled churn, so the platform must make replacement cheap. With a fourteen-day node lifetime, every pod restarts at least every two weeks, which is safe only with graceful shutdown, PodDisruptionBudgets and fast startup. Karpenter disruption budgets can carry schedules, so drift replacement pauses during sale hours and runs overnight. Image pull time dominates scale-out: order Dockerfile layers so dependencies change less often than application code, use layered Spring Boot jars or Jib, and use an ECR pull-through cache for public bases. A base image change can trigger rebuilds of sixty services at once, so limit Renovate's concurrent pull requests and CI concurrency to avoid saturating runners. Track fleet age, the share of pods and nodes on the latest artifacts, as an operational metric.
9Architecture & Design Considerations
Guideline
Detail
Separate compute and data
Disposable compute
Everything versioned
Traceability
Enforce with policy
Guardrails
Table 36 — Design guidance
10Interview Questions & Answers
Q1L1 · BasicConcept
What is immutable infrastructure?
Immutable infrastructure means runtime units, such as containers, nodes, VMs and functions, are never modified after deployment. To change anything, including code, OS patches or baked configuration, you build a new versioned artifact, test it, and replace the running units with it. The running environment therefore always matches a known, reproducible definition: an image digest, an AMI ID, a Lambda version or a Terraform module version. At ShopNow this applies at every layer, from application images deployed by digest to Bottlerocket nodes replaced by Karpenter drift. The key mental model is that a change not captured in a new artifact is not a change at all, it is drift.
Q2L1 · BasicConcept
What is configuration drift?
Configuration drift is the divergence between what is actually running and what its definition says should be running. It accumulates through manual hotfixes over SSH, console edits, kubectl edit or exec quick fixes, and in-place patches applied to some servers but not others. The result is snowflake servers: two instances that should be identical behave differently, nobody knows the real configuration, and rebuilding from code produces something that no longer matches production. Drift also undermines security and audits, because you cannot prove what is running. ShopNow measures drift with AWS Config and Argo CD diffs, and cut monthly findings from 140 to 3 by making infrastructure immutable.
Q3L2 · IntermediateInternals
How are patches applied?
Patches are applied by rebuilding artifacts and replacing what runs, never by patching in place. For applications, Renovate raises pull requests when base JRE images or libraries change, and CI rebuilds, scans and signs every affected service, which then rolls out progressively. For EKS nodes, AWS publishes new Bottlerocket AMIs weekly and Karpenter detects drift and replaces nodes within disruption budgets. For legacy EC2, Image Builder produces a new golden AMI and an Auto Scaling instance refresh replaces the fleet. Managed services are patched by the provider. In the Log4Shell-style example, all services were rebuilt and rolled out within 30 hours without touching a single running container.
Q4L2 · IntermediateTricky
How is rollback done?
Rollback is a redeploy of the previous artifact, nothing more. With GitOps, you revert the commit that changed the image digest and Argo CD rolls the previous image back in minutes; for nodes or VMs, you point back to the previous AMI and replace again; for Lambda, you shift the alias back to the previous version. This only works if old artifacts are retained, ShopNow keeps the last 20 production digests. The catch is that rollback restores compute, not data. A schema migration or message format change made by the new version stays, so changes must be backward compatible using expand and contract, or rollback becomes impossible.
Q5L3 · Senior EngineerDesign
How do you enforce immutability in Kubernetes?
Enforce it in layers, so mutation is impossible rather than merely discouraged. In the pod spec, set readOnlyRootFilesystem, runAsNonRoot, allowPrivilegeEscalation false and drop all capabilities, with emptyDir volumes only where writes are needed. Build distroless images without shells or package managers, and deploy by digest from ECR repositories with immutable tags. Use admission policies, such as Kyverno or Pod Security Admission, to reject pods that violate these rules or use unsigned images. Remove kubectl exec and edit rights from humans in production, and let Argo CD self-heal revert any manual change to the desired state in Git. Finally, cap node lifetime with Karpenter's expireAfter.
Q6L3 · Senior EngineerScenario
How do you debug without SSH?
Give people the ability to observe without the ability to change. For pods, use kubectl debug to attach an ephemeral container with debugging tools to the running pod, granted through just-in-time access and fully audited, so the application image stays distroless. For EC2 hosts, use SSM Session Manager instead of SSH keys, with sessions logged to CloudWatch or S3. Collect JFR recordings, thread dumps and heap dumps through jcmd or Actuator and ship them to encrypted S3. Rich telemetry, logs, metrics and traces, should answer most questions without access at all. Any fix found goes through the pipeline as a new artifact, never as an edit on the box.
Q7L4 · Technical ArchitectDesign
Where does state go?
State goes into services designed to keep it, never onto the instances or containers that get replaced. Databases live in managed services such as Aurora or DynamoDB, files in S3 or EFS, and caches in Redis, treated as rebuildable. Logs and metrics stream off the host as they are produced. Secrets and configuration are injected at start from Secrets Manager, Parameter Store or ConfigMaps rather than baked into images. Temporary scratch space uses emptyDir and is discarded with the pod. The test is simple: any node or pod can be terminated at any moment, as Spot and Karpenter will do, without losing anything that matters.
Q8L4 · Technical ArchitectInternals
How do nodes stay patched?
Nodes stay patched because they are short-lived and replaced automatically. ShopNow runs Bottlerocket, a minimal container OS with a read-only root filesystem and image-based updates. When AWS publishes a new AMI, Karpenter sees that running nodes no longer match the EC2NodeClass and marks them drifted, then replaces them gradually within the NodePool's disruption budget of 10% and the workloads' PodDisruptionBudgets. Independently, expireAfter caps any node's lifetime at 14 days, so even without a new AMI nothing lives long enough to accumulate drift. Critical kernel CVEs have a 48-hour replacement SLA. Managed node groups achieve the same with rolling node group updates.
Q9L5 · Solution ArchitectConcept
What are the security benefits?
Immutability removes most of what attackers rely on after initial access. Hosts and pods are short-lived, so persistence mechanisms such as implanted binaries or cron jobs disappear on the next replacement, at most 14 days for ShopNow nodes. Read-only filesystems, non-root users, dropped capabilities and shell-less images make it hard to download tools or modify the application, which is why a penetration test that achieved code execution could not persist. Without SSH, there are no long-lived keys to steal. Every running unit maps to a scanned, signed artifact, so a compromise or CVE is quickly scoped by digest. Patching is also faster, shrinking exposure windows.
Q10L5 · Solution ArchitectConcept
How does it help compliance?
It turns compliance evidence into a by-product of delivery. Auditors ask what is running, whether it was approved, whether it was patched and whether anyone changed it. With immutable infrastructure, the answers are records rather than interviews: image digests and AMI IDs from clusters and Auto Scaling groups, signatures and attestations proving each artifact was built by the pipeline and scanned, SBOMs showing base image versions, and pipeline history linking every change to a reviewed commit. Drift detection logs and the absence of SSH show there were no unauthorised changes. For PayGrid, this covers PCI DSS change control, hardening and patching requirements largely by construction.