Containers and Kubernetes · Intermediate · 17 min
Keep Snip healthy with probes and graceful shutdown
By Padding · Updated 18 Nov 2026
Ubuntu 26.04 · Kubernetes 1.37 · Kustomize 5.8.3 · kubeconform 0.8.0
You will give the Snip Deployment startup, readiness and liveness probes with timings you can explain, a preStop pause and a grace period that let in-flight requests finish during a rollout, and watch readiness take a pod out of service when PostgreSQL stops while liveness leaves it running.
On this page
Kubernetes cannot see inside Snip. It knows a container is running, but not whether the process is stuck, still starting, or unable to reach its database. Probes are how you tell it. Each probe is a small HTTP request the kubelet makes on a timer, and each one answers a different question:
- The startup probe asks "has the process finished starting?" Until it passes, the other two probes are not run.
- The readiness probe asks "should this pod get traffic right now?" A failing pod stays running but is taken out of the Service.
- The liveness probe asks "is the process alive, or should it be restarted?" A failing pod is killed and started again.
Part 1 gave Snip the two endpoints these probes need. /healthz returns ok as long as the process can answer HTTP and checks nothing else. /readyz pings the store with a two-second timeout and returns 503 when PostgreSQL is unreachable or when Snip is shutting down. Part 1 also made Snip stop accepting connections on SIGTERM and give requests already in flight up to 20 seconds to finish.
In this part you wire the endpoints to the Deployment, set the timings on purpose, add a short pause before shutdown so a rollout drops no requests, and check every manifest against the Kubernetes 1.37 schemas before it reaches the cluster. It is part 4 of Ship a Go API to Kubernetes.
Step 1 · Check the starting point
Every change in this part goes into the base, so both overlays pick it up. Before you change anything, render the dev overlay and validate it. kubeconform -strict checks each object against the published JSON schema for Kubernetes 1.37.3 and also rejects any field the schema does not know, which is how it catches a misspelt probe setting before it reaches the cluster:
cd ~/snip-demo/k8s
kustomize build overlays/dev | kubeconform -strict -summary -kubernetes-version 1.37.3kubeconform downloads the schemas it needs from GitHub the first time, so the first run takes a few seconds longer. On a metered or prepaid connection that is a few hundred kilobytes per run; add -cache ~/.cache/kubeconform (create the folder first) to keep them between runs.
Check it worked
The last line reads something like Summary: 6 resources found parsing stdin - Valid: 6, Invalid: 0, Errors: 0, Skipped: 0: part 2's four objects plus the StatefulSet and Service from part 3. If the count differs, check what you added; what matters is Invalid: 0 and Errors: 0. Look at the container section of the rendered Deployment as well:
kustomize build overlays/dev | grep -c 'Probe:' || trueIt prints 0. Snip has no probes yet, so Kubernetes treats the pod as ready the moment its container starts, whether or not PostgreSQL is reachable.
Step 2 · Add the three probes
Put the probes in a patch file of their own in the base. Keeping them apart from deployment.yaml means one file holds every health setting, and later parts can change them without touching the rest of the Deployment. The patch names the container snip, so Kustomize merges it into that container:
cd ~/snip-demo/k8s/base
cat > probes.yaml <<'YAML'
apiVersion: apps/v1
kind: Deployment
metadata:
name: snip
spec:
template:
spec:
containers:
- name: snip
startupProbe:
httpGet:
path: /healthz
port: http
periodSeconds: 2
failureThreshold: 30
readinessProbe:
httpGet:
path: /readyz
port: http
periodSeconds: 5
timeoutSeconds: 3
failureThreshold: 2
livenessProbe:
httpGet:
path: /healthz
port: http
periodSeconds: 10
timeoutSeconds: 2
failureThreshold: 3
YAML
kustomize edit add patch --path probes.yaml
cd ..port: http refers to the named container port from part 2, so the probes follow the port if you ever change its number. kustomize edit adds the file to the patches: list in base/kustomization.yaml, creating the list if it is not there yet, and may reorder the file's keys as it writes it.
Note which endpoint each probe uses. Readiness uses /readyz, which checks the database. Liveness uses /healthz, which does not. That split is deliberate:
- If PostgreSQL goes away, every Snip pod fails its database check at the same moment. If liveness checked the database, the kubelet would restart every pod, over and over, while the database was down. Restarts fix nothing here: the new process cannot reach PostgreSQL either, and the restarts add load just as the database comes back.
- Readiness failing is the right response. The pods stay running with warm connection pools, they stop receiving traffic they cannot serve, and they rejoin the Service as soon as
/readyzpasses again. - Liveness is for problems only a restart fixes: a deadlock, an exhausted goroutine pool, a process that has stopped answering HTTP at all.
Check it worked
grep -A2 '^patches:' base/kustomization.yaml
kustomize build overlays/dev | grep -E '^ +(startupProbe|readinessProbe|livenessProbe):|path: /(healthz|readyz)'The first command shows patches: followed by - path: probes.yaml. The second lists the three probes, alphabetically as Kustomize writes them (livenessProbe, readinessProbe, startupProbe), each followed by its path: /healthz, /readyz and /healthz.
Step 3 · Work out what the timings mean
Each probe runs every periodSeconds. A single check fails if it gets an error status or no answer within timeoutSeconds (the default is 1 second). The probe only acts after failureThreshold failures in a row, and readiness recovers after successThreshold successes (the default is 1). Multiply the numbers out and you get the behaviour you have chosen:
- Startup: 30 failures × 2 seconds gives Snip up to 60 seconds to start answering
/healthzbefore the kubelet gives up and restarts it. Snip normally answers in well under a second, so the probe passes on its first or second check and liveness takes over straight away. The generous budget is for a slow, busy node, not for Snip. Without a startup probe you would need aninitialDelaySecondson liveness instead, which delays every start by the same fixed amount. - Readiness: 2 failures × 5 seconds means a pod leaves the Service roughly 10 seconds after the database becomes unreachable, and at most about 13 seconds when the last check also waits out its 3-second timeout. It comes back within about 5 seconds of the database returning, because one success is enough.
- Readiness timeout:
/readyzgives its database ping 2 seconds. The probe'stimeoutSeconds: 3is longer than that, so a slow database shows up as a clear503from Snip, not as a probe timeout. - Liveness: 3 failures × 10 seconds means Snip must stop answering
/healthzfor about 30 seconds before it is restarted. One slow garbage-collection pause or a brief CPU throttle (see part 2's CPU request) will not trigger a restart.
Two rules of thumb fall out of the arithmetic. Readiness should react faster than liveness, so a struggling pod is taken out of traffic well before anyone considers killing it. And liveness should be the most forgiving of the three, because a wrong restart costs more than a short wait.
Check it worked
kustomize build overlays/dev | grep -E '^ +(periodSeconds|timeoutSeconds|failureThreshold):'The output lists eight values in the order the probes render: liveness (3, 10, 2), readiness (2, 5, 3), startup (30, 2). The startup probe has no timeoutSeconds line because it uses the 1-second default, so there is no ninth value to look for. Within each probe Kustomize sorts the keys alphabetically, so failureThreshold comes first. Check each against the bullet list above before you go on.
Step 4 · Add a pause before shutdown
During a rollout, Kubernetes deletes old pods. Deleting a pod does two things at the same time: the kubelet starts shutting the container down, and the control plane marks the pod as terminating in the Service's EndpointSlice so that kube-proxy and any gateway stop sending it new requests. The second part is not instant. Every node, and every proxy in front of the cluster, has to see the change, and until it does, new requests can still arrive at the old pod.
If Snip received SIGTERM at once, it would close its listener and those late requests would be refused. A preStop hook runs before SIGTERM is sent, so a short pause there keeps Snip serving normally while the rest of the cluster catches up. Snip's image is distroless and has no shell or sleep binary, so use the kubelet's built-in sleep action (stable since Kubernetes 1.34), not an exec hook.
terminationGracePeriodSeconds is the total time Kubernetes allows for the whole shutdown, and the clock starts when the pod is deleted, so it must cover the pause and the drain together:
- 5 seconds of
preStoppause, while traffic moves away; - then SIGTERM, and up to 20 seconds for Snip to finish requests in flight (the limit set in part 1);
- 25 seconds in total. A grace period of 35 seconds leaves 10 seconds of margin before the kubelet sends SIGKILL.
Add a second patch:
cd ~/snip-demo/k8s/base
cat > shutdown.yaml <<'YAML'
apiVersion: apps/v1
kind: Deployment
metadata:
name: snip
spec:
template:
spec:
terminationGracePeriodSeconds: 35
containers:
- name: snip
lifecycle:
preStop:
sleep:
seconds: 5
YAML
kustomize edit add patch --path shutdown.yaml
cd ..If you ever raise Snip's own drain limit above 20 seconds, raise the grace period with it. The pause does not slow normal requests down; it only makes each old pod take five seconds longer to go away during a rollout or a scale-down.
Check it worked
kustomize build overlays/dev | grep -E -A3 '^ +(lifecycle|terminationGracePeriodSeconds):'You see lifecycle: with preStop:, sleep: and seconds: 5 under it, and terminationGracePeriodSeconds: 35 at the pod level, next to containers:.
Step 5 · Validate both overlays
Render both overlays and validate them with the same strict check. The prod overlay has its own patches for resources and GOMEMLIMIT from part 2; this confirms that the base patches and the prod patches merge into one valid container:
for env in dev prod; do
echo "== $env"
kustomize build "overlays/$env" | kubeconform -strict -summary -kubernetes-version 1.37.3
done
kustomize build overlays/prod | grep -c 'Probe:'To see what -strict protects you from, feed it a copy of the dev output with one field misspelt. The if keeps your shell open either way:
if kustomize build overlays/dev | sed 's/periodSeconds/periodSecond/' | kubeconform -strict -kubernetes-version 1.37.3; then
echo "unexpected: the typo was accepted"; false
else
echo "typo rejected, as expected"
fiCheck it worked
Both summaries end in Invalid: 0, Errors: 0, and the probe count for prod is 3. The typo check prints an error for the Deployment that mentions periodSecond as a property that is not allowed, then typo rejected, as expected. Without -strict, kubeconform reports the same file as valid. kubectl would still refuse the unknown field when you applied it, but only once you had started the deploy, not while you were editing.
Step 6 · Apply the probes and watch the pod become ready
Apply the dev overlay to your kind cluster. The pod template has changed, so the Deployment rolls out a new pod:
kubectl apply -k overlays/dev
kubectl -n snip rollout status deployment/snip --timeout=120s
kubectl -n snip get pods -l app.kubernetes.io/component=apikubectl apply -k uses the copy of Kustomize built into kubectl. It renders the same objects as the standalone kustomize build you validated.
Check it worked
rollout status ends with deployment "snip" successfully rolled out, and the pod shows READY 1/1 with RESTARTS 0. Look at the pod's events:
kubectl -n snip describe pod -l app.kubernetes.io/component=api | grep -E 'Liveness|Readiness|Startup'The Liveness, Readiness and Startup lines show your settings in kubectl's short form, something like http-get http://:http/readyz delay=0s timeout=3s period=5s #success=1 #failure=2. If the pod sits at 0/1, read the Events section in full; the pod debugging tutorial walks through the usual causes.
Step 7 · Stop PostgreSQL and watch readiness react
Now break the database on purpose and watch the two probes disagree. In one terminal, watch the Snip pod:
kubectl -n snip get pods -l app.kubernetes.io/component=api -wIn a second terminal, scale the snip-db StatefulSet from part 3 down to zero. Its data stays on the PersistentVolumeClaim:
kubectl -n snip scale statefulset snip-db --replicas=0Within about 10 seconds the Snip pod's READY column changes from 1/1 to 0/1. Ask the EndpointSlice behind the Snip Service what it now thinks of the pod:
kubectl -n snip get endpointslices -l kubernetes.io/service-name=snip \
-o jsonpath='{range .items[*].endpoints[*]}{.targetRef.name}{" ready="}{.conditions.ready}{"\n"}{end}'The pod is listed with ready=false. Kube-proxy only sends Service traffic to ready endpoints, so requests to http://snip inside the cluster now fail fast instead of reaching a pod that would answer with database errors. Wait a full minute, then bring PostgreSQL back:
kubectl -n snip scale statefulset snip-db --replicas=1
kubectl -n snip rollout status statefulset/snip-db --timeout=120sCheck it worked
While PostgreSQL was down, the watch showed 0/1 but the RESTARTS column stayed at 0: liveness kept passing, because /healthz does not touch the database. kubectl -n snip logs deployment/snip shows repeated readyz: store: lines from that minute. A few seconds after PostgreSQL is back, the pod returns to 1/1 and the EndpointSlice query prints ready=true. Stop the watch with Ctrl+C.
Step 8 · Roll out under load and count failed requests
The last check is the one that matters to users: a rollout should drop nothing. Start a small load pod inside the cluster that calls the Service ten times a second for about 30 seconds and counts the results:
kubectl -n snip run load --image=curlimages/curl:8.23.0 --restart=Never --command -- \
sh -c 'ok=0; fail=0; for i in $(seq 1 300); do if curl -fsS -m 2 -o /dev/null http://snip/links; then ok=$((ok+1)); else fail=$((fail+1)); fi; sleep 0.1; done; echo "ok=$ok fail=$fail"'While it runs, restart the Deployment. This replaces the pod exactly as a new release would:
kubectl -n snip rollout restart deployment/snip
kubectl -n snip rollout status deployment/snip --timeout=120sWith one replica and the default rolling-update settings, Kubernetes starts the new pod first, waits for its readiness probe to pass, and only then deletes the old one. The old pod then sits in its five-second pause while the EndpointSlice change spreads, receives SIGTERM, and finishes whatever it is still handling.
Check it worked
When the load pod finishes, read its result and remove it:
kubectl -n snip wait --for=jsonpath='{.status.phase}'=Succeeded pod/load --timeout=120s
kubectl -n snip logs load
kubectl -n snip delete pod loadThe log line reads ok=300 fail=0, or close to 300 successes with fail=0. On a one-node kind cluster the routing change spreads quickly, so you may also see no failures with the pause removed. On larger clusters, and behind a gateway like the one in part 5, the gap is longer and the pause is what keeps it invisible. Users on slow mobile connections feel this most: a request that has taken several seconds to arrive is exactly the kind that would otherwise be cut off mid-release.
Leave everything running. Part 5 puts the Gateway API in front of this Service, and part 8 uses the readiness probe as a release gate.
Next steps
- When a pod will not become ready, work through /tutorials/debug-a-failing-kubernetes-pod-with-kubectl.
- Revisit how
/healthz,/readyzand the SIGTERM drain are written in /tutorials/package-the-snip-go-api-in-a-distroless-image.
Related tutorials
- Package the Snip Go API in a distroless container imageYou will write Snip, a small Go 1.27 link-shortener API with health and readiness endpoints and a clean drain on SIGTERM, build it as a static binary, package it in a two-stage Dockerfile on a distroless non-root base, and load the image into a kind cluster.
- Debug a failing Kubernetes pod with kubectlYou will break Deployments on a kind cluster in six common ways, read each failure from kubectl get, describe, logs and events, fix it, and finish by opening a shell beside a distroless pod with kubectl debug.
Need this done for you?
Padding does this work for growing companies, from the first diagnosis to a system that keeps working.
Get new tutorials