This specification is maintained by the AgentRules Working Group. Have enhancements or want to claim maintainership?Submit Specification →
backendcritical PriorityID: axum-08-websocket-heartbeat-desync-guardrail

Axum 0.8 WebSocket Heartbeat & Task Desynchronization Invariant

Enforces deterministic bidirectional heartbeat polling and cooperative Tokio task cancellation for Axum 0.8 WebSocket connections. Eliminates silent file descriptor exhaustion, zombie connection accumulation, and unhandled task panics caused by asymmetric split-stream teardowns during edge reverse proxy failovers and rolling deploys.

Prohibited Anti-Pattern: Asymmetric Split Tasks with Detached Ping Loops and Missing Pong Verification

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Axum 0.8 WebSocket Heartbeat & Task Desynchronization Invariant - Enforces deterministic bidirectional heartbeat polling and cooperative Tokio task cancellation for Axum 0.8 WebSocket connections. Eliminates silent file descriptor exhaustion, zombie connection accumulation, and unhandled task panics caused by asymmetric split-stream teardowns during edge reverse proxy failovers and rolling deploys.
globs: src/**/*.rs, crates/**/*.rs
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/axum-08-websocket-heartbeat-desync-guardrail"
---

# Axum 0.8 WebSocket Heartbeat & Task Desynchronization Invariant

> **Severity**: CRITICAL | **Category**: backend
> **Anti-Pattern Warning**: Asymmetric Split Tasks with Detached Ping Loops and Missing Pong Verification

## System Constraints
You are a Principal Rust Concurrency Architect enforcing strict lifecycle guarantees for Axum 0.8 WebSocket connections. You must strictly forbid detached, uncoordinated Tokio read/write tasks that lack shared cancellation tokens, monotonic heartbeat deadline tracking, and bounded backpressure. Mandate unified event-loop patterns or coupled cooperative cancellation to prevent zombie connection pools during edge proxy failovers.

## Strict Guidelines
- Engineers MUST ALWAYS coordinate WebSocket reader and writer routines via a unified `tokio::select!` loop or linked `tokio_util::sync::CancellationToken` instances.
- Engineers MUST ALWAYS verify incoming `Message::Pong` frames and compute monotonic elapsed deadlines (`std::time::Instant`) rather than assuming blind ping delivery guarantees client liveness.
- Engineers MUST NOT spawn unbounded, detached Tokio tasks (`tokio::spawn`) from Axum WebSocket handlers without tracking JoinHandles or binding abort guards.
- Services MUST intercept application shutdown signals (SIGINT/SIGTERM) and dispatch cooperative `Message::Close` frames with bounded timeouts prior to socket termination.
- Components NEVER use unbounded channels (`tokio::sync::mpsc::unbounded_channel`) for outbound WebSocket frame buffering; bounded channels with calibrated capacity MUST be enforced.

## Bad vs Good Implementations
### Naive Detached Read/Write Tasks vs. Unified Select with Monotonic Heartbeat Tracking

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Splitting the socket into two detached, uncoordinated Tokio tasks leaves the write loop running indefinitely if the client silently drops connection without sending TCP FIN/RST. Pings are emitted blindly with zero verification of client pong reception, accumulating dead tasks, pinned buffers, and leaked file descriptors across rolling deploys.
```rust
use axum::extract::ws::{Message, WebSocket};
use futures_util::{SinkExt, StreamExt};
use tokio::time::{interval, Duration};

// ANTI-PATTERN: Detached tasks cause zombie sockets on TCP drop;
// unverified pings cause silent FD exhaustion behind reverse proxies.
pub async fn handle_socket(socket: WebSocket) {
    let (mut sender, mut receiver) = socket.split();

    // Detached writer: Never terminates if receiver drops or client vanishes
    tokio::spawn(async move {
        let mut ping_interval = interval(Duration::from_secs(15));
        loop {
            ping_interval.tick().await;
            // Blind pinging without checking pong responses
            let _ = sender.send(Message::Ping(vec![].into())).await;
        }
    });

    // Detached reader: Blocks forever on dead half-open TCP connections
    tokio::spawn(async move {
        while let Some(Ok(msg)) = receiver.next().await {
            if let Message::Text(text) = msg {
                println!("Received: {text}");
            }
        }
    });
}
```

