Skip to main content
Lesson 1 of 1Advanced⏱ 15 mins

Graceful Shutdown

Handling SIGTERM cleanly.

0% of path

Learning Objectives

  • Intercept kill signals

##Graceful Shutdown & Health Checks

When deploying an Actix Web application to production (e.g., in a Docker container or Kubernetes pod), you need to handle server shutdowns gracefully. If you simply kill the process, any in-flight requests will be abruptly terminated, resulting in errors for your users.

Actix Web's HttpServer supports graceful shutdown by default when it receives OS signals (like SIGINT from Ctrl+C, or SIGTERM from Docker/Kubernetes).

#How Graceful Shutdown Works

When a termination signal is received: 1. The server stops accepting new connections. 2. It waits for active requests to finish processing. 3. Once all active requests complete (or a timeout is reached), the server shuts down.

By default, Actix Web waits up to 30 seconds for workers to shut down. You can configure this using the shutdown_timeout method:

code_blocksrust
use actix_web::{App, HttpServer, HttpResponse, get};

#[get("/")]
async fn index() -> HttpResponse {
    HttpResponse::Ok().body("Server is running")
}

#[actix_web::main]
async fn main() -> std::io::Result<()> {
    HttpServer::new(|| {
        App::new().service(index)
    })
    .bind(("0.0.0.0", 8080))?
    // Wait up to 10 seconds for active connections to finish
    .shutdown_timeout(10)
    .run()
    .await
}

#Implementing a Health Check

A health check endpoint is essential for load balancers and orchestrators (like Kubernetes) to know if your application is ready to receive traffic. A simple /health endpoint returning 200 OK is usually sufficient.

code_blocksrust
use actix_web::{get, HttpResponse, Responder};

#[get("/health")]
async fn health_check() -> impl Responder {
    // You could also check DB connectivity here before returning 200
    HttpResponse::Ok().json(serde_json::json!({
        "status": "healthy",
        "version": env!("CARGO_PKG_VERSION")
    }))
}

In a real application, your health check might also ping your database pool or check Redis connectivity to ensure the service is fully operational.

Practical Exercise

Configure Graceful Shutdown

Task

Requirements

    Try solving the exercise in your local environment first. Once you have a solution, or if you get completely stuck, reveal the answer.

    Key Takeaways

    • Actix Web handles OS signals (`SIGINT`, `SIGTERM`) automatically for graceful shutdown.
    • Use `shutdown_timeout(seconds)` on the `HttpServer` to configure how long to wait for in-flight requests.
    • Always include a `/health` or `/live` endpoint for Kubernetes/Docker health checks.
    • A health check should return a 200 status code and optionally verify critical dependencies like the database.

    Finished reading?

    Mark this lesson as done to track your progress and earn XP.