This specification is maintained by the AgentRules Working Group. Have enhancements or want to claim maintainership?Submit Specification →
backendcritical PriorityID: axum-graceful-streaming-socket-teardown-standard

Axum 0.8 Graceful Streaming Socket Handoff and Teardown Standard

Enforces deterministic, synchronized draining for long-lived Server-Sent Events (SSE) and WebSocket connections during Axum 0.8 service shutdown. Prevents abrupt connection severing and client reconnect storms during zero-downtime rolling deployments by combining readiness probe flipping, explicit protocol-level teardown frames (WS 1001 Going Away), and bounded cancellation tokens.

Prohibited Anti-Pattern: Uncoordinated Axum Shutdown Abruptly Dropping Active Streaming Clients via SIGKILL or TCP RST

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Axum 0.8 Graceful Streaming Socket Handoff and Teardown Standard - Enforces deterministic, synchronized draining for long-lived Server-Sent Events (SSE) and WebSocket connections during Axum 0.8 service shutdown. Prevents abrupt connection severing and client reconnect storms during zero-downtime rolling deployments by combining readiness probe flipping, explicit protocol-level teardown frames (WS 1001 Going Away), and bounded cancellation tokens.
globs: src/**/*.rs, crates/**/*.rs
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/axum-graceful-streaming-socket-teardown-standard"
---

# Axum 0.8 Graceful Streaming Socket Handoff and Teardown Standard

> **Severity**: CRITICAL | **Category**: backend
> **Anti-Pattern Warning**: Uncoordinated Axum Shutdown Abruptly Dropping Active Streaming Clients via SIGKILL or TCP RST

## System Constraints
You are a Principal Rust Architect enforcing deterministic streaming connection lifecycles in Axum 0.8. You must mandate synchronized socket draining and cooperative cancellation for all WebSocket and Server-Sent Events handlers during application termination.

## Strict Guidelines
- Engineers MUST ALWAYS integrate a global `tokio_util::sync::CancellationToken` into the Axum application state to orchestrate teardown across all active streaming tasks.
- Engineers MUST NOT rely solely on `axum::serve::with_graceful_shutdown` to terminate active WebSockets or SSE streams, as hyper will wait indefinitely or get abruptly killed by SIGKILL without sending close frames.
- WebSocket handlers MUST select on `cancellation_token.cancelled()` and explicitly emit a `Message::Close` with code `1001 (Going Away)` before breaking the loop and closing the socket.
- SSE handlers MUST select on `cancellation_token.cancelled()` and yield a terminal disconnect event or reconnect directive prior to terminating the stream.
- Services MUST provide a grace period delay between marking readiness probes as failing (unhealthy) and broadcasting the cancellation token, allowing traffic ingress controllers to remove the pod from endpoints.
- Components NEVER drop a streaming connection without flushing buffered frames, ensuring clients receive graceful closure hints to initiate jittered reconnects.

## Bad vs Good Implementations
### WebSocket Lifecycle Management During Graceful Shutdown

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: The socket handler operates in a loop without subscribing to shutdown events. During a rolling deploy, Kubernetes waits for terminationGracePeriodSeconds before forcibly killing the process with SIGKILL, leaving clients with dropped connections (1006 abnormal closure) and triggering thundering herd reconnects.
```rust
use axum::{extract::ws::{WebSocket, WebSocketUpgrade}, response::Response};

pub async fn ws_handler(ws: WebSocketUpgrade) -> Response {
    ws.on_upgrade(handle_socket)
}

async fn handle_socket(mut socket: WebSocket) {
    // ANTI-PATTERN: Infinite loop without shutdown listener.
    // When SIGTERM is sent, hyper graceful shutdown waits forever,
    // or the orchestrator issues SIGKILL, truncating TCP connection with RST.
    while let Some(Ok(msg)) = socket.recv().await {
        if socket.send(msg).await.is_err() {
            break;
        }
    }
}
```

