This specification is maintained by the AgentRules Working Group. Have enhancements or want to claim maintainership?Submit Specification →
backendcritical PriorityID: axum-h3-quic-graceful-draining-invariant

Axum 0.8 HTTP/3 QUIC Graceful Connection Draining Invariant

Enforces structured bidirectional QUIC stream retirement and RFC 9114 HTTP/3 GOAWAY mechanics during server teardown in Axum 0.8 environments. Guarantees zero-downtime canary transitions by preventing abrupt QUIC stream resets (RESET_STREAM or sudden CONNECTION_CLOSE) through phased stream count signaling and Tokio cancellation-safe connection draining.

Prohibited Anti-Pattern: Immediate Tokio Runtime Dropping and Uncoordinated QUIC Connection Teardown on SIGTERM

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Axum 0.8 HTTP/3 QUIC Graceful Connection Draining Invariant - Enforces structured bidirectional QUIC stream retirement and RFC 9114 HTTP/3 GOAWAY mechanics during server teardown in Axum 0.8 environments. Guarantees zero-downtime canary transitions by preventing abrupt QUIC stream resets (RESET_STREAM or sudden CONNECTION_CLOSE) through phased stream count signaling and Tokio cancellation-safe connection draining.
globs: src/**/*.rs, crates/**/*.rs
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/axum-h3-quic-graceful-draining-invariant"
---

# Axum 0.8 HTTP/3 QUIC Graceful Connection Draining Invariant

> **Severity**: CRITICAL | **Category**: backend
> **Anti-Pattern Warning**: Immediate Tokio Runtime Dropping and Uncoordinated QUIC Connection Teardown on SIGTERM

## System Constraints
You are a Principal Systems Architect enforcing Axum 0.8 HTTP/3 and QUIC zero-downtime connection draining invariants. Mandate RFC 9114 phased GOAWAY signaling, strict Tokio cancellation safety during shutdown sweeps, and bounded stream retirement.

## Strict Guidelines
- Engineers MUST ALWAYS execute a two-phase HTTP/3 GOAWAY sequence upon receiving shutdown signals: emit an initial advisory GOAWAY with maximum stream ID (2^62 - 4) to stop new stream creation, wait for in-flight requests to settle across at least one RTT, then emit a definitive GOAWAY with the actual final stream ID.
- Engineers MUST NOT abruptly drop Quinn/h3 connection or endpoint futures inside a `tokio::select!` branch, as dropping in-flight bidirectional stream drivers triggers ungraceful RESET_STREAM frames and drops active customer requests.
- Code MUST employ `tokio_util::sync::CancellationToken` and tracking structures (such as `tokio::sync::watch` or atomic stream tallies) to decouple shutdown signal acquisition from QUIC stream executor termination.
- Services MUST enforce a bounded grace period timeout (e.g., via `tokio::time::timeout`) around connection draining, after which connections send a clean `H3_NO_ERROR` CONNECTION_CLOSE instead of dropping the socket without notification.
- Components NEVER treat HTTP/3 connections identically to HTTP/1.1 or HTTP/2 TCP sockets; connection lifecycles are stateful UDP endpoints where stream multiplexing requires separate transport and application teardown synchronization.

## Bad vs Good Implementations
### Graceful Two-Stage QUIC Stream Draining vs Abrupt Drop in Axum 0.8 / h3

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Abruptly exiting the Tokio task scope drops the QUIC endpoint and connection handlers. In-flight bidirectional streams are abruptly severed without sending GOAWAY frames, causing visible connection errors (e.g. ERR_QUIC_PROTOCOL_ERROR or HTTP_1_1_REQUIRED fallbacks) in client traffic during canary updates.
```rust
use tokio::net::UdpSocket;

pub async fn run_server(endpoint: quinn::Endpoint) {
    tokio::select! {
        _ = serve_quic(endpoint) => {},
        _ = tokio::signal::ctrl_c() => {
            // CRITICAL ANTI-PATTERN: Dropping the endpoint and active connections immediately
            // emits stateless resets or drops UDP traffic without RFC 9114 GOAWAY sequences.
            // Active in-flight HTTP/3 requests in the canary deployment are immediately aborted.
            tracing::info!("SIGINT received, killing HTTP/3 endpoint immediately");
        }
    }
}

async fn serve_quic(_endpoint: quinn::Endpoint) {
    // Stream handling without tracking active stream counts or shutdown hooks
}
```

