This specification is maintained by the AgentRules Working Group. Have enhancements or want to claim maintainership?Submit Specification →
backendcritical PriorityID: axum-webtransport-datagram-flow-control-boundary

Axum WebTransport Datagram Ingress Flow-Control & Backpressure Boundary

Enforces deterministic ingress backpressure and bounded allocation on WebTransport UDP datagram streams in Axum/Tokio services. Because HTTP/3 datagrams bypass connection-level flow control, unconstrained ingress loops saturate executor thread pools and trigger unbounded memory allocations during packet floods.

Prohibited Anti-Pattern: Unbounded Task Spawning and Unchecked Ingress Loops on HTTP/3 Datagram Channels

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Axum WebTransport Datagram Ingress Flow-Control & Backpressure Boundary - Enforces deterministic ingress backpressure and bounded allocation on WebTransport UDP datagram streams in Axum/Tokio services. Because HTTP/3 datagrams bypass connection-level flow control, unconstrained ingress loops saturate executor thread pools and trigger unbounded memory allocations during packet floods.
globs: src/**/*.rs, crates/**/*.rs
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/axum-webtransport-datagram-flow-control-boundary"
---

# Axum WebTransport Datagram Ingress Flow-Control & Backpressure Boundary

> **Severity**: CRITICAL | **Category**: backend
> **Anti-Pattern Warning**: Unbounded Task Spawning and Unchecked Ingress Loops on HTTP/3 Datagram Channels

## System Constraints
You are a Principal Systems Engineer enforcing strict UDP and WebTransport datagram flow-control invariants in Axum and Tokio environments. Mandate zero unbounded allocations, bounded concurrency buffers, and immediate drop-or-throttle backpressure boundaries to prevent thread pool exhaustion and out-of-memory denial-of-service conditions.

## Strict Guidelines
- Engineers MUST ALWAYS enforce bounded ingress buffering using bounded channels (e.g., `tokio::sync::mpsc::channel`) or bounded semaphore permits when reading WebTransport datagrams.
- Engineers MUST NEVER invoke `tokio::spawn` per incoming datagram directly from the ingress read loop.
- Engineers MUST handle Datagram Buffer Saturation deterministically using `try_reserve` or non-blocking drops, emitting metric counters for dropped datagrams instead of stalling the network loop.
- Code SHOULD pre-allocate datagram memory slabs using reusable byte pools (e.g., `bytes::BytesMut`) rather than performing continuous heap allocations inside packet-processing hot paths.
- Services MUST bound the total memory allocated to datagram ingress per session and across the entire Axum HTTP/3 server process using atomic limits or token buckets.
- Components NEVER bridge raw datagrams directly into blocking sync code or unthrottled downstream message buses without strict rate-limiting and circuit breaking.

## Bad vs Good Implementations
### Unbounded Datagram Spawn vs Bounded Permit Reserve

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Directly spawning asynchronous tasks within an unthrottled datagram loop causes unbounded allocation. WebTransport datagrams have no QUIC flow-control window, making the process vulnerable to executor starvation and memory exhaustion under packet-flood conditions.
```rust
use axum::extract::State;
use bytes::Bytes;

// Anti-pattern: Unbounded task creation and unbounded channel consumption per datagram
pub async fn handle_session(mut session: wtransport::Session) {
    while let Ok(datagram) = session.receive_datagram().await {
        // Spawns a Tokio task for every UDP packet received.
        // A flood of 500k pps exhausts the Tokio worker thread queue,
        // causing catastrophic memory bloat and eventual process OOM.
        tokio::spawn(async move {
            let payload = datagram.to_vec(); // Unnecessary allocation
            process_packet(&payload).await;
        });
    }
}

async fn process_packet(_data: &[u8]) {
    // processing logic
}
```

