This specification is maintained by the AgentRules Working Group. Have enhancements or want to claim maintainership?Submit Specification →
backendcritical PriorityID: axum-graceful-connection-migration-sentinel

Axum Persistent Transport Drain and Connection Migration Sentinel

Mandates coordinated draining and protocol-level handoff for persistent SSE and WebSocket connections during Axum rolling deploys. Enforces RAII connection tracking, shutdown broadcast propagation, and clean frame-level close handshakes (code 1001 Going Away) to prevent client-side socket resets.

Prohibited Anti-Pattern: Abrupt Process Eviction Dropping Active WebSockets and SSE Streams via Socket RST

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Axum Persistent Transport Drain and Connection Migration Sentinel - Mandates coordinated draining and protocol-level handoff for persistent SSE and WebSocket connections during Axum rolling deploys. Enforces RAII connection tracking, shutdown broadcast propagation, and clean frame-level close handshakes (code 1001 Going Away) to prevent client-side socket resets.
globs: src/**/*.rs
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/axum-graceful-connection-migration-sentinel"
---

# Axum Persistent Transport Drain and Connection Migration Sentinel

> **Severity**: CRITICAL | **Category**: backend
> **Anti-Pattern Warning**: Abrupt Process Eviction Dropping Active WebSockets and SSE Streams via Socket RST

## System Constraints
You are a Principal Rust Architect enforcing zero-downtime connection draining standards across Axum services. All persistent HTTP/2 SSE and WebSocket connection lifecycles must be decoupled from bare process signals through coordinated token tracking, protocol-level shutdown frames, and bounded drain timers.

## Strict Guidelines
- Engineers MUST ALWAYS bind persistent connections (WebSocket upgrades, SSE streams) to an application-level drain signal via `tokio_util::sync::CancellationToken` or `tokio::sync::watch`.
- Engineers MUST track all active persistent connections using RAII guards or `tokio_util::task::TaskTracker` to guarantee deterministic drain accounting during graceful shutdown.
- WebSocket handlers MUST send an explicit `CloseFrame` with code `1001 (Going Away)` and await sink flush before terminating upon receiving the drain signal.
- SSE handlers MUST emit a terminal event or a renegotiation `retry:` directive prior to ending the stream during pod evacuation.
- The service shutdown sequence MUST enforce a bounded drain timeout with `tokio::time::timeout` before forcing termination, allowing existing sessions to finish or reconnect cleanly.
- Handlers MUST NEVER rely solely on bare TCP teardown or OS process termination (SIGTERM), which causes `ECONNRESET` cascades in client applications.

## Bad vs Good Implementations
### Axum WebSocket Shutdown Handling

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: The WebSocket loop is detached from the server's lifecycle. When SIGTERM is received, the server exits or drops the connection abruptly without sending a WebSocket close frame, resulting in dropped frames and broken socket errors on the client side.
```rust
use axum::{extract::ws::{WebSocket, WebSocketUpgrade}, response::IntoResponse};

pub async fn ws_handler(ws: WebSocketUpgrade) -> impl IntoResponse {
    ws.on_upgrade(|mut socket| async move {
        // BAD: Loops indefinitely with no awareness of server drain signal
        // When pod is evicted, process drops socket immediately, causing ECONNRESET
        while let Some(Ok(msg)) = socket.recv().await {
            if socket.send(msg).await.is_err() {
                break;
            }
        }
    })
}
```

#### Production Standard (Correct)
> **Standard**: The good example integrates the WebSocket session into a `TaskTracker` and selects against a `CancellationToken`. Upon shutdown signal reception, it negotiates a clean close frame (CloseCode 1001) before dropping the socket, allowing client connection migration without errors.
```rust
use axum::{extract::{ws::{close_code, CloseFrame, Message, WebSocket}, State, WebSocketUpgrade}, response::IntoResponse};
use std::sync::Arc;
use tokio_util::sync::CancellationToken;
use tokio_util::task::TaskTracker;

#[derive(Clone)]
pub struct AppState {
    pub drain_token: CancellationToken,
    pub tracker: TaskTracker,
}

pub async fn ws_handler(ws: WebSocketUpgrade, State(state): State<Arc<AppState>>) -> impl IntoResponse {
    ws.on_upgrade(move |mut socket| {
        let drain_token = state.drain_token.clone();
        state.tracker.track_future(async move {
            loop {
                tokio::select! {
                    _ = drain_token.cancelled() => {
                        // Send protocol-level 1001 Going Away close frame
                        let close_frame = CloseFrame {
                            code: close_code::AWAY,
                            reason: "Service deploying: please reconnect".into(),
                        };
                        let _ = socket.send(Message::Close(Some(close_frame))).await;
                        let _ = socket.close().await;
                        break;
                    }
                    msg = socket.recv() => {
                        match msg {
                            Some(Ok(Message::Close(_))) | None => break,
                            Some(Ok(m)) => { if socket.send(m).await.is_err() { break; } }
                            Some(Err(_)) => 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 Persistent Transport Drain and Connection Migration Sentinel

Axum Persistent Transport Drain and Connection Migration Sentinel defines an industrial-grade behavioral standard for backend engineering. Mandates coordinated draining and protocol-level handoff for persistent SSE and WebSocket connections during Axum rolling deploys. Enforces RAII connection tracking, shutdown broadcast propagation, and clean frame-level close handshakes (code 1001 Going Away) to prevent client-side socket resets. 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 Process Eviction Dropping Active WebSockets and SSE Streams via Socket 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 DriftAbrupt Process Eviction Dropping Active WebSockets and SSE Streams via Socket 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 bind persistent connections (WebSocket upgrades, SSE streams) to an application-level drain signal via `tokio_util

Engineers MUST ALWAYS bind persistent connections (WebSocket upgrades, SSE streams) to an application-level drain signal via `tokio_util::sync::CancellationToken` or `tokio::sync::watch`.

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 track all active persistent connections using RAII guards or `tokio_util

Engineers MUST track all active persistent connections using RAII guards or `tokio_util::task::TaskTracker` to guarantee deterministic drain accounting during graceful shutdown.

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 send an explicit `CloseFrame` with code `1001 (Going Away)` and await sink flush before terminating upon receiving the drain signal.

WebSocket handlers MUST send an explicit `CloseFrame` with code `1001 (Going Away)` and await sink flush before terminating upon receiving the drain signal.

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 emit a terminal event or a renegotiation `retry

SSE handlers MUST emit a terminal event or a renegotiation `retry:` directive prior to ending the stream during pod evacuation.

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

The service shutdown sequence MUST enforce a bounded drain timeout with `tokio

The service shutdown sequence MUST enforce a bounded drain timeout with `tokio::time::timeout` before forcing termination, allowing existing sessions to finish or reconnect cleanly.

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

Handlers MUST NEVER rely solely on bare TCP teardown or OS process termination (SIGTERM), which causes `ECONNRESET` cascades in client applications.

Handlers MUST NEVER rely solely on bare TCP teardown or OS process termination (SIGTERM), which causes `ECONNRESET` cascades in client applications.

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 Persistent Transport Drain and Connection Migration Sentinel critical for AI coding assistants?

Mandates coordinated draining and protocol-level handoff for persistent SSE and WebSocket connections during Axum rolling deploys. Enforces RAII connection tracking, shutdown broadcast propagation, and clean frame-level close handshakes (code 1001 Going Away) to prevent client-side socket resets. 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 Process Eviction Dropping Active WebSockets and SSE Streams via Socket 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