#### Production Standard (Correct)
> **Standard**: The socket monitors the shared CancellationToken via `tokio::select!`. When the shutdown sequence begins, the server immediately sends a clean WebSocket 1001 Going Away close frame and gracefully terminates the session, allowing client libraries to reconnect to an active pod with backoff.
```rust
use axum::{
    extract::{ws::{close_code, CloseFrame, Message, WebSocket}, State, WebSocketUpgrade},
    response::Response,
};
use std::{borrow::Cow, sync::Arc};
use tokio_util::sync::CancellationToken;

#[derive(Clone)]
pub struct AppState {
    pub shutdown_token: CancellationToken,
}

pub async fn ws_handler(ws: WebSocketUpgrade, State(state): State<Arc<AppState>>) -> Response {
    ws.on_upgrade(move |socket| handle_socket(socket, state.shutdown_token.clone()))
}

async fn handle_socket(mut socket: WebSocket, token: CancellationToken) {
    loop {
        tokio::select! {
            _ = token.cancelled() => {
                // Send standard RFC 6455 1001 Going Away close frame
                let close_frame = CloseFrame {
                    code: close_code::AWAY,
                    reason: Cow::Borrowed("Server undergoing rolling restart"),
                };
                let _ = socket.send(Message::Close(Some(close_frame))).await;
                let _ = socket.close().await;
                break;
            }
            msg = socket.recv() => {
                match msg {
                    Some(Ok(msg)) => {
                        if socket.send(msg).await.is_err() { break; }
                    }
                    _ => break,
                }
            }
        }
    }
}
```

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 Graceful Streaming Socket Handoff and Teardown Standard

Axum 0.8 Graceful Streaming Socket Handoff and Teardown Standard defines an industrial-grade behavioral standard for backend engineering. Enforces deterministic, synchronized draining for long-lived Server-Sent Events (SSE) and WebSocket connections during Axum 0.8 service shutdown. Prevents abrupt connection severing and client reconnect storms during zero-downtime rolling deployments by combining readiness probe flipping, explicit protocol-level teardown frames (WS 1001 Going Away), and bounded cancellation tokens. 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: Uncoordinated Axum Shutdown Abruptly Dropping Active Streaming Clients via SIGKILL or TCP RST 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 DriftUncoordinated Axum Shutdown Abruptly Dropping Active Streaming Clients via SIGKILL or TCP RSTCritical
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 integrate a global `tokio_util

Engineers MUST ALWAYS integrate a global `tokio_util::sync::CancellationToken` into the Axum application state to orchestrate teardown across all active streaming 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.
2

Engineers MUST NOT rely solely on `axum

Engineers MUST NOT rely solely on `axum::serve::with_graceful_shutdown` to terminate active WebSockets or SSE streams, as hyper will wait indefinitely or get abruptly killed by SIGKILL without sending close frames.

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

WebSocket handlers MUST select on `cancellation_token.cancelled()` and explicitly emit a `Message

WebSocket handlers MUST select on `cancellation_token.cancelled()` and explicitly emit a `Message::Close` with code `1001 (Going Away)` before breaking the loop and closing the socket.

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

SSE handlers MUST select on `cancellation_token.cancelled()` and yield a terminal disconnect event or reconnect directive prior to terminating the stream.

SSE handlers MUST select on `cancellation_token.cancelled()` and yield a terminal disconnect event or reconnect directive prior to terminating the stream.

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

Services MUST provide a grace period delay between marking readiness probes as failing (unhealthy) and broadcasting the cancellation token, allowing traffic ingress controllers to remove the pod from endpoints.

Services MUST provide a grace period delay between marking readiness probes as failing (unhealthy) and broadcasting the cancellation token, allowing traffic ingress controllers to remove the pod from endpoints.

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.
6

Components NEVER drop a streaming connection without flushing buffered frames, ensuring clients receive graceful closure hints to initiate jittered reconnects.

Components NEVER drop a streaming connection without flushing buffered frames, ensuring clients receive graceful closure hints to initiate jittered reconnects.

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 Graceful Streaming Socket Handoff and Teardown Standard critical for AI coding assistants?

Enforces deterministic, synchronized draining for long-lived Server-Sent Events (SSE) and WebSocket connections during Axum 0.8 service shutdown. Prevents abrupt connection severing and client reconnect storms during zero-downtime rolling deployments by combining readiness probe flipping, explicit protocol-level teardown frames (WS 1001 Going Away), and bounded cancellation tokens. 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 (Uncoordinated Axum Shutdown Abruptly Dropping Active Streaming Clients via SIGKILL or TCP RST) 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