#### Production Standard (Correct)
> **Standard**: Implements a strict bounded channel with zero-copy packet ingestion and deterministic non-blocking drops (`try_send`) upon buffer saturation. This preserves Tokio worker health and satisfies the flow-control boundary for unreliable datagrams.
```rust
use bytes::Bytes;
use tokio::sync::mpsc::{channel, error::TrySendError};
use tracing::warn;

const DATAGRAM_CAPACITY: usize = 4096;

pub async fn handle_session(mut session: wtransport::Session) {
    // Invariant: Hard-bounded channel enforcing flow-control boundary
    let (tx, mut rx) = channel::<Bytes>(DATAGRAM_CAPACITY);

    // Worker pool reader with dedicated bounded capacity
    tokio::spawn(async move {
        while let Some(datagram) = rx.recv().await {
            process_packet(datagram).await;
        }
    });

    // Ingress loop: Non-blocking try_reserve drop semantics
    while let Ok(datagram) = session.receive_datagram().await {
        let payload = datagram.payload(); // Zero-copy Bytes view

        match tx.try_send(payload) {
            Ok(_) => {}
            Err(TrySendError::Full(_)) => {
                // Drop packet intentionally to preserve executor responsiveness
                metrics::counter!("webtransport.datagrams.dropped_capacity").increment(1);
            }
            Err(TrySendError::Closed(_)) => {
                warn!("Datagram processor terminated; breaking ingress loop");
                break;
            }
        }
    }
}

async fn process_packet(_data: Bytes) {
    // processing logic
}
```

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 WebTransport Datagram Ingress Flow-Control & Backpressure Boundary

Axum WebTransport Datagram Ingress Flow-Control & Backpressure Boundary defines an industrial-grade behavioral standard for backend engineering. Enforces deterministic ingress backpressure and bounded allocation on WebTransport UDP datagram streams in Axum/Tokio services. Because HTTP/3 datagrams bypass connection-level flow control, unconstrained ingress loops saturate executor thread pools and trigger unbounded memory allocations during packet floods. 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: Unbounded Task Spawning and Unchecked Ingress Loops on HTTP/3 Datagram Channels 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 DriftUnbounded Task Spawning and Unchecked Ingress Loops on HTTP/3 Datagram ChannelsCritical
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 enforce bounded ingress buffering using bounded channels (e.g., `tokio

Engineers MUST ALWAYS enforce bounded ingress buffering using bounded channels (e.g., `tokio::sync::mpsc::channel`) or bounded semaphore permits when reading WebTransport datagrams.

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 NEVER invoke `tokio

Engineers MUST NEVER invoke `tokio::spawn` per incoming datagram directly from the ingress read loop.

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 handle Datagram Buffer Saturation deterministically using `try_reserve` or non-blocking drops, emitting metric counters for dropped datagrams instead of stalling the network loop.

Engineers MUST handle Datagram Buffer Saturation deterministically using `try_reserve` or non-blocking drops, emitting metric counters for dropped datagrams instead of stalling the network loop.

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

Code SHOULD pre-allocate datagram memory slabs using reusable byte pools (e.g., `bytes

Code SHOULD pre-allocate datagram memory slabs using reusable byte pools (e.g., `bytes::BytesMut`) rather than performing continuous heap allocations inside packet-processing hot paths.

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 bound the total memory allocated to datagram ingress per session and across the entire Axum HTTP/3 server process using atomic limits or token buckets.

Services MUST bound the total memory allocated to datagram ingress per session and across the entire Axum HTTP/3 server process using atomic limits or token buckets.

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 bridge raw datagrams directly into blocking sync code or unthrottled downstream message buses without strict rate-limiting and circuit breaking.

Components NEVER bridge raw datagrams directly into blocking sync code or unthrottled downstream message buses without strict rate-limiting and circuit breaking.

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 WebTransport Datagram Ingress Flow-Control & Backpressure Boundary critical for AI coding assistants?

Enforces deterministic ingress backpressure and bounded allocation on WebTransport UDP datagram streams in Axum/Tokio services. Because HTTP/3 datagrams bypass connection-level flow control, unconstrained ingress loops saturate executor thread pools and trigger unbounded memory allocations during packet floods. 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 (Unbounded Task Spawning and Unchecked Ingress Loops on HTTP/3 Datagram Channels) 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