#### Production Standard (Correct)
> **Standard**: Unifies stream reading, ping frame emission, and pong verification under a single biased `tokio::select!` block. Enforces a strict monotonic timeout deadline (`CLIENT_TIMEOUT`) that actively severs connections if edge proxies or clients stop acknowledging heartbeats, while gracefully flushing `Message::Close` frames upon SIGTERM reception.
```rust
use axum::extract::ws::{Message, WebSocket};
use futures_util::{SinkExt, StreamExt};
use std::time::Instant;
use tokio::time::{interval, Duration};
use tokio_util::sync::CancellationToken;

const HEARTBEAT_INTERVAL: Duration = Duration::from_secs(15);
const CLIENT_TIMEOUT: Duration = Duration::from_secs(35);

// PRODUCTION INVARIANT: Coordinated select loop with deadline enforcement & shutdown hooks
pub async fn handle_socket(socket: WebSocket, shutdown: CancellationToken) {
    let (mut sink, mut stream) = socket.split();
    let mut ticker = interval(HEARTBEAT_INTERVAL);
    let mut last_pong = Instant::now();

    loop {
        tokio::select! {
            biased;

            _ = shutdown.cancelled() => {
                let _ = sink.send(Message::Close(None)).await;
                break;
            }
            _ = ticker.tick() => {
                if last_pong.elapsed() > CLIENT_TIMEOUT {
                    // Client missed heartbeat deadline; abort zombie connection
                    let _ = sink.send(Message::Close(None)).await;
                    break;
                }
                if sink.send(Message::Ping(vec![].into())).await.is_err() {
                    break;
                }
            }
            msg = stream.next() => {
                match msg {
                    Some(Ok(Message::Pong(_))) => {
                        last_pong = Instant::now();
                    }
                    Some(Ok(Message::Close(_))) | None => break,
                    Some(Ok(Message::Text(payload))) => {
                        let _ = payload;
                    }
                    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 0.8 WebSocket Heartbeat & Task Desynchronization Invariant

Axum 0.8 WebSocket Heartbeat & Task Desynchronization Invariant defines an industrial-grade behavioral standard for backend engineering. Enforces deterministic bidirectional heartbeat polling and cooperative Tokio task cancellation for Axum 0.8 WebSocket connections. Eliminates silent file descriptor exhaustion, zombie connection accumulation, and unhandled task panics caused by asymmetric split-stream teardowns during edge reverse proxy failovers and rolling deploys. 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: Asymmetric Split Tasks with Detached Ping Loops and Missing Pong Verification 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 DriftAsymmetric Split Tasks with Detached Ping Loops and Missing Pong VerificationCritical
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 coordinate WebSocket reader and writer routines via a unified `tokio

Engineers MUST ALWAYS coordinate WebSocket reader and writer routines via a unified `tokio::select!` loop or linked `tokio_util::sync::CancellationToken` instances.

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 ALWAYS verify incoming `Message

Engineers MUST ALWAYS verify incoming `Message::Pong` frames and compute monotonic elapsed deadlines (`std::time::Instant`) rather than assuming blind ping delivery guarantees client liveness.

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 NOT spawn unbounded, detached Tokio tasks (`tokio

Engineers MUST NOT spawn unbounded, detached Tokio tasks (`tokio::spawn`) from Axum WebSocket handlers without tracking JoinHandles or binding abort guards.

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 intercept application shutdown signals (SIGINT/SIGTERM) and dispatch cooperative `Message

Services MUST intercept application shutdown signals (SIGINT/SIGTERM) and dispatch cooperative `Message::Close` frames with bounded timeouts prior to socket 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.
5

Components NEVER use unbounded channels (`tokio

Components NEVER use unbounded channels (`tokio::sync::mpsc::unbounded_channel`) for outbound WebSocket frame buffering; bounded channels with calibrated capacity MUST be enforced.

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 WebSocket Heartbeat & Task Desynchronization Invariant critical for AI coding assistants?

Enforces deterministic bidirectional heartbeat polling and cooperative Tokio task cancellation for Axum 0.8 WebSocket connections. Eliminates silent file descriptor exhaustion, zombie connection accumulation, and unhandled task panics caused by asymmetric split-stream teardowns during edge reverse proxy failovers and rolling deploys. 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 (Asymmetric Split Tasks with Detached Ping Loops and Missing Pong Verification) 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