Containers and the Reproducible Deployment

During a Catalog Service deployment, Baodium’s engineers encountered a problem that many of us have seen before. Some application instances started normally, while others crashed before they could serve a single request. The release record showed the same Git commit across the fleet, so the team initially suspected a problem in the application code.
The on-call engineer compared a healthy instance with one that had failed. The machines were running different Python versions, one had an older system library, and a required environment variable was missing from the failing instance. The source code was identical, but the environments in which it ran were different.
The engineers could have corrected those differences manually. They knew which packages needed updating and which configuration value was missing. But that would leave them depending on every production machine being configured correctly before the next release. A newly provisioned machine might have another library version, and an emergency replacement could introduce a difference nobody had encountered yet.
The team needed a more reliable way to determine what production would run. They began by separating the files and dependencies that belonged to the application from the settings and resources supplied by its environment. That led them to container images, a repeatable build process, and a deployment configuration that could be reviewed and tested alongside the application.
What a Git Revision Does Not Tell Us
A Git commit identifies a particular version of the source tree. It tells us which application files were checked into the repository, but it does not necessarily tell us which Python interpreter will execute them or which native libraries the application will load.
Consider a Python package that depends on a compiled image-processing library. The package may import successfully on a developer’s laptop, where the expected native library is installed. On another machine, the same import can fail because the required library is missing or incompatible.
The application has not changed, yet its startup behavior has. Engineers often describe these differences as environment drift.
The Catalog team listed the inputs needed to start the service and divided them according to who should provide them. Table Table shows the distinction.
The first group can be packaged into a container image. The image contains the application and the user-space files it needs, together with metadata describing how the process should start.
When the platform starts the image, it creates a running container using the runtime settings assigned to that deployment.
There is an important boundary here. A Linux container uses the host’s kernel. It does not bring a separate Linux kernel with it, as a virtual machine normally would. The image can therefore standardize the language runtime and user-space libraries without eliminating differences in kernel behavior, CPU architecture, mounted files, or resource enforcement.
That distinction helped the Baodium engineers. If two instances used the same image for the same platform, they could focus their comparison on deployment configuration, external dependencies, and host conditions instead of repeatedly checking whether someone had installed a different Python package.
Building the Application Image
The Catalog team moved dependency installation into its continuous integration (CI) pipeline. Each release would produce one image containing the tested application and its declared dependencies.
Production machines would pull that artifact rather than install packages independently during deployment.
Listing Listing shows the simplified Dockerfile.
# CI supplies a base image reference pinned by digest.
ARG PYTHON_BASE_IMAGE
FROM ${PYTHON_BASE_IMAGE}
WORKDIR /app
ENV PYTHONDONTWRITEBYTECODE=1
ENV PYTHONUNBUFFERED=1
COPY requirements.lock .
RUN python -m pip install \
--no-cache-dir \
--require-hashes \
-r requirements.lock
COPY catalog_service ./catalog_service
USER 65532:65532
CMD ["python", "-m", "catalog_service"]The base image supplies the Python runtime. CI passes an approved image reference that includes a digest, so the build does not silently switch to a newer base when someone republishes a tag.
The dependency lock file specifies the packages the application needs, including transitive dependencies. With --require-hashes, pip verifies the distribution files against recorded hashes. This requires a complete set of pinned dependencies and hashes for the distributions the build may use.
Those controls reduce the number of inputs that can change between builds. They do not automatically make every build byte-for-byte reproducible. Build tools, generated files, timestamps, and platform differences can still affect the result. The release process therefore records the actual image it produced and tests that artifact.
The Dockerfile copies the application directory explicitly rather than copying the entire developer workspace. A .dockerignore file also excludes files that should not enter the build context, such as credentials, local environments, and test output.
Catalog Service runs as a non-root user. The build must therefore make its application files readable by that user and provide writable locations for anything the process needs to create.
The final line uses the executable form of CMD, which starts Python without an intervening shell. That matters during shutdown because Kubernetes sends a termination signal to the container’s main process.
There is still something to verify. When Python runs as process ID 1 inside a Linux PID namespace, its default handling of termination signals may not provide the shutdown behavior the application needs. The service must implement the required signal handling or run under a suitable init process, such as tini. Using the executable form avoids an unnecessary shell, but it does not replace a tested shutdown procedure.
The team’s CI checks therefore ran against the built image. They verified startup, file permissions, native dependencies, configuration handling, and termination. Unit tests executed directly on the CI machine would not have covered all those conditions.
Keeping Build Inputs Current
Pinning dependencies makes a build predictable, but it also means that updates require deliberate action.
Suppose a security fix becomes available for the Python base image. Catalog Service will not receive that fix merely because the base-image publisher has released a patched version. Images already built from the older base continue using their existing contents.
The team needed to update the approved base reference, rebuild Catalog Service, run its checks, and deploy the new artifact. Application dependencies followed the same process.
Tools such as Dependabot and Renovate can open pull requests when pinned dependencies need updating. The important part of that workflow is that dependency changes are reviewed and tested as ordinary application changes.
Some packages need compilers or other build tools during installation. Those tools may be unnecessary once the application starts. A multi-stage Docker build can perform compilation in one stage and copy only the required runtime files into the final image.
This reduces the size and contents of the deployed artifact. It also gives the team fewer packages to maintain in production, although it does not replace dependency scanning or runtime security controls.
The release record includes the source revision, image digest, dependency inventory, and build provenance. A digest identifies an artifact, while provenance records information about how that artifact was produced.
The team could sign the artifact using a tool such as Sigstore’s cosign and configure deployment admission to verify the signature and approved provenance. Signing becomes useful as an enforcement control only when the platform checks those properties against a trusted policy.
Promoting the Same Artifact Between Environments
Once the pipeline produced a tested image, the next question was how to move it into production.
One approach would rebuild Catalog Service for staging and again for production. Both builds might use the same Git revision, but they could still differ if a base image, build tool, or dependency changed between them.
Baodium instead built the application once and promoted the recorded artifact through its environments.
Figure Figure compares the two approaches.
Container registries let engineers refer to images using tags or digests.
A tag such as catalog-service:release-42 is convenient for people reading the release history. Depending on the registry policy, however, the tag can be moved to another image.
A digest identifies the referenced image manifest or index by its content. Deploying an approved digest prevents the registry from silently substituting different content under the same reference.
The release pipeline recorded that digest and used it through testing, staging, and production. A rollback could then refer to an earlier approved artifact without rebuilding it.
A multi-platform image introduces another detail. One image index may reference separate platform-specific manifests for x86 and ARM. Two hosts using the same index digest can therefore run different platform-specific images.
If the fleet supports several architectures, the team must test each required platform and record which image each instance actually runs. Registry retention is also part of the rollback plan, since an earlier digest is useful only while its referenced content remains available.
Configuration That Does Not Belong in the Image
The application image was now consistent, but Baodium still had the missing environment variable from the original incident to address.
Database endpoints, Redis connections, feature settings, credentials, and resource allocations can differ between environments. Baking those values into the image would require separate builds or expose environment-specific information wherever the artifact was copied.
The Catalog team kept deployment configuration separate and versioned it alongside the release manifest. Each deployment therefore identified both the application image and the configuration revision used to start it.
The application also needed to reject invalid settings before declaring itself ready.
def load_config(env):
required = ("DATABASE_URL", "REDIS_URL")
missing = [name for name in required if not env.get(name)]
if missing:
raise ConfigError(
"Missing required configuration: "
+ ", ".join(missing)
)
try:
pool_size = int(env.get("DB_POOL_SIZE", "18"))
except ValueError:
raise ConfigError("DB_POOL_SIZE must be an integer")
if not 1 <= pool_size <= 40:
raise ConfigError(
"DB_POOL_SIZE is outside the approved range"
)
return Config(
database_url=env["DATABASE_URL"],
redis_url=env["REDIS_URL"],
pool_size=pool_size,
)This check catches missing values, malformed pool sizes, and settings outside the application’s permitted range. The configured range is only a validation boundary. The actual pool size must still come from a tested fleet-wide database allocation, as Chapter 2 explained.
The error identifies the invalid setting without printing its value. That matters because database connection strings may contain credentials.
Configuration errors also need to be distinguished from dependency failures. Retrying startup cannot fix a missing environment variable. A temporarily unavailable database is different. Depending on the service’s requirements, the application may start and report itself unready, or retry initial connection setup for a bounded period.
In either case, the startup procedure must not hide a permanent configuration error behind repeated connection attempts.
Packaging Kubernetes Configuration With Helm
The Kubernetes deployment required several related manifests. The team used Helm to keep the shared structure in templates and supply environment-specific settings through values files.
For Catalog Service, the production values included the image reference, replica count, database-pool size, and resource settings.
image:
repository: registry.baodium.internal/catalog-service
digest: "sha256:REPLACED_BY_CI"
replicaCount: 12
config:
dbPoolSize: "18"
resources:
requests:
cpu: 500m
memory: 768Mi
ephemeral-storage: 256Mi
limits:
cpu: "1"
memory: 768Mi
ephemeral-storage: 1GiThe digest is a placeholder that the release pipeline must replace with a valid approved digest. The chart must reject the placeholder rather than deploying it unchanged.
The pool size also needs explanation. Suppose the database team allocates 300 sessions to Catalog Service. Twelve replicas with 18 connections each could open 216 sessions. During a rolling deployment with one additional active replica, that would increase to 234.
This leaves some of the 300-session allocation for terminating processes, recovery, and unexpected overlap. Whether 18 connections per instance is enough for the application still requires a load test.
A rolling-update setting of one surge replica does not guarantee that the total number of processes consuming resources is limited to thirteen. Terminating Pods may continue using connections while new Pods begin running. The budget must account for that overlap and for any other processes using the same database allocation.
The Deployment template references the approved image and includes an annotation derived from the rendered ConfigMap.
{{- $config := include (print $.Template.BasePath "/configmap.yaml") . }}
apiVersion: apps/v1
kind: Deployment
metadata:
name: catalog
spec:
replicas: {{ .Values.replicaCount }}
selector:
matchLabels:
app: catalog
template:
metadata:
labels:
app: catalog
annotations:
checksum/config: {{ $config | sha256sum | quote }}
spec:
containers:
- name: catalog
image: "{{ .Values.image.repository }}@{{ .Values.image.digest }}"
resources:
{{- toYaml .Values.resources | nindent 12 }}The example is a template excerpt, so the complete chart still needs its environment variables, ports, probes, security settings, and any required volumes.
The checksum annotation solves a common configuration problem. A Kubernetes ConfigMap can change without restarting a process that reads its values through environment variables. Those values are established when the container starts.
Because the annotation is part of the Pod template, a changed rendered ConfigMap produces a different template and triggers a rolling update.
This mechanism covers the rendered configuration included in the checksum. Secret changes and settings delivered through other mechanisms need their own reload or restart policy.
Before deploying, the team rendered the chart with helm template to inspect the manifests that Kubernetes would receive. A tool such as the helm-diff plugin could then show differences from the existing release.
Kustomize provides another way to manage Kubernetes configuration, using patches rather than Helm templates. The important requirement is that the reviewed configuration matches what the deployment platform will apply.
A GitOps controller such as Argo CD or Flux can reconcile the cluster against that approved configuration and report unexpected differences. Chapter 10 examines how those changes are introduced gradually.
Secrets and Credential Rotation
Credentials require additional care because a container image can be copied, cached, and retained in several places after it has been built.
The team kept secrets out of image layers, source files, build arguments, and diagnostic output. Secret values were delivered through the platform’s approved secret mechanism rather than embedded in the application artifact.
When a build needed a credential to download a private dependency, Docker BuildKit could mount it temporarily for that build step.
RUN --mount=type=secret,id=package_token \
install-private-dependencyThe command is illustrative. The build system must provide the secret mount and use a real installation command.
A secret copied into an image layer is not removed merely because a later layer deletes the file. The earlier layer can remain available through the image history or registry.
If a credential is exposed that way, rebuilding the image is insufficient. The credential must be rotated, and the team must investigate copies in registries, build caches, and other locations where the artifact was stored.
Runtime rotation needs its own procedure. A mounted secret file may be updated without the application rereading it. An environment variable does not change inside an existing process when its Deployment definition changes.
For every secret, the Catalog team documented whether the application supported a validated reload or required a restart. Instances reported the configuration revision they were using without exposing secret contents.
Container Isolation and Writable State
A container image determines the application files, but the runtime determines which resources and operating-system features the process may access.
On Linux, containers commonly use namespaces to separate views of process IDs, mounts, and networking. Control groups, or cgroups, account for resources and enforce limits such as CPU and memory consumption.
Those mechanisms provide useful isolation, although the actual boundary depends on runtime configuration. A privileged container or a sensitive host mount can expose resources that the application image itself does not contain.
The Catalog team ran the process as a non-root user, removed unnecessary Linux capabilities, and configured a read-only root filesystem.
securityContext:
runAsNonRoot: true
runAsUser: 65532
readOnlyRootFilesystem: true
allowPrivilegeEscalation: false
capabilities:
drop: ["ALL"]Those settings were tested against the built image. Any code path that attempted to write into the read-only application filesystem failed during testing rather than appearing unexpectedly in production.
Catalog Service still needed temporary writable storage, including a location such as /tmp. Kubernetes could mount a separately limited temporary volume for that purpose.
The team also reviewed which files needed to survive a container replacement. Customer records belonged in durable external storage. Generated reports intended for later download needed object storage or another durable location.
A temporary cache could be rebuilt, provided its refill path used the source admission controls from Chapter 5.
The same distinction applied to temporary files. Downloads, logs, and intermediate results could fill ephemeral storage even while CPU and memory usage looked normal. Kubernetes resource settings can limit ephemeral-storage consumption, and the kubelet may evict Pods when their usage exceeds the applicable limits or node storage pressure requires it.
CPU and Memory Limits
The new image removed differences in application dependencies, but the service could still behave differently when deployed with different resource settings.
Kubernetes uses resource requests to help the scheduler decide where Pods can be placed. A request is part of the scheduling and resource-allocation model. It is not a guarantee that the requested CPU will be available without contention at every moment.
A resource limit constrains what the container may consume. CPU and memory limits have different failure behavior.
Figure Figure illustrates the distinction.
Catalog Service used the following illustrative configuration.
resources:
requests:
cpu: "500m"
memory: "768Mi"
ephemeral-storage: "256Mi"
limits:
cpu: "1"
memory: "768Mi"
ephemeral-storage: "1Gi"The CPU request is half a core, while the limit allows the equivalent of one core of CPU time. Memory has the same request and limit in this example.
That does not make the Pod a Guaranteed quality-of-service Pod, since the CPU request and limit differ. Kubernetes considers the resource settings of all containers when assigning the Pod’s quality-of-service class.
The values must be tested under production-like traffic. Copying limits from another service could produce latency or restarts that resemble application defects.
CPU Throttling
Consider a Catalog Service instance running with a one-CPU limit. Under a common Linux CFS quota configuration, the container receives 100 milliseconds of CPU time during each 100-millisecond scheduling period.
Now suppose eight application threads become runnable at once, and the host has enough cores for them to execute concurrently.
Together, they can consume the container’s 100-millisecond CPU allowance in approximately 12.5 milliseconds. The container can then be throttled for the remaining portion of the period, even though the individual threads have more processing to complete.
The exact behavior depends on the kernel and runtime configuration, but the consequence is important. Requests can become slower because the container has exhausted its CPU allowance, even when the host’s overall CPU utilization appears relatively low.
The team compared throttled periods, CPU usage, CPU time per request, and the configured quota. A high throttling rate alongside increased request latency suggested the quota needed attention.
However, an increase in CPU time per request could also indicate a code change that made each request more expensive. Raising the limit would conceal that regression without explaining it.
Worker configuration introduces another trap. Some applications choose their worker count from the CPUs visible on the host. A Python application using os.cpu_count() may see more logical CPUs than its cgroup quota allows it to use.
Starting a worker for every visible CPU can therefore create more runnable threads or processes than the container’s allocation can support efficiently.
Catalog Service configured its worker count against tested concurrency and available CPU rather than assuming the host’s logical CPU count described its runtime budget.
Memory Exhaustion
Memory limits require a different investigation.
The process uses memory for more than its application objects. Native libraries, thread stacks, network buffers, runtime metadata, and memory-backed temporary files contribute to its consumption.
A runtime heap configured to use nearly the entire container limit may leave insufficient room for those other allocations. For Java applications, settings such as the JVM’s MaxRAMPercentage help manage the relationship between heap size and container memory.
The Catalog team tested memory under peak concurrency, unusually large responses, and sustained traffic. They needed to know both the maximum observed consumption and whether memory was released after demand decreased.
When a container terminates with exit code 137, it has received SIGKILL. That exit code alone does not establish why it was killed.
Kubernetes may report OOMKilled when the container exceeds its memory limit. A node can also experience memory pressure, and an operator or another process can send a kill signal.
The engineers therefore examined the termination reason alongside memory measurements, resource limits, node events, and restart timing.
If legitimate traffic required more memory, the team could increase the allocation and repeat its load test. If memory consumption continued increasing without returning to its previous level, the next investigation was whether the application retained objects that should have been released.
Finding Containers Under Resource Pressure
During an incident, Kubernetes can show which containers were terminated and why.
The following command lists containers whose most recent recorded termination was an out-of-memory kill.
kubectl get pods -A -o json | jq -r '
.items[] | . as $pod
| .status.containerStatuses[]?
| select(.lastState.terminated.reason == "OOMKilled")
| . as $cs
| ($pod.spec.containers[]
| select(.name == $cs.name)
| .resources.limits.memory // "none") as $limit
| [$pod.metadata.namespace, $pod.metadata.name,
$cs.name, $limit, ($cs.restartCount | tostring),
$cs.lastState.terminated.finishedAt]
| @tsv'This gives the engineer a focused list of containers to investigate. It reports the last recorded termination for each container, so it is useful for recent incidents but cannot replace retained metrics or historical events.
For longer-term analysis, the team used container memory and CPU-throttling metrics.
# Working set above 90 percent of the memory limit
max by (namespace, pod, container) (
container_memory_working_set_bytes{container!=""}
)
/
max by (namespace, pod, container) (
kube_pod_container_resource_limits{resource="memory",unit="byte"}
)
> 0.9
# Throttled CPU periods above 25 percent
sum by (namespace, pod, container) (
rate(container_cpu_cfs_throttled_periods_total[5m])
)
/
sum by (namespace, pod, container) (
rate(container_cpu_cfs_periods_total[5m])
)
> 0.25
These are investigative thresholds rather than universal alert rules. The available metric names and labels depend on the versions and configuration of cAdvisor, kube-state-metrics, and the metrics pipeline.
The memory working set is a useful operational signal, but it is not an exact prediction of the kernel’s out-of-memory decision. The team also checked total cgroup memory consumption, termination events, and node pressure.
CPU throttling requires similar context. A high fraction of throttled periods may matter little when requests still complete within their objectives. It becomes more concerning when latency rises or throughput falls under the same request mix.
Resource recommendations can help during routine reviews. If the Vertical Pod Autoscaler (VPA) is installed, it can operate in recommendation-only mode.
apiVersion: autoscaling.k8s.io/v1
kind: VerticalPodAutoscaler
metadata:
name: catalog
spec:
targetRef:
apiVersion: apps/v1
kind: Deployment
name: catalog
updatePolicy:
updateMode: "Off"With updateMode set to "Off", the VPA publishes recommendations without modifying the running workload.
The engineers could review those values alongside peak tests and application requirements before changing the Helm chart.
A recommendation based on a memory leak could simply recommend more memory for the leaking application. The team also needed to coordinate VPA settings with any Horizontal Pod Autoscaler using the same resource signals, since changing resource requests can affect utilization-based horizontal scaling.
Scheduling Pods Across Nodes and Zones
Once the application image and its resource settings were defined, Kubernetes still had to decide where to run each Pod.
That placement mattered to Baodium because the service had to continue operating after a node or availability-zone failure.
The scheduler considers resource requests, node availability, and constraints supplied by the workload. Without an explicit placement policy, the resulting distribution may be unsuitable for the service’s failure requirements.
The Catalog team wanted replicas spread across availability zones and scheduled on nodes that supported the approved CPU architecture.
spec:
topologySpreadConstraints:
- maxSkew: 1
topologyKey: topology.kubernetes.io/zone
whenUnsatisfiable: DoNotSchedule
labelSelector:
matchLabels:
app: catalog
nodeSelector:
kubernetes.io/arch: amd64
tolerations:
- key: dedicated
operator: Equal
value: catalog
effect: NoSchedule
affinity:
nodeAffinity:
requiredDuringSchedulingIgnoredDuringExecution:
nodeSelectorTerms:
- matchExpressions:
- key: pool
operator: In
values: ["catalog"]The topology-spread constraint limits the difference in matching Pod counts across eligible zones during scheduling.
With DoNotSchedule, Kubernetes leaves a new Pod pending when placing it would violate the constraint. That can protect the planned distribution, but it can also prevent a deployment from completing if eligible capacity is unavailable in the required zones.
The constraint applies to scheduling decisions. It does not automatically redistribute running Pods after a zone fails or existing Pods are removed. The team still needed to test zone loss and recovery.
The node selector restricts this example to amd64 nodes. If the service later supports ARM, the release pipeline needs to build and test the corresponding platform image before relaxing that restriction.
The remaining settings select a dedicated node pool.
A taint prevents Pods without a matching toleration from being scheduled on a node. The toleration permits Catalog Service to use those nodes. Required node affinity then restricts Catalog Service to nodes labeled pool=catalog.
Both settings are needed for the intended placement policy. A toleration alone does not force a Pod onto a particular node pool, and it does not prevent another workload with the same toleration from using that pool.
The following commands illustrate how an operator could label and taint an approved node.
kubectl label node node-7 pool=catalog
kubectl taint node node-7 dedicated=catalog:NoScheduleThe same approach can be used for workloads that require GPUs, local storage, or other specialized hardware.
Planned Node Maintenance
Node maintenance introduces another capacity question. An operator may need to drain a node before updating its operating system or replacing the machine.
If several Catalog Pods are removed at once, the remaining instances must still handle customer traffic.
Kubernetes supports a PodDisruptionBudget (PDB), which limits the voluntary disruptions admitted through the Eviction API.
apiVersion: policy/v1
kind: PodDisruptionBudget
metadata:
name: catalog
spec:
minAvailable: 10
selector:
matchLabels:
app: catalogWith twelve healthy replicas, the policy normally permits voluntary evictions while at least ten remain available.
A command such as kubectl drain uses the Eviction API and respects that budget. If too few healthy replicas are available, the drain may have to wait.
The budget cannot prevent an unexpected node failure or a container crash. Ordinary Deployment rolling updates also follow their own rollout strategy rather than being constrained by the PDB in the same way as eviction requests.
The team therefore kept separate tests for planned maintenance, deployment, and involuntary failure.
Startup, Readiness, and Liveness
A process can start successfully before it is capable of serving customer traffic.
Catalog Service needed valid configuration and completed local initialization before accepting requests. It did not need every optional Redis entry populated, since the cache-miss path already had source admission controls.
Kubernetes provides three kinds of probes for managing the lifecycle.
When a startup probe is configured, Kubernetes does not run the liveness or readiness probes until startup has succeeded.
That gives an application time to initialize without being restarted merely because startup takes longer than a normal health check.
Readiness is evaluated throughout the container’s lifetime. It allows an instance to stop receiving new service traffic when the instance itself cannot serve requests.
Liveness has a different consequence. If the probe repeatedly fails, Kubernetes restarts the container. That is appropriate when a restart can resolve the condition, such as certain deadlocks or unrecoverable local failures.
It becomes dangerous when the probe depends on a service shared by the entire fleet.
The Catalog team avoided putting a database query in its liveness probe.
A PostgreSQL outage should not cause every Catalog container to restart. The database would still be unavailable, while the restarting applications would add initialization work, connection setup, and possibly cache refilling to an already overloaded environment.
The liveness check therefore focused on local conditions for which restarting the process was a useful recovery action.
The engineers also kept probe execution inexpensive. A health check that performs substantial database work can become another source of traffic during an outage.
Warming New Instances Without Overloading Dependencies
Passing readiness does not guarantee that a new instance has reached its normal performance.
Its local caches may be empty, its database pool may have only a few established connections, and some runtime initialization may still occur during its first requests.
As soon as the instance becomes ready, the serving layer may assign it a full share of customer traffic.
That can produce higher latency for new instances than for those that have been running for hours.
Where the serving infrastructure supports it, a slow-start policy can increase the traffic assigned to a new instance gradually. For example, suitable load balancer or proxy configurations can ramp up traffic while the process establishes connections and populates local caches.
Warm-up itself needs admission limits. Opening an entire database pool on every new Pod during a rollout could create a connection burst even before customer traffic increased.
The team measured the initial connection demand and allowed pool growth within the service’s database allocation. A shared Redis cache did not need to be repopulated when one Catalog instance restarted, but local in-process entries would begin empty.
The deployment strategy also controlled how many replacements could begin together.
strategy:
type: RollingUpdate
rollingUpdate:
maxSurge: 1
maxUnavailable: 0This configuration permits one additional non-terminating replica during the rolling replacement and requests no planned reduction in available replicas.
However, an old Pod can continue consuming CPU, memory, and database connections while it terminates. Kubernetes can therefore have more running or terminating Pods consuming resources than the desired replica count plus maxSurge.
That matters to the database-pool calculation earlier in the chapter. The team needed to measure the actual overlap during deployment, including connection cleanup and the time required for old instances to exit.
If the scheduler could not find capacity for the new Pod, the rollout might pause. That was preferable to forcing the new instance onto a node without the resources it needed.
Chapter 10 examines canary exposure and the release decisions built on these deployment mechanics.
Graceful Shutdown and In-Flight Requests
When Kubernetes replaces a Catalog instance, that instance may still be processing customer requests.
Stopping it immediately can interrupt those requests, drop open connections, and leave callers uncertain about whether an operation completed.
The service therefore needed a shutdown procedure that stopped new admission, allowed accepted requests to finish within a bounded interval, released resources, and exited.
This is called graceful shutdown.
The difficulty is that traffic does not stop reaching an instance at exactly the moment its termination begins. Endpoint updates must propagate through the cluster and through whatever proxies and load balancers are serving clients. Existing connections can also carry requests during that interval.
Kubernetes starts the Pod termination grace period when termination begins. If the Pod has a preStop hook, the kubelet ordinarily runs that hook before sending the container its termination signal.
A short pause can allow endpoint removal to propagate before application shutdown begins.
terminationGracePeriodSeconds: 30
containers:
- name: catalog
lifecycle:
preStop:
exec:
command: ["sleep", "5"]This example assumes the image contains a sleep executable. The hook and application shutdown must fit within the termination grace period.
The five-second pause is not a universal value. The team measured endpoint propagation and in-flight request duration under the serving infrastructure it actually used.
The process also had to handle the termination signal and stop admitting new work. Without correct signal handling, the platform could wait until the grace period expired and then forcibly kill the process.
A request that cannot finish before shutdown needs a result appropriate to its operation.
A read may fail and be retried under the caller’s normal policy. A payment or reservation may already have committed an external effect and require the durable reconciliation procedure from Chapter 3.
A longer grace period may allow more requests to finish, but it also extends the interval during which old and new instances consume resources together.
Baodium’s deployment tests therefore replaced instances while sending representative traffic. The engineers measured failed requests, accepted operations left unfinished, released connections, and the time each process required to exit.
Rollback and Compatibility With External State
Promoting an image by digest gave the team a reliable reference for rollback. It did not guarantee that the old image could still run correctly after a new release changed the database or external configuration.
Suppose a deployment removes a database column that the previous version still queries. Rolling back the image would restore the old application code, but its first database request could now fail.
Event schemas, configuration formats, and secret rotation can introduce similar compatibility problems.
The Catalog team tested the previous approved image against the database and configuration state it would encounter after a release.
Chapter 10 develops the expand-then-contract approach for schema changes, where applications and database structures evolve through compatible stages.
An image rollback also cannot reverse a payment, shipment, or other external business action that has already completed. Such effects still require the reconciliation and compensation rules from Chapter 3.
Investigating Deployment Differences
The original Catalog incident took longer to investigate because the release record named only the Git commit. The engineers knew the source revision was the same, but had to compare the other runtime inputs manually.
After changing the release process, each deployment recorded its source revision, image digest, configuration revision, resource settings, and platform-specific artifact.
An instance’s startup and deployment records also identified the node where it ran and the failures reported during initialization.
With that information, engineers could compare healthy and failing instances without immediately changing the application or restarting the fleet.
Listing Listing shows read-only checks for a Catalog Deployment. The commands assume the appropriate namespace is selected through the variable NS.
NS=catalog-prod
# Which images are the running containers using?
kubectl -n "$NS" get pods -l app=catalog \
-o jsonpath='{range .items[*]}{.metadata.name}{"\t"}{range .status.containerStatuses[*]}{.name}{"="}{.imageID}{" "}{end}{"\n"}{end}'
# Has the Deployment completed its rollout?
kubectl -n "$NS" rollout status deploy/catalog --watch=false
# Which ReplicaSets still have desired or ready replicas?
kubectl -n "$NS" get rs -l app=catalog \
-o custom-columns=NAME:.metadata.name,\
DESIRED:.spec.replicas,READY:.status.readyReplicas
# Which configuration revisions are running?
kubectl -n "$NS" get pods -l app=catalog \
-o custom-columns=POD:.metadata.name,\
CONFIG:.metadata.annotations.checksum/config
# Are failed instances concentrated on one node?
kubectl -n "$NS" get pods -l app=catalog -o wide
# Inspect termination state and Kubernetes events.
kubectl -n "$NS" describe pod "$POD"The first check compares the actual container image IDs. A Deployment may refer to a tag, while its running containers have resolved that reference to an image.
If the rollout is incomplete, the fleet may intentionally contain different image versions while old and new replicas overlap. That is different from an instance unexpectedly running an unapproved artifact.
The configuration comparison uses the checksum annotation introduced in the Helm template. If two Pods use the same image but have different configuration checksums, the team can examine the corresponding rendered configuration before investigating the application code.
When image and configuration references agree but failures are concentrated on one node, the investigation turns toward that node’s kernel, container runtime, storage, networking, and resource conditions.
Matching image digests narrow the investigation. They do not establish that the host environment or external dependencies are healthy.
The team also kept secrets out of its diagnostics. Configuration could be compared by revision, presence, and approved non-secret fields without dumping entire environments into logs.
The investigation that originally required several manual host comparisons could now begin with a much smaller set of possible differences.
Summary
Baodium’s Catalog deployment failed even though every instance reported the same source revision. The engineers eventually found different language runtimes, system libraries, and configuration values across the machines. Rebuilding the application as a container image and promoting that image by digest removed much of that variation.
The deployment still depended on settings and conditions outside the image. Kubernetes controlled where the process ran, which resources it could consume, when it received traffic, and how it stopped. The team needed to test those conditions with the same care as the packaged application.
The next incident involving two otherwise identical Pods could begin with a comparison of their image digests, configuration revisions, resource limits, and hosts. That gave engineers useful evidence before deciding whether to roll back, replace a node, or change the application.
The Catalog team had also reduced its source traffic through caching, but the remaining database demand still required a scaling plan. In Chapter 7, we will examine what happens when additional database copies are introduced and customers begin reading from replicas that may contain different versions of the same record.
After this chapter
⌘/Ctrl K to search