This specification is maintained by the AgentRules Working Group. Have enhancements or want to claim maintainership?Submit Specification →
backendcritical PriorityID: axum-hyper-graceful-connection-drain

Axum 0.8 Hyper v1 Graceful Connection Drain and Lease Standard

Guarantees deterministic zero-downtime rolling deployments by decoupling socket listener termination from in-flight request cancellation. Enforces explicit connection drain timeouts, correct HTTP/2 GOAWAY emission, and bounded keep-alive leases before SIGKILL triggers.

Prohibited Anti-Pattern: Immediate Runtime Future Dropping and Unbounded HTTP/2 Keep-Alive Lease Starvation During SIGTERM

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Axum 0.8 Hyper v1 Graceful Connection Drain and Lease Standard - Guarantees deterministic zero-downtime rolling deployments by decoupling socket listener termination from in-flight request cancellation. Enforces explicit connection drain timeouts, correct HTTP/2 GOAWAY emission, and bounded keep-alive leases before SIGKILL triggers.
globs: src/**/*.rs, crates/**/*.rs
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/axum-hyper-graceful-connection-drain"
---

# Axum 0.8 Hyper v1 Graceful Connection Drain and Lease Standard

> **Severity**: CRITICAL | **Category**: backend
> **Anti-Pattern Warning**: Immediate Runtime Future Dropping and Unbounded HTTP/2 Keep-Alive Lease Starvation During SIGTERM

## System Constraints
You are a Principal Systems Architect enforcing the Axum 0.8 and Hyper v1 Graceful Connection Drain & Lease Standard. Mandate invariants that prevent abrupt TCP resets, dropped HTTP/2 multiplexed streams, and container SIGKILL drops during rolling deploys.

## Strict Guidelines
- Engineers MUST ALWAYS decouple socket shutdown signaling from in-flight execution using `axum::serve::with_graceful_shutdown` rather than wrapping the root server task in a destructive `tokio::select!` branch.
- Engineers MUST NOT allow indefinite graceful shutdown; drain phases MUST enforce a bounded timeout that is strictly shorter than the container orchestrator's termination grace period (e.g., 25s timeout for a 30s Kubernetes terminationGracePeriodSeconds).
- Services MUST trap both `SIGINT` and `SIGTERM` signals using OS-level signal handlers via `tokio::signal::unix` on Unix targets.
- Code SHOULD configure Hyper v1 connection builders with explicit keep-alive timeouts and HTTP/2 max concurrent stream lease limits to ensure active connections observe `GOAWAY` frames promptly.
- Components NEVER drop Tokio runtime task handles running long-lived background tasks associated with HTTP connection life cycles without cooperative cancellation tokens (`tokio_util::sync::CancellationToken`).

## Bad vs Good Implementations
### Graceful Shutdown Coordination with Hard Drain Timeout

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Directly aborting the server future via select! causes immediate drops of active Hyper connection handles. This sends abrupt TCP RST packets to clients, truncates HTTP/2 streams mid-response, and violates zero-downtime deployment guarantees.
```rust
use axum::{routing::get, Router};
use tokio::net::TcpListener;

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let app = Router::new().route("/health", get(|| async { "UP" }));
    let listener = TcpListener::bind("0.0.0.0:8080").await?;

    // ANTI-PATTERN: Wrapping axum::serve directly inside tokio::select!
    // When ctrl_c resolves, the server future is abruptly DROPPED.
    // Active TCP connections are RST, HTTP/2 GOAWAY frames are never sent,
    // and in-flight client requests fail immediately.
    tokio::select! {
        res = axum::serve(listener, app) => res?,
        _ = tokio::signal::ctrl_c() => {
            println!("Received shutdown signal; aborting all connections immediately.");
        }
    }
    Ok(())
}
```

