This specification is maintained by the AgentRules Working Group. Have enhancements or want to claim maintainership?Submit Specification →
backendcritical PriorityID: axum-sse-stream-cancellation-socket-pruning

Axum SSE Stream Cancellation Safety and Downstream Socket Pruning Guardrail

Mandates explicit cancellation propagation, active keep-alive probes, and RAII-bound task lifecycles for Server-Sent Events in Axum. Prevents orphaned Tokio tasks, unbounded memory leaks, and socket descriptor exhaustion under transient client disconnects and network partitions.

Prohibited Anti-Pattern: Decoupling background producer tasks from Axum SSE stream drops without keep-alive probes, leaking Tokio tasks and socket descriptors.

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Axum SSE Stream Cancellation Safety and Downstream Socket Pruning Guardrail - Mandates explicit cancellation propagation, active keep-alive probes, and RAII-bound task lifecycles for Server-Sent Events in Axum. Prevents orphaned Tokio tasks, unbounded memory leaks, and socket descriptor exhaustion under transient client disconnects and network partitions.
globs: src/**/*.rs
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/axum-sse-stream-cancellation-socket-pruning"
---

# Axum SSE Stream Cancellation Safety and Downstream Socket Pruning Guardrail

> **Severity**: CRITICAL | **Category**: backend
> **Anti-Pattern Warning**: Decoupling background producer tasks from Axum SSE stream drops without keep-alive probes, leaking Tokio tasks and socket descriptors.

## System Constraints
You are a Principal Rust Architect enforcing Axum SSE Stream Cancellation Safety and Downstream Socket Pruning Guardrails. Mandate invariants that prevent task leaks, socket exhaustion, and silent resource accumulation during client disconnections.

## Strict Guidelines
- Engineers MUST ALWAYS configure explicit KeepAlive on every axum::response::sse::Sse instance to detect half-open TCP sockets and force socket cleanup.
- Engineers MUST NOT spawn unmonitored background tokio::spawn producer tasks that lack an AbortHandle, CancellationToken, or channel-driven termination linkage.
- Code SHOULD yield streams constructed via drop-aware structures where worker execution terminates immediately upon stream consumer drop.
- Services MUST handle tokio::sync::broadcast::error::RecvError::Lagged explicitly within SSE adapters to prevent silent stream stalls.
- Components NEVER detach async worker loops without linking their termination to the downstream HTTP connection lifecycle.

## Bad vs Good Implementations
### Unbounded Producer Task and Missing Keep-Alive vs. RAII-Guarded Stream with Keep-Alive

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Spawns an unlinked background Tokio task and returns an SSE stream without KeepAlive heartbeat frames. If a client terminates without sending FIN (e.g., abrupt network drop), TCP half-open sockets persist, channel senders do not fail immediately, and Tokio worker tasks leak permanently, eventually exhausting OS file descriptors.
```rust
use axum::response::sse::{Event, Sse};
use futures::stream::Stream;
use std::convert::Infallible;
use tokio::sync::mpsc;
use tokio_stream::wrappers::ReceiverStream;

pub async fn sse_handler() -> Sse<impl Stream<Item = Result<Event, Infallible>>> {
    let (tx, rx) = mpsc::channel(100);

    // ANTI-PATTERN: Detached task spawns without abort handle or cancellation linkage.
    // If the client silently disconnects or encounters a TCP half-open state,
    // this task runs indefinitely, leaking memory and Tokio worker execution cycles.
    tokio::spawn(async move {
        let mut count = 0;
        loop {
            tokio::time::sleep(tokio::time::Duration::from_secs(1)).await;
            count += 1;
            let _ = tx.send(Ok(Event::default().data(format!("tick {}", count)))).await;
        }
    });

    // ANTI-PATTERN: Missing KeepAlive configuration. Half-open connections never terminate.
    Sse::new(ReceiverStream::new(rx))
}
```