#### Production Standard (Correct)
> **Standard**: Decouples shutdown signalling using CancellationToken, triggers transport close and HTTP/3 GOAWAY frames, tracks outstanding streams atomically, and gracefully waits for in-flight streams to complete up to a deterministic timeout before terminating the endpoint.
```rust
use std::sync::atomic::{AtomicUsize, Ordering};
use std::sync::Arc;
use std::time::Duration;
use tokio::sync::watch;
use tokio_util::sync::CancellationToken;

pub struct ServerMetrics {
    pub active_streams: AtomicUsize,
}

pub async fn run_server_graceful(
    endpoint: quinn::Endpoint,
    cancel_token: CancellationToken,
) -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
    let (drain_tx, mut drain_rx) = watch::channel(false);
    let metrics = Arc::new(ServerMetrics { active_streams: AtomicUsize::new(0) });

    // Main accept loop decoupled from cancel token via explicit drain signal
    let endpoint_handle = endpoint.clone();
    let server_metrics = Arc::clone(&metrics);
    
    tokio::spawn(async move {
        cancel_token.cancelled().await;
        tracing::info!("Shutdown signal received: initiating HTTP/3 GOAWAY countdown");
        
        // Step 1: Notify all active connections to issue advisory GOAWAY (RFC 9114 §5.2)
        let _ = drain_tx.send(true);
        
        // Step 2: Stop accepting new incoming QUIC handshakes at transport layer
        endpoint_handle.close(0u32.into(), b"Server Shutting Down");
    });

    // Bounded drain window for in-flight streams
    let drain_timeout = Duration::from_secs(30);
    let drain_started = tokio::time::Instant::now();

    while metrics.active_streams.load(Ordering::Acquire) > 0 {
        if drain_started.elapsed() > drain_timeout {
            tracing::warn!("HTTP/3 connection drain timeout exceeded; forcing final closure");
            break;
        }
        tokio::time::sleep(Duration::from_millis(100)).await;
    }

    endpoint.wait_idle().await;
    tracing::info!("HTTP/3 QUIC connection draining completed cleanly");
    Ok(())
}
```

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 Graceful Connection Draining Invariant

Axum 0.8 HTTP/3 QUIC Graceful Connection Draining Invariant defines an industrial-grade behavioral standard for backend engineering. Enforces structured bidirectional QUIC stream retirement and RFC 9114 HTTP/3 GOAWAY mechanics during server teardown in Axum 0.8 environments. Guarantees zero-downtime canary transitions by preventing abrupt QUIC stream resets (RESET_STREAM or sudden CONNECTION_CLOSE) through phased stream count signaling and Tokio cancellation-safe connection draining. 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 Tokio Runtime Dropping and Uncoordinated QUIC Connection Teardown 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 DriftImmediate Tokio Runtime Dropping and Uncoordinated QUIC Connection Teardown 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 execute a two-phase HTTP/3 GOAWAY sequence upon receiving shutdown signals

Engineers MUST ALWAYS execute a two-phase HTTP/3 GOAWAY sequence upon receiving shutdown signals: emit an initial advisory GOAWAY with maximum stream ID (2^62 - 4) to stop new stream creation, wait for in-flight requests to settle across at least one RTT, then emit a definitive GOAWAY with the actual final 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 NOT abruptly drop Quinn/h3 connection or endpoint futures inside a `tokio

Engineers MUST NOT abruptly drop Quinn/h3 connection or endpoint futures inside a `tokio::select!` branch, as dropping in-flight bidirectional stream drivers triggers ungraceful RESET_STREAM frames and drops active customer requests.

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 employ `tokio_util

Code MUST employ `tokio_util::sync::CancellationToken` and tracking structures (such as `tokio::sync::watch` or atomic stream tallies) to decouple shutdown signal acquisition from QUIC stream executor termination.

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 enforce a bounded grace period timeout (e.g., via `tokio

Services MUST enforce a bounded grace period timeout (e.g., via `tokio::time::timeout`) around connection draining, after which connections send a clean `H3_NO_ERROR` CONNECTION_CLOSE instead of dropping the socket without notification.

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 treat HTTP/3 connections identically to HTTP/1.1 or HTTP/2 TCP sockets

Components NEVER treat HTTP/3 connections identically to HTTP/1.1 or HTTP/2 TCP sockets; connection lifecycles are stateful UDP endpoints where stream multiplexing requires separate transport and application teardown synchronization.

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 Graceful Connection Draining Invariant critical for AI coding assistants?

Enforces structured bidirectional QUIC stream retirement and RFC 9114 HTTP/3 GOAWAY mechanics during server teardown in Axum 0.8 environments. Guarantees zero-downtime canary transitions by preventing abrupt QUIC stream resets (RESET_STREAM or sudden CONNECTION_CLOSE) through phased stream count signaling and Tokio cancellation-safe connection draining. 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 Tokio Runtime Dropping and Uncoordinated QUIC Connection Teardown 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