#### Production Standard (Correct)
> **Standard**: Uses with_graceful_shutdown to stop accepting new connections while issuing HTTP/2 GOAWAY frames and letting in-flight requests finish cleanly. Protects against indefinitely stalled keep-alive clients using a bounded 25s timeout.
```rust
use axum::{routing::get, Router};
use std::time::Duration;
use tokio::net::TcpListener;
use tokio_util::sync::CancellationToken;

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let app = Router::new().route("/health", get(|| async { "UP" }));
    let listener = TcpListener::bind("0.0.0.0:8080").await?;
    let token = CancellationToken::new();

    let shutdown_token = token.clone();
    let server = axum::serve(listener, app).with_graceful_shutdown(async move {
        shutdown_signal().await;
        shutdown_token.cancel();
    });

    // Bound the drain window to 25s (Kubernetes default terminationGracePeriod is 30s)
    tokio::select! {
        res = server => res?,
        _ = async {
            token.cancelled().await;
            tokio::time::sleep(Duration::from_secs(25)).await;
        } => {
            eprintln!("Drain timeout reached: forcing socket close before orchestrator SIGKILL");
        }
    }
    Ok(())
}

async fn shutdown_signal() {
    let ctrl_c = async {
        tokio::signal::ctrl_c()
            .await
            .expect("Failed to install Ctrl+C handler");
    };

    #[cfg(unix)]
    let terminate = async {
        tokio::signal::unix::signal(tokio::signal::unix::SignalKind::terminate())
            .expect("Failed to install SIGTERM handler")
            .recv()
            .await;
    };

    #[cfg(not(unix))]
    let terminate = std::future::pending::<()>();

    tokio::select! {
        _ = ctrl_c => {},
        _ = terminate => {},
    }
}
```

Recommended MCP Servers (mcp-serverlist.com)

Equip agent with system tools to verify code for this stack.

Recommended Agent Skills (askills.dev)

Ready-to-use executable skill functions tailored to this stack.

Architectural Specification & Invariant Rationale

Architectural Invariant Design: Axum 0.8 Hyper v1 Graceful Connection Drain and Lease Standard

Axum 0.8 Hyper v1 Graceful Connection Drain and Lease Standard defines an industrial-grade behavioral standard for backend engineering. Guarantees deterministic zero-downtime rolling deployments by decoupling socket listener termination from in-flight request cancellation. Enforces explicit connection drain timeouts, correct HTTP/2 GOAWAY emission, and bounded keep-alive leases before SIGKILL triggers. Modern software architectures require strict adherence to deterministic patterns to guarantee high availability, maintainability, and zero security vulnerabilities.

Framework Paradigm Shift & Drift MechanicsLLMs are trained on millions of open-source repositories containing outdated code, legacy idioms, and unpatched antipatterns. When coding assistants generate implementations for this stack, they default to common statistical tokens: Immediate Runtime Future Dropping and Unbounded HTTP/2 Keep-Alive Lease Starvation During SIGTERM Without an explicit system instruction file, developers spend hours debugging silent failures.
Failure Modes & Production Blast Radius

Hazard Analysis: What Breaks Without This Rule

The following failure modes have been cataloged from hundreds of hours of production code reviews where AI assistants produced non-compliant implementations:

Failure ModeAI Symptom (The Anti-Pattern)SeverityProduction Impact & Remedy
AI Hallucination & Deprecation DriftImmediate Runtime Future Dropping and Unbounded HTTP/2 Keep-Alive Lease Starvation During SIGTERMCritical
Violating this industrial standard introduces regression bugs, security risks, and unexpected runtime failures in production.
Enforce explicit behavioral system directives across all AI coding assistants in your repository.
Silent Architecture InconsistencyAI assistants produce mixed paradigms across files, creating fragmented codebase conventions.Medium
Increases cognitive load during code reviews and leads to maintenance debt across engineering teams.
Pin project conventions in .cursor/rules, CLAUDE.md, and AGENTS.md so all team agents follow identical guardrails.
Architectural Directives in Detail

Step-by-Step Production Directives

Each rule constraint below is injected into the AI agent's system prompt to establish deterministic boundaries:

1

Engineers MUST ALWAYS decouple socket shutdown signaling from in-flight execution using `axum

Engineers MUST ALWAYS decouple socket shutdown signaling from in-flight execution using `axum::serve::with_graceful_shutdown` rather than wrapping the root server task in a destructive `tokio::select!` branch.

Rationale:AI models frequently generate unconstrained code here because statistical language distributions lack project-specific architectural context. Mandating this directive ensures that generated code adheres to verified industrial production requirements.
Enforcement:Integrated into the Agent Pack rule file. When Cursor, Claude Code, or Codex processes this prompt, it applies this constraint before emitting syntax.
2

Engineers MUST NOT allow indefinite graceful shutdown

Engineers MUST NOT allow indefinite graceful shutdown; drain phases MUST enforce a bounded timeout that is strictly shorter than the container orchestrator's termination grace period (e.g., 25s timeout for a 30s Kubernetes terminationGracePeriodSeconds).

Rationale:AI models frequently generate unconstrained code here because statistical language distributions lack project-specific architectural context. Mandating this directive ensures that generated code adheres to verified industrial production requirements.
Enforcement:Integrated into the Agent Pack rule file. When Cursor, Claude Code, or Codex processes this prompt, it applies this constraint before emitting syntax.
3

Services MUST trap both `SIGINT` and `SIGTERM` signals using OS-level signal handlers via `tokio

