This specification is maintained by the AgentRules Working Group. Have enhancements or want to claim maintainership?Submit Specification →
backendcritical PriorityID: axum-0-8-h3-quic-stream-drain-termination

Axum 0.8 HTTP/3 QUIC Stream Draining & Connection Termination Guardrail

Enforces graceful HTTP/3 connection lifecycle management during SIGTERM and rolling updates in Axum 0.8 / Quinn runtimes. Mandates emission of stepped HTTP/3 GOAWAY frames with stream cancellation shields to eliminate drops of in-flight and 0-RTT early-data requests.

Prohibited Anti-Pattern: Abrupt QUIC Endpoint Teardown and Unshielded Tokio Task Aborts on SIGTERM

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Axum 0.8 HTTP/3 QUIC Stream Draining & Connection Termination Guardrail - Enforces graceful HTTP/3 connection lifecycle management during SIGTERM and rolling updates in Axum 0.8 / Quinn runtimes. Mandates emission of stepped HTTP/3 GOAWAY frames with stream cancellation shields to eliminate drops of in-flight and 0-RTT early-data requests.
globs: src/**/*.rs
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/axum-0-8-h3-quic-stream-drain-termination"
---

# Axum 0.8 HTTP/3 QUIC Stream Draining & Connection Termination Guardrail

> **Severity**: CRITICAL | **Category**: backend
> **Anti-Pattern Warning**: Abrupt QUIC Endpoint Teardown and Unshielded Tokio Task Aborts on SIGTERM

## System Constraints
You are a Principal Systems Engineer enforcing zero-downtime Axum 0.8 HTTP/3 (QUIC) lifecycle management. Mandate that every server orchestrates a multi-phase graceful draining protocol: (1) stop accepting new UDP datagrams/handshakes, (2) transmit initial GOAWAY with maximum Stream ID to stop new requests while accepting late 0-RTT streams, (3) transmit terminal GOAWAY with the actual processed stream ID, and (4) guard active processing futures using tokio::task::JoinSet or stream cancellation shields (e.g., CancellationToken combined with timeout tracking) to prevent dropping in-flight I/O.

## Strict Guidelines
- Engineers MUST ALWAYS implement a two-phase HTTP/3 GOAWAY sequence: emit an initial GOAWAY with Stream ID 2^62-4 before emitting the final GOAWAY with the highest acknowledged client stream ID.
- Engineers MUST wrap in-flight request processing futures in Tokio cancellation shields or track them in a centralized JoinSet to prevent immediate abort on SIGTERM signal reception.
- Services MUST configure a deterministic drain timeout budget allowing in-flight 0-RTT streams and pending responses to flush before closing the Quinn endpoint.
- Engineers MUST NOT rely solely on standard TCP graceful shutdown helpers (e.g., axum::serve(...).with_graceful_shutdown(...)) for HTTP/3, as UDP/QUIC multiplexed connection semantics are bypassed.
- Endpoints MUST explicitly close Quinn QUIC connections using application code 0x100 (H3_NO_ERROR) only after all shielded stream tasks have completed or timed out.

## Bad vs Good Implementations
### Naive QUIC Server Teardown vs Controlled HTTP/3 GOAWAY Drain Sequence

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Abruptly terminating the future running the QUIC server causes immediate socket closure. Client requests currently in-flight, particularly multiplexed streams and 0-RTT requests mid-handshake, are dropped without an RFC 9114 GOAWAY frame, producing user-facing 502/503 errors during rolling updates.
```rust
use axum::{routing::get, Router};
use tokio::signal;

#[tokio::main]
async fn main() {
    let app = Router::new().route("/", get(|| async { "Hello, HTTP/3!" }));
    
    // ANTI-PATTERN: Wrapping a generic future into an immediate abort.
    // Once SIGTERM arrives, the select! drops the HTTP/3 runner immediately.
    // In-flight QUIC streams and 0-RTT early data are abruptly severed
    // with CONNECTION_RESET or silent UDP packet drops.
    tokio::select! {
        _ = run_quic_server(app) => {},
        _ = signal::ctrl_c() => {
            tracing::warn!("Forced exit on SIGTERM without GOAWAY or stream draining");
        }
    }
}

async fn run_quic_server(_app: Router) {
    // Hypothetical raw QUIC runner
}
```

