ArchitectMind
  1. Home
  2. Java Ecosystem
  3. Book 9 · Cloud, Containers, DevOps & Production Architecture
  4. Volume VII
  5. Immutable Infrastructure
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
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
Covers
Immutable infrastructure
On this page
  1. 1. Concept / Definition
  2. 2. Why It Exists
  3. 3. Core Concepts — Immutable Infrastructure
  4. 4. How It Works Internally — Golden Image Pipeline (ShopNow)
  5. 4A. Deep Dive — Patch Cadence by Replacement
  6. 4B. Deep Dive — Runtime Immutability
  7. 4C. Deep Dive — State with Immutable Compute
  8. 4D. Deep Dive — Debugging Without Mutation
  9. 4E. Deep Dive — Audit and Compliance Benefits
  10. 5. APIs / Features / Syntax
  11. 6. Practical Examples
  12. 7. Common Problems & Mistakes
  13. 8. Performance & Production Considerations
  14. 9. Architecture & Design Considerations
  15. 10. Interview Questions & Answers

1Concept / Definition

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.

Mutable vs immutable infrastructure
Figure 1 — Mutable vs immutable infrastructure
Immutable delivery pipeline
Figure 2 — Immutable delivery pipeline
VocabularyMeaning
Golden imageHardened, pre-baked base image/AMI
DriftDivergence between running state and definition
Instance refreshRolling replacement of instances with a new launch template
Read-only root filesystemContainer cannot modify its own image at runtime
Table 1 — Terms

2Why It Exists

Configuration drift findings (monthly)
Figure 3 — Configuration drift findings (monthly)
Mutable-world problemImmutable answer
"Works on server 3 but not server 7"All instances from the same image
Emergency hotfixes via SSH never recordedNo SSH; change = new artifact
Patch Tuesday breaks productionPatched image tested in staging first
Rollback means un-patchingRedeploy previous image
Attackers persist on long-lived hostsShort-lived, replaced instances
Table 2 — Why

3Core Concepts — Immutable Infrastructure

LayerImmutable unitReplacement mechanism
ApplicationContainer image (by digest)Rolling update / Argo Rollouts
Node OSBottlerocket / EKS-optimised AMIKarpenter drift, managed node group update
VM workloadsGolden AMIASG instance refresh / blue-green
ServerlessLambda version + aliasAlias shift (CodeDeploy)
InfrastructureTerraform module versionsPlan/apply creating replacements
ConfigGit commit (ConfigMaps rendered)Rollout triggered by hash annotation
Table 3 — Units per layer

4How It Works Internally — Golden Image Pipeline (ShopNow)

StageToolingDetail
Base selectionChainguard/UBI minimal JRE, BottlerocketMinimal attack surface
BuildDocker BuildKit / EC2 Image BuilderReproducible, pinned versions
HardenCIS benchmarks, remove shells where possibleDistroless for apps
ScanTrivy/InspectorBlock high/critical
Sign & attestcosign + SBOM + provenanceAdmission verifies
PublishECR / AMI catalog with version tagsImmutable tags
RolloutStaging → prod progressiveAutomatic cadence
RetireDeregister images > 90 days (keep last N)Hygiene
Table 4 — Pipeline

4ADeep Dive — Patch Cadence by Replacement

ComponentCadenceMechanism
Base JRE imagesWeekly rebuild + on critical CVERenovate PRs, CI rebuild of all services
Bottlerocket nodesWeekly AMI releaseKarpenter drift replaces nodes within disruption budgets
Golden AMIs (legacy EC2)Monthly + criticalImage Builder pipeline → instance refresh
Managed servicesProvider-managedMaintenance windows / zero-downtime patching
Table 5 — Patching = replacing

4BDeep Dive — Runtime Immutability

ControlEffect
readOnlyRootFilesystem: trueNo writes to image layers; writable emptyDir only where needed
runAsNonRoot, drop all capabilitiesLimits mutation and escalation
No SSH, no shell in distroless imagesNo interactive changes
Kyverno policies enforcing the aboveGuardrails
Drift detection (Argo CD self-heal)Reverts manual kubectl edits
Table 6 — Enforce immutability at runtime

4CDeep Dive — State with Immutable Compute

StateWhere
DatabasesManaged services (Aurora, DynamoDB) — not on instances
FilesS3 / EFS
CachesRedis (rebuildable)
LogsStreamed off-box
Secrets/configInjected at start (Secrets Manager, ConfigMaps)
Temporary scratchemptyDir, discarded
Table 7 — Compute disposable, data durable

4DDeep Dive — Debugging Without Mutation

NeedImmutable-friendly tool
Inspect a running podkubectl debug ephemeral container (audited, JIT access)
Access an EC2 hostSSM Session Manager (logged), no SSH keys
Collect JFR/heap dumpActuator/jcmd via ephemeral container → encrypted S3
FixNew artifact through pipeline
EmergencyBreak-glass pipeline, not manual edits
Table 8 — Observe freely, change only via artifacts

4EDeep Dive — Audit and Compliance Benefits

Audit questionEvidence
What is running?Image digests / AMI IDs from cluster and ASG
Was it scanned and approved?Attestations on digest
Were patches applied?Base image version in SBOM; node AMI version
Any unauthorised change?No SSH; drift detection logs
Table 9 — Immutable = provable