Services MUST trap both `SIGINT` and `SIGTERM` signals using OS-level signal handlers via `tokio::signal::unix` on Unix targets.

Rationale:AI models frequently generate unconstrained code here because statistical language distributions lack project-specific architectural context. Mandating this directive ensures that generated code adheres to verified industrial production requirements.
Enforcement:Integrated into the Agent Pack rule file. When Cursor, Claude Code, or Codex processes this prompt, it applies this constraint before emitting syntax.
4

Code SHOULD configure Hyper v1 connection builders with explicit keep-alive timeouts and HTTP/2 max concurrent stream lease limits to ensure active connections observe `GOAWAY` frames promptly.

Code SHOULD configure Hyper v1 connection builders with explicit keep-alive timeouts and HTTP/2 max concurrent stream lease limits to ensure active connections observe `GOAWAY` frames promptly.

Rationale:AI models frequently generate unconstrained code here because statistical language distributions lack project-specific architectural context. Mandating this directive ensures that generated code adheres to verified industrial production requirements.
Enforcement:Integrated into the Agent Pack rule file. When Cursor, Claude Code, or Codex processes this prompt, it applies this constraint before emitting syntax.
5

Components NEVER drop Tokio runtime task handles running long-lived background tasks associated with HTTP connection life cycles without cooperative cancellation tokens (`tokio_util

Components NEVER drop Tokio runtime task handles running long-lived background tasks associated with HTTP connection life cycles without cooperative cancellation tokens (`tokio_util::sync::CancellationToken`).

Rationale:AI models frequently generate unconstrained code here because statistical language distributions lack project-specific architectural context. Mandating this directive ensures that generated code adheres to verified industrial production requirements.
Enforcement:Integrated into the Agent Pack rule file. When Cursor, Claude Code, or Codex processes this prompt, it applies this constraint before emitting syntax.
Technical Questions & Answers

Frequently Asked Technical Questions

Common questions developers face when configuring AI coding assistants for this stack:

Q:Why is Axum 0.8 Hyper v1 Graceful Connection Drain and Lease Standard critical for AI coding assistants?

Guarantees deterministic zero-downtime rolling deployments by decoupling socket listener termination from in-flight request cancellation. Enforces explicit connection drain timeouts, correct HTTP/2 GOAWAY emission, and bounded keep-alive leases before SIGKILL triggers. Without explicit behavioral boundaries, AI coding assistants (Cursor, Claude Code, Windsurf, Codex) rely on training data averages, which frequently produce deprecated, inefficient, or vulnerable code patterns.

Q:How does adopting this rule prevent AI hallucinations?

This rule explicitly declares what the AI must avoid (Immediate Runtime Future Dropping and Unbounded HTTP/2 Keep-Alive Lease Starvation During SIGTERM) and prescribes verified positive examples. Grounding the LLM with negative and positive pairs eliminates guesswork.

Q:Which AI coding environments are supported?

This specification is multi-platform compatible: Cursor (.cursor/rules/*.mdc & .cursorrules), Anthropic Claude Code (CLAUDE.md), Windsurf (.windsurfrules), Codex / Cline (AGENTS.md), and GitHub Copilot (.github/copilot-instructions.md).

Q:Can I combine this rule with other technology stacks?

Yes. Use the Interactive Stack Builder or download an Agent Pack to merge this rule with other frontend, backend, database, security, and DevOps rules without syntax collision.

Open Specification · CC BY 4.0·Free for Personal, Team & Commercial In-Repo Use

Citation & Open Source Attribution Guidelines

This specification is licensed under Creative Commons Attribution 4.0 International (CC BY 4.0). You are completely free to adapt and share this rule in your workspace. If citing, including in public AI benchmark datasets, or redistributing, attribution to AgentRules.org is required.

1 Rule in Stack

Axum