#### Production Standard (Correct)
> **Standard**: The good pattern implements phased draining. Upon signal reception, it signals the HTTP/3 transport layer to issue an initial GOAWAY (stopping new stream allocation while accommodating late 0-RTT frames), provides a drain period for in-flight tasks, and terminates with an RFC-compliant clean application closure.
```rust
use axum::{routing::get, Router};
use tokio::signal;
use tokio::sync::watch;
use tokio_util::sync::CancellationToken;
use std::time::Duration;

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let cancel_token = CancellationToken::new();
    let (drain_tx, mut drain_rx) = watch::channel(false);
    
    let app = Router::new().route("/", get(|| async {
        // In-flight task is shielded or tied to cancellation token
        "Gracefully handled HTTP/3"
    }));

    let h3_handle = tokio::spawn(run_h3_draining_server(app, cancel_token.clone(), drain_rx.clone()));

    signal::ctrl_c().await?;
    tracing::info!("SIGTERM detected: beginning stepped HTTP/3 GOAWAY drain protocol");

    // Phase 1: Signal endpoints to emit initial GOAWAY (StreamID: 2^62-4) to cease new streams
    let _ = drain_tx.send(true);
    
    // Phase 2: Give 0-RTT and existing streams an upper-bound drain budget
    tokio::time::sleep(Duration::from_secs(15)).await;

    // Phase 3: Cancel token triggers final connection closure with H3_NO_ERROR (0x100)
    cancel_token.cancel();
    h3_handle.await??;

    Ok(())
}

async fn run_h3_draining_server(
    _app: Router,
    _cancel: CancellationToken,
    mut _drain_rx: watch::Receiver<bool>,
) -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
    // Implementation manages Quinn Endpoint, sends stepped GOAWAY frames,
    // and uses JoinSet to await active stream tasks before calling endpoint.close(0x100u32.into(), b"clean shutdown")
    Ok(())
}
```

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 HTTP/3 QUIC Stream Draining & Connection Termination Guardrail

Axum 0.8 HTTP/3 QUIC Stream Draining & Connection Termination Guardrail defines an industrial-grade behavioral standard for backend engineering. Enforces graceful HTTP/3 connection lifecycle management during SIGTERM and rolling updates in Axum 0.8 / Quinn runtimes. Mandates emission of stepped HTTP/3 GOAWAY frames with stream cancellation shields to eliminate drops of in-flight and 0-RTT early-data requests. 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: Abrupt QUIC Endpoint Teardown and Unshielded Tokio Task Aborts on 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 DriftAbrupt QUIC Endpoint Teardown and Unshielded Tokio Task Aborts on 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 implement a two-phase HTTP/3 GOAWAY sequence

Engineers MUST ALWAYS implement a two-phase HTTP/3 GOAWAY sequence: emit an initial GOAWAY with Stream ID 2^62-4 before emitting the final GOAWAY with the highest acknowledged client stream ID.

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 wrap in-flight request processing futures in Tokio cancellation shields or track them in a centralized JoinSet to prevent immediate abort on SIGTERM signal reception.

Engineers MUST wrap in-flight request processing futures in Tokio cancellation shields or track them in a centralized JoinSet to prevent immediate abort on SIGTERM signal reception.

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 configure a deterministic drain timeout budget allowing in-flight 0-RTT streams and pending responses to flush before closing the Quinn endpoint.

Services MUST configure a deterministic drain timeout budget allowing in-flight 0-RTT streams and pending responses to flush before closing the Quinn endpoint.

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

Engineers MUST NOT rely solely on standard TCP graceful shutdown helpers (e.g., axum

Engineers MUST NOT rely solely on standard TCP graceful shutdown helpers (e.g., axum::serve(...).with_graceful_shutdown(...)) for HTTP/3, as UDP/QUIC multiplexed connection semantics are bypassed.

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

Endpoints MUST explicitly close Quinn QUIC connections using application code 0x100 (H3_NO_ERROR) only after all shielded stream tasks have completed or timed out.

Endpoints MUST explicitly close Quinn QUIC connections using application code 0x100 (H3_NO_ERROR) only after all shielded stream tasks have completed or timed out.

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 HTTP/3 QUIC Stream Draining & Connection Termination Guardrail critical for AI coding assistants?

Enforces graceful HTTP/3 connection lifecycle management during SIGTERM and rolling updates in Axum 0.8 / Quinn runtimes. Mandates emission of stepped HTTP/3 GOAWAY frames with stream cancellation shields to eliminate drops of in-flight and 0-RTT early-data requests. 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 (Abrupt QUIC Endpoint Teardown and Unshielded Tokio Task Aborts on 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