In a world where services are spun up and torn down in milliseconds, a single mis‑configured health check can leave a cluster in a split‑brain state, routing stale traffic to a dead pod or, worse, to an uninitialized replica.
When a deployment rolls, the load balancer must stop sending traffic to the old pod before it shuts down, and the pod itself must finish processing in‑flight requests before the container dies.
Combining Kubernetes readiness probes, liveness checks, and graceful shutdown hooks in a Go HTTP server eliminates these pitfalls and delivers truly zero‑downtime deployments.
TL;DR
- Readiness probes let the kube‑proxy know when a pod is ready to receive traffic; they should depend on external dependencies (DB, cache, etc.).
- Liveness probes detect a hung or crashed process; they should be simple, fast, and independent of external services.
- Graceful shutdown is achieved by catching
SIGTERM/SIGINT, canceling acontext, and allowing the HTTP server to finish pending requests. - During a rolling update, set the pod’s readiness to false before the termination signal to drain traffic, then let the graceful shutdown finish.
Why Health Checks Matter in Modern Deployments
- Split‑brain scenarios occur when a pod believes it’s healthy but its dependencies are down. Traffic routed to such a pod can expose stale data or fail silently, leading to inconsistent user experiences.
- Load balancers (e.g., kube‑proxy, Istio, Traefik) rely on the liveness/readiness state to decide whether to forward requests. An incorrect probe can cause a pod to stay in the pool after it should have been removed.
- Service discovery tools such as Consul or Eureka need accurate status information to avoid cascading failures. If a pod reports “up” while its database is unreachable, downstream services may start making expensive retries, amplifying latency.
Liveness vs Readiness: The Core Difference
Liveness
- Indicates the process is running and should be restarted if it reports unhealthy.
- Should be a lightweight check that never depends on external services.
- Typical implementation: a
/healthzendpoint that returns 200 if the process can respond to a simple request.
Readiness
- Signals that the service is fully initialized and ready to accept traffic.
- Must verify that all external dependencies (DB, message broker, cache) are reachable.
- During maintenance or rolling updates, a pod’s readiness should be set to false to stop new traffic while it shuts down.
Typical Patterns
| Endpoint | Purpose | Typical Implementation |
|---|---|---|
/healthz |
Liveness | Return 200 if the HTTP server can respond. |
/readyz |
Readiness | Return 200 only after all dependency checks pass. |
Implementing Readiness Probes in Kubernetes
A readiness probe in Kubernetes is usually an HTTP GET to /readyz. The pod should only return 200 when it can talk to all required services.
Example Go handler
package main
import (
"context"
"database/sql"
"log"
"net/http"
"os"
"os/signal"
"time"
_ "github.com/lib/pq"
)
// dbCheck verifies that the database is reachable.
func dbCheck(ctx context.Context, db *sql.DB) error {
// Ping with a short timeout to avoid blocking the readiness check.
ctx, cancel := context.WithTimeout(ctx, 200*time.Millisecond)
defer cancel()
return db.PingContext(ctx)
}
func readyzHandler(db *sql.DB) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
if err := dbCheck(r.Context(), db); err != nil {
http.Error(w, "DB not ready", http.StatusServiceUnavailable)
return
}
w.WriteHeader(http.StatusOK)
w.Write([]byte("ready"))
}
}
func healthzHandler() http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
// Simple check: can we write a 200?
w.WriteHeader(http.StatusOK)
w.Write([]byte("ok"))
}
}
func main() {
// Connect to the database once at startup.
db, err := sql.Open("postgres", os.Getenv("POSTGRES_DSN"))
if err != nil {
log.Fatalf("failed to open DB: %v", err)
}
// Ensure the DB connection is closed on shutdown.
defer db.Close()
mux := http.NewServeMux()
mux.HandleFunc("/healthz", healthzHandler())
mux.HandleFunc("/readyz", readyzHandler(db))
mux.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
w.Write([]byte("Hello, world!"))
})
srv := &http.Server{
Addr: ":8080",
Handler: mux,
}
// Channel to listen for termination signals.
stop := make(chan os.Signal, 1)
signal.Notify(stop, os.Interrupt, os.Kill)
// Start the HTTP server in a goroutine.
go func() {
log.Println("listening on :8080")
if err := srv.ListenAndServe(); err != http.ErrServerClosed {
log.Fatalf("listen: %v", err)
}
}()
// Block until a termination signal is received.
<-stop
log.Println("shutdown signal received")
// Create a context with a timeout to allow in‑flight requests to finish.
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
defer cancel()
// Trigger graceful shutdown.
if err := srv.Shutdown(ctx); err != nil {
log.Fatalf("shutdown failed: %v", err)
}
log.Println("server exited properly")
}
Explanation
- Readiness handler (
/readyz) pings the database with a 200 ms timeout. If the ping fails, the endpoint returns503 Service Unavailable. - Liveness handler (
/healthz) simply returns200 OK. - The main function starts the HTTP server and listens for
SIGINT/SIGTERM. - Upon receiving a signal, it creates a context with a 30‑second timeout, allowing any in‑flight requests to finish before the server shuts down.
- The database connection is closed cleanly during shutdown.
Graceful Shutdown: Hooking into the Runtime
Graceful shutdown is the process of stopping the service in a controlled manner:
- Stop accepting new connections – achieved by the readiness probe or by closing the listener.
- Finish in‑flight requests – the HTTP server will keep serving until all handlers return.
- Stop background workers – cancel any goroutines using the shared context.
- Release resources – close DB connections, file handles, etc.
The Go http.Server provides a Shutdown(ctx) method that does exactly this. The context’s deadline is the maximum time you allow for cleanup. If the deadline expires, the server forces a shutdown.
Coordinating Readiness and Shutdown for Zero‑Downtime
During a rolling update:
- Set readiness to false – before the pod receives
SIGTERM, Kubernetes will stop routing traffic. - Graceful shutdown – the pod finishes processing current requests and cleans up.
- Pod termination – after the grace period, Kubernetes kills the container.
In practice, Kubernetes will send a termination signal after the pod’s readiness probe fails. The pod’s readiness endpoint can be designed to return 503 once it detects that it is in shutdown mode (e.g., after a signal has been received). This ensures the kube‑proxy immediately drains the pod.
Example readiness logic that flips after SIGTERM
var shuttingDown atomic.Bool
func readyzHandler(db *sql.DB) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
if shuttingDown.Load() {
http.Error(w, "shutting down", http.StatusServiceUnavailable)
return
}
if err := dbCheck(r.Context(), db); err != nil {
http.Error(w, "DB not ready", http.StatusServiceUnavailable)
return
}
w.WriteHeader(http.StatusOK)
w.Write([]byte("ready"))
}
}
In the signal handler:
shuttingDown.Store(true)
Now, once SIGTERM arrives, the readiness probe immediately starts failing, kube‑proxy stops sending traffic, and the graceful shutdown proceeds.
Common Mistakes & Trade‑Offs
| Mistake | Why it hurts | Mitigation |
|---|---|---|
| Using liveness probe for readiness | A liveness probe that checks DB connectivity can cause unnecessary restarts if the DB is temporarily unreachable. | Keep liveness simple (e.g., /healthz that just verifies the HTTP server is alive). Use readiness for dependency checks. |
| Failing to drain connections | New requests may be dropped if the pod stops accepting connections before finishing current ones. | Use a proper Shutdown with a generous timeout; ensure the readiness probe is disabled during shutdown. |
| Too short shutdown timeouts | Incomplete cleanup (e.g., uncommitted DB transactions, orphaned goroutines). | Test the shutdown path and set a timeout that covers the longest cleanup operation. |
| Aggressive readiness checks | If readiness requires a long DB transaction or external service that is slow, the pod may appear unready for extended periods, causing traffic to be routed to other replicas unnecessarily. | Keep readiness checks lightweight; cache dependency status if possible. |
| Not handling context cancellation in goroutines | Background workers may keep running after the server exits, leaking resources. | Pass the main context to all goroutines and listen for cancellation. |
| Ignoring SIGKILL | Kubernetes may send SIGKILL if the pod does not terminate in the grace period, leading to abrupt termination. |
Ensure the shutdown timeout is long enough for all cleanup; monitor logs for forced kills. |
Real‑world Example: E‑commerce Order Service
An order service in a microservice architecture needs to:
- Connect to a PostgreSQL database and a Redis cache.
- Process HTTP requests for order creation and status.
- Handle background jobs for payment processing.
Deployment strategy
- Readiness checks that both PostgreSQL and Redis are reachable.
- Liveness is a simple
/healthzthat verifies the HTTP server can respond. - Graceful shutdown waits for in‑flight HTTP requests and pending payment jobs to finish.
- Rolling update uses a
preStophook to set a flag that makes/readyzreturn503, ensuring kube‑proxy stops sending traffic before the container receivesSIGTERM.
This setup guarantees that during a deployment, no new orders are accepted by the old pod, existing orders finish processing, and the service never serves stale data.
Key takeaways
- Separate liveness and readiness: keep liveness fast and independent, readiness checks should verify all external dependencies.
- Use readiness probes to drain traffic during rolling updates or graceful shutdown.
- Graceful shutdown in Go is straightforward with
http.Server.Shutdown(ctx); always cancel the context for background workers. - Set appropriate timeouts: too short leads to incomplete cleanup; too long delays new deployments.
- Test the shutdown path in a staging environment to ensure no requests are dropped and resources are released.
By combining Kubernetes readiness probes, lightweight liveness checks, and a robust graceful shutdown routine, you can eliminate split‑brain scenarios and achieve truly zero‑downtime deployments for your containerized services.
FAQ
What is the difference between liveness and readiness probes?
Liveness probes check that the process is running and can respond quickly, while readiness probes verify that all external dependencies are reachable before the pod accepts traffic.
How does a Go HTTP server implement graceful shutdown?
By catching SIGTERM or SIGINT, creating a context with timeout, calling srv.Shutdown(ctx) to allow in‑flight requests to finish, and then closing resources like DB connections.
What should a readiness probe check for?
It should ping all required services, such as the database, with a short timeout, and return 200 only if all checks pass; otherwise return 503 Service Unavailable.
What timeout should be used for graceful shutdown?
A 30‑second timeout is common, giving enough time for pending requests to complete while preventing indefinite waits.