A process that exits on SIGTERM by dying mid-request leaves clients holding a broken connection and databases missing a commit. Graceful shutdown means:
- Stop accepting new work.
- Let in-flight work finish (up to a deadline).
- Close downstream resources (DB connections, caches, flush buffers) in reverse init order.
- Exit.
The shutdown deadline is mandatory. Step 2 without a cap means a stuck request can hold up the deploy forever.
Go
HTTP server shutdown
http.Server.Shutdown stops the listener and waits for active connections to
become idle before returning. Pass it a context with a timeout so it doesn’t
wait indefinitely:
func main() {
mux := http.NewServeMux()
mux.HandleFunc("GET /", handleRoot)
srv := &http.Server{
Addr: ":8080",
Handler: mux,
}
// NotifyContext cancels when SIGINT or SIGTERM arrives.
ctx, stop := signal.NotifyContext(context.Background(),
os.Interrupt, syscall.SIGTERM)
defer stop()
go func() {
if err := srv.ListenAndServe(); !errors.Is(err, http.ErrServerClosed) {
log.Printf("server error: %v", err)
os.Exit(1)
}
}()
<-ctx.Done()
stop() // unregister signal handlers; a second signal now terminates immediately
shutdownCtx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
defer cancel()
if err := srv.Shutdown(shutdownCtx); err != nil {
log.Printf("shutdown error: %v", err)
}
}srv.Shutdown does not close hijacked connections (WebSockets, HTTP/2 streams
that have been taken over manually). Track those separately if you use them.
Cleaning up other resources
Open a DB pool, message queue client, or cache connection after the server
starts and close it after Shutdown returns, not before:
db, err := sql.Open("pgx", os.Getenv("DATABASE_URL"))
if err != nil {
log.Fatal(err)
}
srv := &http.Server{Addr: ":8080", Handler: buildHandler(db)}
// ... signal setup and goroutine as above ...
<-ctx.Done()
stop()
shutdownCtx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
defer cancel()
if err := srv.Shutdown(shutdownCtx); err != nil {
log.Printf("shutdown error: %v", err)
}
// Handlers have all returned; safe to close the pool.
if err := db.Close(); err != nil {
log.Printf("db close error: %v", err)
}The ordering matters: db.Close() after srv.Shutdown() guarantees no handler
is mid-query when the pool drains.
Tracking background goroutines
HTTP request handlers aren’t the only work that needs to finish. A worker that
processes jobs from a queue also needs draining. Use sync.WaitGroup or
golang.org/x/sync/errgroup to track goroutines and wait for them in the
shutdown path:
var wg sync.WaitGroup
wg.Add(1)
go func() {
defer wg.Done()
runWorker(ctx) // ctx is the signal-cancelled context
}()
<-ctx.Done()
stop()
done := make(chan struct{})
go func() {
wg.Wait()
close(done)
}()
select {
case <-done:
log.Println("workers finished")
case <-time.After(30 * time.Second):
log.Println("shutdown timeout: some workers did not finish")
}The worker exits when ctx is cancelled. The select enforces the deadline
independently of the HTTP server shutdown.
Rust (tokio / axum)
HTTP server shutdown with axum
axum::serve accepts a future that, when it resolves, triggers graceful
shutdown: the server stops accepting new connections and waits for active ones
to close:
use tokio::net::TcpListener;
#[tokio::main]
async fn main() -> anyhow::Result<()> {
let app = build_router();
let listener = TcpListener::bind("0.0.0.0:8080").await?;
axum::serve(listener, app)
.with_graceful_shutdown(shutdown_signal())
.await?;
Ok(())
}The signal future handles both Ctrl-C (all platforms) and SIGTERM (Unix):
async fn shutdown_signal() {
let ctrl_c = async {
tokio::signal::ctrl_c()
.await
.expect("failed to install Ctrl+C handler");
};
#[cfg(unix)]
let sigterm = async {
tokio::signal::unix::signal(tokio::signal::unix::SignalKind::terminate())
.expect("failed to install SIGTERM handler")
.recv()
.await;
};
#[cfg(not(unix))]
let sigterm = std::future::pending::<()>();
tokio::select! {
_ = ctrl_c => {},
_ = sigterm => {},
}
}select! resolves as soon as either signal arrives; the other branch is
dropped. On non-Unix targets (Windows), sigterm is a never-resolving future
so only ctrl_c fires.
Enforcing a shutdown deadline
axum::serve itself has no built-in drain timeout, and wrapping the whole
serve future in tokio::time::timeout starts the clock at startup, not at the
signal. Own the signal with a CancellationToken so the deadline starts when
the signal arrives:
use std::future::IntoFuture;
use tokio::net::TcpListener;
use tokio::time::{timeout, Duration};
use tokio_util::sync::CancellationToken;
#[tokio::main]
async fn main() -> anyhow::Result<()> {
let app = build_router();
let listener = TcpListener::bind("0.0.0.0:8080").await?;
let shutdown = CancellationToken::new();
// Translate OS signals into a token cancellation.
tokio::spawn({
let shutdown = shutdown.clone();
async move {
shutdown_signal().await;
shutdown.cancel();
}
});
let server = tokio::spawn(
axum::serve(listener, app)
.with_graceful_shutdown({
let shutdown = shutdown.clone();
async move { shutdown.cancelled().await }
})
.into_future(),
);
// The drain deadline starts when the signal arrives, not at startup.
shutdown.cancelled().await;
match timeout(Duration::from_secs(30), server).await {
Ok(joined) => joined??,
Err(_) => eprintln!("shutdown timed out after 30s"),
}
Ok(())
}Cleaning up after shutdown
Resources that handlers depend on must outlive the server. Create them before starting the server, and close them after the drain completes:
use sqlx::PgPool;
#[tokio::main]
async fn main() -> anyhow::Result<()> {
let pool = PgPool::connect(&std::env::var("DATABASE_URL")?).await?;
let app = build_router(pool.clone());
let listener = TcpListener::bind("0.0.0.0:8080").await?;
// ... spawn the server and wait out the drain deadline as above ...
// All handlers have returned; close the pool.
pool.close().await;
Ok(())
}Background tasks with CancellationToken
Spawn long-running tasks with a shared CancellationToken. Cancel it when the
signal fires and join the tasks before exiting:
use tokio_util::sync::CancellationToken;
use tokio::task::JoinSet;
#[tokio::main]
async fn main() -> anyhow::Result<()> {
let token = CancellationToken::new();
let mut tasks = JoinSet::new();
tasks.spawn(run_worker(token.clone()));
tasks.spawn(run_scheduler(token.clone()));
let app = build_router();
let listener = TcpListener::bind("0.0.0.0:8080").await?;
axum::serve(listener, app)
.with_graceful_shutdown(shutdown_signal())
.await?;
// Signal fired; cancel all background tasks.
token.cancel();
// Wait for them, with a deadline.
let drain = async { while tasks.join_next().await.is_some() {} };
timeout(Duration::from_secs(30), drain).await.ok();
Ok(())
}Each worker checks token.is_cancelled() at its loop boundary or uses
token.cancelled().await in a select! to yield cleanly.
Shutdown order
The same sequence applies regardless of language:
SIGTERM / Ctrl-C received
│
├─ Stop accepting new connections (close listener)
│
├─ Wait for in-flight requests to finish ← deadline here
│
├─ Cancel background tasks / workers ← deadline here
│
└─ Close resources in reverse init order
├─ Cache clients
├─ Message queue connections
└─ Database poolThe deadline at each drain step prevents a single stuck request or runaway
worker from blocking the whole shutdown. Under Kubernetes, the pod’s
terminationGracePeriodSeconds is the outer wall; make your internal deadlines
comfortably shorter so the process exits before the kubelet sends SIGKILL.
Fail the readiness probe immediately on SIGTERM, before draining begins, so the load balancer stops routing new requests before connections close. See Health Checks for the endpoint implementation and Kubernetes probe configuration.