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

Axum 0.8 HTTP/3 & QUIC Multiplexed Stream Graceful Drain Standard

Enforces zero-loss termination of in-flight QUIC bidirectional streams and HTTP/3 frames during continuous orchestrator rolling updates. Mandates two-phase shutdown via GOAWAY frame broadcasting, unbinding incoming connection listeners, and explicit stream join coordination via token-gated timeouts before Quinn/s2n-quic endpoint disposal.

Prohibited Anti-Pattern: Abrupt QUIC Endpoint Drop and Ungraceful Process Exit Dropping Active Multiplexed HTTP/3 Streams on SIGTERM

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Axum 0.8 HTTP/3 & QUIC Multiplexed Stream Graceful Drain Standard - Enforces zero-loss termination of in-flight QUIC bidirectional streams and HTTP/3 frames during continuous orchestrator rolling updates. Mandates two-phase shutdown via GOAWAY frame broadcasting, unbinding incoming connection listeners, and explicit stream join coordination via token-gated timeouts before Quinn/s2n-quic endpoint disposal.
globs: src/**/*.rs, crates/**/*.rs
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/axum-0-8-h3-multiplex-graceful-drain"
---

# Axum 0.8 HTTP/3 & QUIC Multiplexed Stream Graceful Drain Standard

> **Severity**: CRITICAL | **Category**: backend
> **Anti-Pattern Warning**: Abrupt QUIC Endpoint Drop and Ungraceful Process Exit Dropping Active Multiplexed HTTP/3 Streams on SIGTERM

## System Constraints
You are a Principal Systems Architect enforcing the Axum 0.8 Multiplexed HTTP/3 Stream Graceful Drain Standard. You must reject any implementation that abruptly drops QUIC UDP listeners or terminates Axum tasks on OS signals without coordinated HTTP/3 GOAWAY frames and active stream counter draining.

## Strict Guidelines
- Services MUST implement a two-phase drain sequence: (1) stop accepting new QUIC connections/streams and transmit HTTP/3 GOAWAY with maximal stream IDs, (2) await inflight stream completion bounded by an explicit orchestrator termination deadline.
- Engineers MUST NOT drop the underlying QUIC `Endpoint` or terminate the Tokio runtime until all active bidirectional HTTP/3 stream handlers have completed or timed out.
- Engineers MUST track in-flight streams using atomic stream counters, `tokio_util::sync::CancellationToken`, or `tokio::sync::watch` channels across all connection tasks.
- Services MUST coordinate with orchestrator pod lifecycle: set drain timeout to `terminationGracePeriodSeconds` minus safe propagation margin (minimum 5s margin for kube-proxy/ingress iptables convergence).
- Components NEVER call `std::process::exit` or invoke unmanaged task cancellation (`AbortHandle::abort`) on active HTTP/3 request handlers.

## Bad vs Good Implementations
### HTTP/3 and QUIC Graceful Stream Drain Implementation

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Directly binding and relying on standard TCP-only teardown ignores the stateful UDP/QUIC multiplexing layer. On SIGTERM, underlying UDP sockets and tasks are dropped instantly without emitting HTTP/3 GOAWAY frames, causing in-flight streaming uploads/downloads to fail abruptly with QUIC transport errors.
```rust
use axum::{routing::get, Router};
use tokio::signal;

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let app = Router::new().route("/", get(|| async { "ok" }));
    
    // ANTI-PATTERN: Standard bind without QUIC stream coordination.
    // On SIGTERM, the endpoint task is dropped instantly, dropping inflight
    // QUIC bidirectional streams and triggering CONNECTION_REFUSED / RESET_STREAM
    // on client connections during rolling updates.
    let listener = tokio::net::TcpListener::bind("0.0.0.0:3000").await?;
    axum::serve(listener, app)
        .with_graceful_shutdown(async {
            signal::ctrl_c().await.ok();
            // Instant exit - in-flight multiplexed streams severed instantly
        })
        .await?;
        
    Ok(())
}
```