5APIs / Features / Syntax

YAML
# Pod security context enforcing runtime immutability
securityContext:
  runAsNonRoot: true
  seccompProfile: { type: RuntimeDefault }
containers:
  - name: app
    image: 111122223333.dkr.ecr.ap-south-1.amazonaws.com/checkout@sha256:4be1...
    securityContext:
      readOnlyRootFilesystem: true
      allowPrivilegeEscalation: false
      capabilities: { drop: ["ALL"] }
    volumeMounts: [{ name: tmp, mountPath: /tmp }]
volumes: [{ name: tmp, emptyDir: { sizeLimit: 256Mi } }]
YAML
# Karpenter NodePool: Bottlerocket nodes replaced on drift within a disruption budget
apiVersion: karpenter.sh/v1
kind: NodePool
metadata: { 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 refresh
resource "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

StepDetail
Revert GitOps digestPrevious image restored in minutes
Table 10 — Rollback is redeploy

6.5 Worked example — image tagging

RuleReason
Deploy by digest; tags immutable in ECRNo tag hijacking
Table 11 — Immutable references

6.6 Worked example — node lifetime

SettingValue
expireAfter14 days
Table 12 — Short-lived hosts

6.7 Worked example — interview whiteboard

PromptAnswer 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 controlImmutable evidence
Change control, hardening, patchingPipeline records, AMI versions
Table 14 — Compliance by construction

6.9 Worked example — anti-patterns

Anti-patternEffect
kubectl exec to "quick fix"Drift, unaudited
Mutable "latest" tagsUnknown versions
Long-lived nodesPatch lag, persistence
Config edited in consolesDrift
Table 15 — Common mistakes

6.10 Worked example — config change rollout

MechanismDetail
ConfigMap hash annotation on pod templateConfig change triggers rolling replacement
Table 16 — Config treated immutably

6.11 Worked example — Image Builder for EC2

ComponentContent
RecipeBase AMI + hardening + agents
TestsCIS checks, boot tests
Table 17 — Golden AMI factory

6.12 Worked example — blue-green for VMs

StepDetail
New ASG with new AMI; switch ALB target groupInstant rollback by switching back
Table 18 — Replacement at fleet level

6.13 Worked example — immutable Lambda

MechanismDetail
Publish version; alias shift 10% → 100%Versioned functions
Table 19 — Serverless immutability

6.14 Worked example — reproducible builds

PracticeDetail
Pinned base digests, Maven lockfile/enforcer, SOURCE_DATE_EPOCHSame input → same output
Table 20 — Trustworthy artifacts

6.15 Worked example — cost

ConcernReality
More image buildsCheap vs incidents from drift
Table 21 — Economics favour immutability

6.16 Worked example — interview follow-ups

Follow-upAnswer
"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

StepDetail
Freeze manual changes; golden AMIs; SSM onlyFirst immutable step before containerising
Table 24 — Incremental adoption

6.19 Worked example — image retention

PolicyDetail
Keep last 20 prod digests; expire untagged after 14 daysRollback + hygiene
Table 25 — Lifecycle rules

6.20 Worked example — emergency change

PathDetail
Break-glass pipeline with post-reviewStill immutable
Table 26 — No console hotfixes

6.21 Worked example — interview scenario

QuestionAnswer
"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

SeverityReplace within
Critical kernel CVE48 h
Table 28 — Measurable patching

6.23 Worked example — immutable config for Java

PracticeDetail
No runtime property edits via actuator/env endpointDisabled in prod
Table 29 — Close mutation paths

6.24 Worked example — drift report

SourceOutput
AWS Config + Argo diffWeekly drift report
Table 30 — Measure immutability

6.25 Worked example — immutability maturity

LevelCharacteristic
1Manual changes on long-lived servers
2Golden images, manual deploys
3Pipelines replace instances; SSH restricted
4No 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 changes
configMapGenerator:
  - name: checkout-config
    files: [application.yaml]

^Config changes become new immutable versions

6.27 Worked example — immutable infrastructure and incidents

Incident stepImmutable advantage
"What changed?"Digest/AMI diff answers precisely
RollbackPrevious artifact, minutes
Table 32 — Faster, safer incident response

6.28 Worked example — node replacement budget

SettingEffect
Disruption budget 10% + PDBsSafe continuous replacement
Table 33 — Immutability without outages

7Common Problems & Mistakes

MistakeFix
Manual hotfixesPipeline
Mutable tagsDigests
Long-lived hostsExpiry
State on instancesManaged 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

ConsiderationPractice
Replacement churnDisruption budgets
Image pull timeSmall images, caching
Rollout durationProgressive, 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

GuidelineDetail
Separate compute and dataDisposable compute
Everything versionedTraceability
Enforce with policyGuardrails
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.

Test your knowledge on this topic →Flashcards from this topic's 10 questions, filtered by level and type.

Free question pack

Get 100 free Core Java interview questions

Subscribe for the Book 1 question pack (PDF, every answer explained) and new tutorials once a week. No spam, unsubscribe anytime. What is in the pack?

Almost done! Check your inbox and click the confirmation link. Your download link arrives as soon as you confirm.