Production-ready applications: health checks, graceful shutdown, structured logs, and timeouts
A production-readiness checklist from the perspective of the people who write the code: liveness, readiness, and startup probes, graceful shutdown, JSON logs with trace IDs, timeouts, retries with jitter, resources, metrics, and security basics.
Development$ kubectl rollout status deployment/api▍“It works on my machine” and “it works in production” are different things. In production, the application gets restarted without warning, receives traffic before it’s ready, depends on services that slow down, and has to be debugged at 3 a.m. by someone who didn’t write the code. The good news: almost everything that separates a fragile service from a reliable one is in the hands of the developers.
Health checks: liveness, readiness, and startup
Kubernetes periodically asks the application questions through probes. Each one answers a different question, and mixing them up is one of the most common causes of instability:
| Probe | Question | If it fails |
|---|---|---|
startupProbe |
Has the application finished starting? | Until it passes, the other probes wait; if it runs out of attempts, the container is restarted |
livenessProbe |
Is the process stuck beyond repair? | The container is restarted |
readinessProbe |
Can this instance take traffic right now? | The pod is removed from the Service endpoints, without a restart |
apiVersion: apps/v1
kind: Deployment
metadata:
name: api
spec:
replicas: 3
selector:
matchLabels:
app: api
template:
metadata:
labels:
app: api
spec:
terminationGracePeriodSeconds: 30
containers:
- name: api
image: ghcr.io/your-org/api:1.4.2
ports:
- containerPort: 8080
env:
- name: PORT
value: "8080"
resources:
requests:
cpu: 250m
memory: 256Mi
limits:
memory: 256Mi
startupProbe:
httpGet:
path: /healthz
port: 8080
periodSeconds: 5
failureThreshold: 30 # up to 150 s to start
livenessProbe:
httpGet:
path: /healthz
port: 8080
periodSeconds: 10
timeoutSeconds: 2
failureThreshold: 3
readinessProbe:
httpGet:
path: /readyz
port: 8080
periodSeconds: 5
timeoutSeconds: 2
failureThreshold: 2
lifecycle:
preStop:
exec:
command: ["sleep", "5"]
securityContext:
runAsNonRoot: true
runAsUser: 10001
allowPrivilegeEscalation: false
readOnlyRootFilesystem: true
What each endpoint should (and shouldn’t) check
- Liveness should be dumb on purpose: “does the process answer HTTP?”. Never make liveness depend on the database. If the database goes down, every pod fails its liveness probe, Kubernetes restarts all of them at once, and a database problem turns into a restart storm that makes recovery worse.
- Readiness answers whether this instance can serve: it has finished initializing, it isn’t shutting down, it isn’t overloaded. Be careful with shared dependencies: if every replica checks the same database and it goes down, they all leave the load balancer together — sometimes it’s better to return a clear error.
- Startup exists for applications that are slow to start (JVM, cache warm-up) and avoids a huge
initialDelaySecondson the liveness probe.
Graceful shutdown
Every deploy, scale-down, or node replacement terminates pods. The sequence in Kubernetes is: the pod is marked as terminating and starts being removed from the endpoints; the preStop hook runs; the container receives SIGTERM; if it doesn’t exit within terminationGracePeriodSeconds (30 seconds by default, including the time spent in preStop), it receives SIGKILL.
The tricky part: endpoint removal is asynchronous, and ingress controllers and kube-proxy keep sending requests for a few seconds. Hence the preStop trick with sleep 5: delay SIGTERM while the removal propagates. The exec action requires a sleep binary in the image; recent Kubernetes versions offer a native sleep action in preStop — check whether your cluster supports it.
When it receives SIGTERM, the application should: stop accepting new connections, finish in-flight requests, close database and queue connections, and flush pending telemetry. In Go (1.22 or later):
package main
import (
"context"
"errors"
"log/slog"
"net/http"
"os"
"os/signal"
"sync/atomic"
"syscall"
"time"
)
func main() {
logger := slog.New(slog.NewJSONHandler(os.Stdout, nil))
port := os.Getenv("PORT")
if port == "" {
port = "8080"
}
var ready atomic.Bool
mux := http.NewServeMux()
mux.HandleFunc("GET /healthz", func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusOK) // the process is alive and responding
})
mux.HandleFunc("GET /readyz", func(w http.ResponseWriter, r *http.Request) {
if !ready.Load() {
http.Error(w, "not ready", http.StatusServiceUnavailable)
return
}
w.WriteHeader(http.StatusOK)
})
srv := &http.Server{
Addr: ":" + port,
Handler: mux,
ReadHeaderTimeout: 5 * time.Second,
ReadTimeout: 10 * time.Second,
WriteTimeout: 15 * time.Second,
IdleTimeout: 60 * time.Second,
}
// ctx is canceled when SIGTERM (Kubernetes) or SIGINT (Ctrl+C) arrives
ctx, stop := signal.NotifyContext(context.Background(), syscall.SIGTERM, syscall.SIGINT)
defer stop()
go func() {
logger.Info("server started", "addr", srv.Addr)
if err := srv.ListenAndServe(); err != nil && !errors.Is(err, http.ErrServerClosed) {
logger.Error("server failed", "err", err)
os.Exit(1)
}
}()
ready.Store(true)
<-ctx.Done()
stop() // a second signal restores the default behavior and exits immediately
ready.Store(false)
logger.Info("signal received, shutting down")
// stop accepting connections and wait for in-flight requests
shutdownCtx, cancel := context.WithTimeout(context.Background(), 20*time.Second)
defer cancel()
if err := srv.Shutdown(shutdownCtx); err != nil {
logger.Error("incomplete shutdown", "err", err)
}
// here: close the database pool, queue consumers, flush telemetry
logger.Info("stopped")
}
Note that the internal deadline (20 s) plus preStop (5 s) fits within the 30 s of terminationGracePeriodSeconds. In Node.js the idea is the same: process.on('SIGTERM', ...) calling server.close(). One caveat: if the process runs behind a shell script as PID 1, the signal may never reach the application — use exec in the script or the JSON (exec) form of CMD in the Dockerfile.
Structured logs with correlation
In production, the first reader of a log is a machine. Write JSON, one line per event, to standard output, with consistent fields:
{"time":"2026-11-24T23:10:04.512Z","level":"ERROR","msg":"failed to charge order","service":"checkout","trace_id":"4bf92f3577b34da6a3ce929d0e0e4736","span_id":"00f067aa0ba902b7","order_id":"ord-81723","duration_ms":2034,"err":"timeout calling payment gateway"}
The trace_id is what lets you jump from the log to the request’s full trace — the topic of correlating metrics, logs, traces, and profiling. Never log passwords, tokens, or full personal data.
Timeouts, retries, and circuit breakers
Every network call needs a timeout. Without one, a slow dependency ties up threads and connections until it takes down its callers. The HTTP clients of several languages, including Go’s, have no timeout by default.
Retries help with transient failures, but only for idempotent operations and with exponential backoff and jitter — without jitter, a thousand clients retry at the same moment and knock over the service that just came back:
package resilience
import (
"context"
"math/rand/v2"
"time"
)
// WithRetry calls fn up to `attempts` times, with exponential backoff and full jitter.
// Use it only for idempotent operations.
func WithRetry(ctx context.Context, attempts int, base time.Duration, fn func(context.Context) error) error {
var err error
for i := range attempts {
if err = fn(ctx); err == nil {
return nil
}
if i == attempts-1 {
break
}
// random wait between 0 and base * 2^i
wait := time.Duration(rand.Int64N(int64(base << i)))
select {
case <-time.After(wait):
case <-ctx.Done():
return ctx.Err()
}
}
return err
}
A circuit breaker completes the trio: after several consecutive failures, it stops calling the dependency for a while and fails fast, giving it room to recover. To validate all of this for real, inject failures with chaos engineering.
Configuration, resources, and metrics
- Configuration through environment variables, never baked into the image: the same image runs in staging and production. See environment variables and the 12-factor app.
- Requests and limits: the
requestis what the scheduler reserves; exceeding the memorylimitcauses an OOMKill. CPU limits cause throttling, so many teams set only the CPU request. - RED metrics (rate, errors, and duration) per endpoint, ideally instrumented with OpenTelemetry as a single collection layer.
Data and dependencies
- Idempotency: operations that may be repeated (payments, webhooks, queue messages) should accept an idempotency key and produce the same result if they arrive twice.
- Backward-compatible migrations: during a rolling update, the old and new versions run side by side against the same database. Use the expand/contract pattern: first add the new column, then migrate the code, and only then drop the old one.
- Pinned versions: committed lockfiles and base images with a specific tag or digest.
latestin production is a change nobody reviewed.
Security basics
Run as a non-root user, with no privilege escalation and a read-only root filesystem (the securityContext in the example above). No secrets inside the image or in the repository: inject them at runtime from a secrets manager.
The readiness table
| Item | Why | How to verify |
|---|---|---|
| Simple liveness, no dependencies | Avoid cascading restarts | Take the database down in staging and confirm the pods don’t restart |
| Readiness reflects the instance | Pull from traffic only the instances that can’t serve | kubectl get endpointslices during a deploy |
| Startup probe for slow apps | Don’t kill the pod while it’s starting | Measure startup time and compare it with the configured limit |
| SIGTERM handling | Deploys without 5xx errors | Continuous load test during a kubectl rollout restart |
preStop and shutdown deadline |
Wait for endpoint removal | Add up preStop and the internal timeout and compare with terminationGracePeriodSeconds |
JSON logs with trace_id |
Fast investigations | Look up a request by trace ID in your logging tool |
| Timeout on every network call | A slow dependency doesn’t take the service down | Code review and latency injection |
| Retries with backoff and jitter | Avoid retry storms | Read the retry policy of each client |
| Requests and limits defined | Predictable scheduling, no OOMKills | kubectl top pod compared with the configured values |
| RED metrics | Know whether users are hurting | Per-endpoint dashboard with rate, errors, and latency |
| Backward-compatible migrations | Rolling updates without breaking the old version | Run the previous version against the new schema |
| Non-root user, no secrets in the image | Reduce the blast radius of a breach | Image scanner and an admission policy in the cluster |
When these items become platform defaults, every new service is born ready — that’s the promise of golden paths.
Checklist
- Liveness, readiness, and startup with distinct endpoints and purposes
- SIGTERM handled, with consistent
preStopand shutdown deadline - JSON logs to standard output, with
trace_idand no sensitive data - Timeouts on every network call and retries only for idempotent operations
- Configuration through environment variables and requests/limits defined
- RED metrics and traces exported via OpenTelemetry
- Backward-compatible migrations, pinned versions, and a non-root container
Production-ready isn’t when the code works; it’s when it fails, restarts, and gets debugged without drama.