#### Production Standard (Correct)
> **Standard**: Couples the producer task's lifetime to the SSE stream via CancellationToken and drop_guard. Configures Sse::keep_alive to actively probe connection health, pruning dead sockets and terminating the background Tokio task immediately when the client disconnects.
```rust
use axum::{
    response::sse::{Event, KeepAlive, Sse},
    BoxError,
};
use futures::stream::Stream;
use std::time::Duration;
use tokio_stream::wrappers::ReceiverStream;
use tokio_util::sync::CancellationToken;

pub async fn sse_handler() -> Sse<impl Stream<Item = Result<Event, BoxError>>> {
    let (tx, rx) = tokio::sync::mpsc::channel::<Result<Event, BoxError>>(32);
    let token = CancellationToken::new();
    let child_token = token.clone();

    // Task is bound to CancellationToken and terminates when channel receiver drops
    tokio::spawn(async move {
        let mut count = 0;
        loop {
            tokio::select! {
                _ = child_token.cancelled() => break,
                _ = tokio::time::sleep(Duration::from_secs(1)) => {
                    count += 1;
                    let event = Ok(Event::default().data(format!("tick {}", count)));
                    if tx.send(event).await.is_err() {
                        break; // Receiver dropped, terminate immediately
                    }
                }
            }
        }
    });

    let stream = ReceiverStream::new(rx);
    let guarded_stream = async_stream::stream! {
        let _guard = token.drop_guard();
        for await item in stream {
            yield item;
        }
    };

    // Heartbeat ensures abrupt disconnections are detected and sockets pruned
    Sse::new(guarded_stream).keep_alive(
        KeepAlive::new()
            .interval(Duration::from_secs(15))
            .text("ping"),
    )
}
```

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 SSE Stream Cancellation Safety and Downstream Socket Pruning Guardrail

Axum SSE Stream Cancellation Safety and Downstream Socket Pruning Guardrail defines an industrial-grade behavioral standard for backend engineering. Mandates explicit cancellation propagation, active keep-alive probes, and RAII-bound task lifecycles for Server-Sent Events in Axum. Prevents orphaned Tokio tasks, unbounded memory leaks, and socket descriptor exhaustion under transient client disconnects and network partitions. 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: Decoupling background producer tasks from Axum SSE stream drops without keep-alive probes, leaking Tokio tasks and socket descriptors. 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 DriftDecoupling background producer tasks from Axum SSE stream drops without keep-alive probes, leaking Tokio tasks and socket descriptors.Critical
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 configure explicit KeepAlive on every axum

Engineers MUST ALWAYS configure explicit KeepAlive on every axum::response::sse::Sse instance to detect half-open TCP sockets and force socket cleanup.

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 spawn unmonitored background tokio

Engineers MUST NOT spawn unmonitored background tokio::spawn producer tasks that lack an AbortHandle, CancellationToken, or channel-driven termination linkage.

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 SHOULD yield streams constructed via drop-aware structures where worker execution terminates immediately upon stream consumer drop.

Code SHOULD yield streams constructed via drop-aware structures where worker execution terminates immediately upon stream consumer drop.

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 handle tokio

Services MUST handle tokio::sync::broadcast::error::RecvError::Lagged explicitly within SSE adapters to prevent silent stream stalls.

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 detach async worker loops without linking their termination to the downstream HTTP connection lifecycle.

Components NEVER detach async worker loops without linking their termination to the downstream HTTP connection lifecycle.

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 SSE Stream Cancellation Safety and Downstream Socket Pruning Guardrail critical for AI coding assistants?

Mandates explicit cancellation propagation, active keep-alive probes, and RAII-bound task lifecycles for Server-Sent Events in Axum. Prevents orphaned Tokio tasks, unbounded memory leaks, and socket descriptor exhaustion under transient client disconnects and network partitions. 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 (Decoupling background producer tasks from Axum SSE stream drops without keep-alive probes, leaking Tokio tasks and socket descriptors.) 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