Structuring a Startup Probe
I'm going to provide a "startup probe" that checks initialization. I need to include dependency checks with timeouts and caching to avoid expensive per-probe costs. It's important to also include aspects like concurrency and backpressure.
I'll create a structured answer that covers the goals, endpoint definitions, probe behavior, what to check, intervals, implementation details, graceful shutdown steps, and a Kubernetes config sample. I want to keep everything concise yet informative, using markdown headings and bullet lists. Let's get started on writing this!
Below is a practical, production-oriented health check strategy that cleanly separates startup, readiness, and liveness, uses dependency gates without causing probe flapping or cascading failures, and supports graceful shutdown (especially in Kubernetes).
1) Define semantics first (what each probe means)
Liveness (“should the process be restarted?”)
Purpose: Detect deadlocks, event-loop stalls, unrecoverable internal corruption.
Rule: Do not include external dependencies (DB, brokers, downstream HTTP) in liveness.
Typical checks:
- Main thread/event loop responsive (heartbeat / watchdog)
- Internal state machine not wedged
- Optional: memory limit trip / fatal error state set by the app itself
Failure action: restart container/process.
Readiness (“should this instance receive traffic now?”)
Purpose: Gate traffic when you can’t serve correctly or with required guarantees.
Rule: Include only dependencies/features that are required to serve the traffic routed to this instance.
Typical checks:
- Server is listening
- Critical configs loaded (feature flags, secrets)
- Hard dependencies reachable (DB primary, required topic subscription, cache if mandatory)
- Backpressure / overload gating (queue depth too high, thread pool saturated)
- “Draining” state during shutdown (force NOT ready)
Failure action: remove from load balancer/service endpoints, but keep process running.
Startup (“is the app done initializing?”)
Purpose: Protect slow boots from being killed by liveness and prevent traffic before init completes.
Rule: Covers one-time initialization steps that must complete before readiness even makes sense.
Typical checks:
- DB migrations/validation complete (if done at boot)
- Warm-up caches (if required)
- Model load / JIT / compilation / plugin discovery complete
- Initial connection to required brokers established (if required for serving)
Failure action: if it never succeeds within a budget, restart (or fail deployment).
2) Endpoint design (simple and consistent)
Common pattern:
GET /livez → liveness (fast, no I/O, always cheap)
GET /readyz → readiness (may check dependencies, but bounded and cached)
GET /startupz → startup (initialization state)
Guidelines:
- Fast: target < 50ms for
/livez, < 200ms typical for /readyz (with caching).
- Bounded: every dependency check must have strict timeouts (e.g., 100–300ms).
- No thundering herd: cache dependency-check results for a short TTL (e.g., 1–5s), don’t re-check per probe hit.
- Return codes only: 200 = OK, 503 = not ready/unhealthy. Avoid 500 unless it’s truly an app bug.
- Optional debug: add
?verbose=1 or separate /health/details protected endpoint for humans.
3) Dependency gates (avoid probe flapping and cascades)
Classify dependencies
- Hard dependency (must-have)
- If it’s down, the service cannot fulfill its contract.
- Gate readiness on it.
- Examples: primary DB for writes, required auth provider for token validation, required queue for core workflow.
- Soft dependency (nice-to-have / degrade)
- If it’s down, the service can serve in degraded mode.
- Do not fail readiness; instead:
- emit metrics/alerts
- degrade behavior (fallback cache, partial responses, feature off)
- Examples: recommendation service, optional analytics sink.
- Startup-only dependency
- Must be present at boot, but transient failures later shouldn’t evict instance.
- Gate startup, not readiness (or gate readiness only on “connection established once”).
- Example: one-time schema validation, model download.
Implement dependency checks safely
- Use timeouts and circuit breakers (don’t pile onto failing dependencies).
- Prefer lightweight checks:
- DB:
SELECT 1 on a pooled connection (don’t create new connections per check)
- Broker: verify client state and last successful poll/heartbeat timestamp
- Use hysteresis to reduce flapping:
- declare “not ready” after N consecutive failures (e.g., 3)
- declare “ready” after M consecutive successes (e.g., 2)
- Separate “dependency down” from “overloaded”:
- Overload should generally fail readiness (stop sending more traffic) even if dependencies are fine.
4) Kubernetes probe configuration (recommended baseline)
livenessProbe:
httpGet: { path: /livez, port: 8080 }
periodSeconds: 10
timeoutSeconds: 1
failureThreshold: 3
readinessProbe:
httpGet: { path: /readyz, port: 8080 }
periodSeconds: 5
timeoutSeconds: 1
failureThreshold: 3
startupProbe:
httpGet: { path: /startupz, port: 8080 }
periodSeconds: 5
timeoutSeconds: 1
failureThreshold: 60 # e.g., allow up to ~5 minutes
Notes:
- Use
startupProbe when cold start can be slow; it prevents liveness from killing the pod during initialization.
- Readiness runs continuously; liveness should remain “green” even when dependencies are down (otherwise you amplify outages by restart storms).
5) Graceful shutdown (drain correctly, avoid dropped requests)
Goals
- Stop receiving new traffic quickly.
- Finish (or time-bound) in-flight requests.
- Close resources cleanly.
- Exit before orchestrator hard-kills the process.
Recommended shutdown sequence (SIGTERM)
- Enter draining mode immediately
- Flip an atomic flag:
draining = true
/readyz starts returning 503 (unready)
- Stop accepting new connections
- Close listener / stop accepting
- For HTTP servers, disable keep-alive or stop accepting new streams
- Drain in-flight work
- Wait for active requests to reach zero, with a max timeout
- Stop background consumers (queue subscriptions) or checkpoint offsets safely
- Cleanup
- Flush logs/metrics/traces
- Close DB pools, broker clients
- Exit
- Return exit code 0 (unless fatal)
Kubernetes specifics
- Set
terminationGracePeriodSeconds to match worst-case drain time.
- Optionally add a
preStop hook to give the readiness change time to propagate:
lifecycle:
preStop:
exec:
command: ["sh", "-c", "sleep 5"]
terminationGracePeriodSeconds: 30
The important part is still: on SIGTERM, fail readiness immediately.
6) Common pitfalls to avoid
- Putting DB/downstream checks in liveness → restart storms during dependency outages.
- Expensive readiness checks (new DB connection per probe) → self-inflicted load.
- No timeouts on dependency checks → probes hang, kubelet kills the pod.
- Readiness that never fails under overload → load balancer keeps sending traffic to a saturated instance.
- Graceful shutdown without readiness flip → requests routed to a pod that’s already closing.
7) Minimal decision table (quick reference)
| Probe | Include dependencies? | Typical fail meaning | Orchestrator action |
|---|
| Startup | Only what’s required to finish init | Still booting or stuck init | Restart / fail rollout |
| Readiness | Hard deps + overload gates | Don’t send traffic | Remove from service endpoints |
| Liveness | No external deps; only internal health | Process is wedged | Restart |
If you share your runtime (Java/Spring, Go, Node, .NET), deployment target (Kubernetes/ECS/systemd), and key dependencies (DB/broker/cache), I can give a concrete probe spec + example handler implementation and shutdown wiring for that stack.