#### Production Standard (Correct)
> **Standard**: Implements an explicit two-phase drain sequence. When SIGTERM is received, phase 1 stops accepting new QUIC connections and issues GOAWAY frames, while phase 2 gracefully awaits in-flight stream completion bounded by a deterministic timeout safely below Kubernetes terminationGracePeriodSeconds.
```rust
use axum::{routing::get, Router};
use std::{sync::Arc, time::Duration};
use tokio::{signal::unix::{signal, SignalKind}, sync::watch, time::timeout};
use tokio_util::sync::CancellationToken;

#[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 inflight_streams = Arc::new(std::sync::atomic::AtomicUsize::new(0));

    let app = Router::new().route("/", get(|| async { "ok" }));

    // Setup SIGTERM handling for Kubernetes pod lifecycles
    let mut sigterm = signal(SignalKind::terminate())?;
    let drain_token = cancel_token.clone();
    
    tokio::spawn(async move {
        sigterm.recv().await;
        tracing::info!("SIGTERM received: initiating phase 1 QUIC/H3 drain (GOAWAY)");
        // Phase 1: Notify listener to stop accepting connections and broadcast H3 GOAWAY
        let _ = drain_tx.send(true);
        drain_token.cancel();
    });

    // Listener drain coordination
    let drain_deadline = Duration::from_secs(25); // Set < pod terminationGracePeriodSeconds (e.g., 30s)
    
    // Simulated Axum / QUIC server execution loop
    tokio::select! {
        _ = cancel_token.cancelled() => {
            tracing::info!("Phase 2: Waiting for in-flight streams to complete");
            let drain_result = timeout(drain_deadline, async {
                while inflight_streams.load(std::sync::atomic::Ordering::Acquire) > 0 {
                    tokio::time::sleep(Duration::from_millis(100)).await;
                }
            }).await;

            if drain_result.is_err() {
                tracing::warn!("Drain deadline reached; forcing close of dangling QUIC streams");
            }
        }
    }

    tracing::info!("QUIC endpoint drained cleanly; exiting runtime");
    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 Multiplexed Stream Graceful Drain Standard

Axum 0.8 HTTP/3 & QUIC Multiplexed Stream Graceful Drain Standard defines an industrial-grade behavioral standard for backend engineering. Enforces zero-loss termination of in-flight QUIC bidirectional streams and HTTP/3 frames during continuous orchestrator rolling updates. Mandates two-phase shutdown via GOAWAY frame broadcasting, unbinding incoming connection listeners, and explicit stream join coordination via token-gated timeouts before Quinn/s2n-quic endpoint disposal. 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 Drop and Ungraceful Process Exit Dropping Active Multiplexed HTTP/3 Streams 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 Drop and Ungraceful Process Exit Dropping Active Multiplexed HTTP/3 Streams 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

Services MUST implement a two-phase drain sequence

Services MUST implement a two-phase drain sequence: (1) stop accepting new QUIC connections/streams and transmit HTTP/3 GOAWAY with maximal stream IDs, (2) await inflight stream completion bounded by an explicit orchestrator termination deadline.

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 underlying QUIC `Endpoint` or terminate the Tokio runtime until all active bidirectional HTTP/3 stream handlers have completed or timed out.

Engineers MUST NOT drop the underlying QUIC `Endpoint` or terminate the Tokio runtime until all active bidirectional HTTP/3 stream handlers 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.
3

Engineers MUST track in-flight streams using atomic stream counters, `tokio_util

Engineers MUST track in-flight streams using atomic stream counters, `tokio_util::sync::CancellationToken`, or `tokio::sync::watch` channels across all connection tasks.

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 with orchestrator pod lifecycle

Services MUST coordinate with orchestrator pod lifecycle: set drain timeout to `terminationGracePeriodSeconds` minus safe propagation margin (minimum 5s margin for kube-proxy/ingress iptables convergence).

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

Components NEVER call `std::process::exit` or invoke unmanaged task cancellation (`AbortHandle::abort`) on active HTTP/3 request handlers.

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 Multiplexed Stream Graceful Drain Standard critical for AI coding assistants?

Enforces zero-loss termination of in-flight QUIC bidirectional streams and HTTP/3 frames during continuous orchestrator rolling updates. Mandates two-phase shutdown via GOAWAY frame broadcasting, unbinding incoming connection listeners, and explicit stream join coordination via token-gated timeouts before Quinn/s2n-quic endpoint disposal. 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 Drop and Ungraceful Process Exit Dropping Active Multiplexed HTTP/3 Streams 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