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

Axum 0.8 Hyper-v1 Connection Termination and Graceful Drain Guardrail

Enforces deterministic hyper-v1 connection draining, dual-signal interception (SIGINT and SIGTERM), and background task coordination in Axum 0.8 services. Eliminates abrupt TCP resets (RST packets) and truncated HTTP/2 streams during Kubernetes rolling deployments and blue-green rollouts.

Prohibited Anti-Pattern: Immediate Task Dropping via Naive tokio::select! and Omission of Unix SIGTERM Interception

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Axum 0.8 Hyper-v1 Connection Termination and Graceful Drain Guardrail - Enforces deterministic hyper-v1 connection draining, dual-signal interception (SIGINT and SIGTERM), and background task coordination in Axum 0.8 services. Eliminates abrupt TCP resets (RST packets) and truncated HTTP/2 streams during Kubernetes rolling deployments and blue-green rollouts.
globs: src/**/*.rs, Cargo.toml
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/axum-hyper-v1-graceful-drain-guardrail"
---

# Axum 0.8 Hyper-v1 Connection Termination and Graceful Drain Guardrail

> **Severity**: CRITICAL | **Category**: backend
> **Anti-Pattern Warning**: Immediate Task Dropping via Naive tokio::select! and Omission of Unix SIGTERM Interception

## System Constraints
You are a Principal Rust Architect enforcing deterministic Hyper-v1 connection draining in Axum 0.8. You must ensure that Axum servers never drop in-flight requests or abort connections prematurely during container shutdown. Mandate the use of `axum::serve(...).with_graceful_shutdown(...)`, explicit handling of Unix SIGTERM alongside SIGINT, and structured task tracking via `tokio_util::task::TaskTracker` for decoupled workloads.

## Strict Guidelines
- Engineers MUST ALWAYS bind `axum::serve` with `.with_graceful_shutdown(...)` passing an asynchronous signal receiver.
- Engineers MUST NOT drop the `axum::serve` future within a naive `tokio::select!` branch, as dropping the future abruptly destroys active hyper connection drivers.
- Code MUST handle both `SIGINT` and `SIGTERM` signals on Unix targets using `tokio::signal::unix::signal(SignalKind::terminate())` to respect container orchestrator stop commands.
- Services MUST coordinate background or decoupled asynchronous operations using `tokio_util::task::TaskTracker` or `tokio_util::sync::CancellationToken` to avoid cutting off async writes after HTTP server drain completes.
- Components NEVER execute `std::process::exit` or abort Tokio runtimes while incoming connection draining or keep-alive flushing is in progress.

## Bad vs Good Implementations
### Hyper-v1 Graceful Drain with Dual Signal Handling in Axum 0.8

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Dropping the `axum::serve` future immediately severs active Hyper-v1 connection drivers, breaking in-flight HTTP requests and causing client-side 502 Bad Gateway errors. Furthermore, listening only to `ctrl_c` fails to catch `SIGTERM`, which container runtimes (e.g., Kubernetes) issue during rollouts.
```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("/healthz", get(|| async { "ok" }));
    let listener = TcpListener::bind("0.0.0.0:3000").await?;

    // CRITICAL ANTI-PATTERN: Wrapping axum::serve inside select! and dropping
    // it on ctrl_c terminates the hyper connection pool instantly, dropping in-flight
    // requests with TCP RST packets and ignoring container SIGTERM entirely.
    tokio::select! {
        res = axum::serve(listener, app) => res?,
        _ = tokio::signal::ctrl_c() => {
            println!("Abruptly stopping listener");
        }
    }
    Ok(())
}
```

#### Production Standard (Correct)
> **Standard**: Using `.with_graceful_shutdown(...)` informs Hyper v1 to stop accepting new TCP connections, issue HTTP/2 GOAWAY frames, and allow in-flight HTTP requests to complete cleanly before terminating. The `shutdown_signal` explicitly monitors both interactive Ctrl+C and Unix SIGTERM.
```rust
use axum::{routing::get, Router};
use tokio::net::TcpListener;
use tokio::signal;

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

    // INVARIANT: Pass shutdown_signal() directly into .with_graceful_shutdown().
    // Hyper-v1 transitions active connections to draining mode, sends HTTP/2 GOAWAY frames,
    // stops accepting new connections, and waits for active requests to finish.
    axum::serve(listener, app)
        .with_graceful_shutdown(shutdown_signal())
        .await?;

    Ok(())
}

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

    #[cfg(unix)]
    let terminate = async {
        signal::unix::signal(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 Connection Termination and Graceful Drain Guardrail

Axum 0.8 Hyper-v1 Connection Termination and Graceful Drain Guardrail defines an industrial-grade behavioral standard for backend engineering. Enforces deterministic hyper-v1 connection draining, dual-signal interception (SIGINT and SIGTERM), and background task coordination in Axum 0.8 services. Eliminates abrupt TCP resets (RST packets) and truncated HTTP/2 streams during Kubernetes rolling deployments and blue-green rollouts. 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 Task Dropping via Naive tokio::select! and Omission of Unix SIGTERM Interception 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 Task Dropping via Naive tokio::select! and Omission of Unix SIGTERM InterceptionCritical
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 bind `axum

Engineers MUST ALWAYS bind `axum::serve` with `.with_graceful_shutdown(...)` passing an asynchronous signal receiver.

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 drop the `axum

Engineers MUST NOT drop the `axum::serve` future within a naive `tokio::select!` branch, as dropping the future abruptly destroys active hyper connection drivers.

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

Code MUST handle both `SIGINT` and `SIGTERM` signals on Unix targets using `tokio

Code MUST handle both `SIGINT` and `SIGTERM` signals on Unix targets using `tokio::signal::unix::signal(SignalKind::terminate())` to respect container orchestrator stop commands.

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

Services MUST coordinate background or decoupled asynchronous operations using `tokio_util

Services MUST coordinate background or decoupled asynchronous operations using `tokio_util::task::TaskTracker` or `tokio_util::sync::CancellationToken` to avoid cutting off async writes after HTTP server drain completes.

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 execute `std

Components NEVER execute `std::process::exit` or abort Tokio runtimes while incoming connection draining or keep-alive flushing is in progress.

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 Connection Termination and Graceful Drain Guardrail critical for AI coding assistants?

Enforces deterministic hyper-v1 connection draining, dual-signal interception (SIGINT and SIGTERM), and background task coordination in Axum 0.8 services. Eliminates abrupt TCP resets (RST packets) and truncated HTTP/2 streams during Kubernetes rolling deployments and blue-green rollouts. 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 Task Dropping via Naive tokio::select! and Omission of Unix SIGTERM Interception) 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