This specification is maintained by the AgentRules Working Group. Have enhancements or want to claim maintainership?Submit Specification →
backendcritical PriorityID: axum-08-makeservice-connection-limit-tcp-reaping

Axum 0.8 Connection Limiting and TCP Handshake Reaping Guardrail

Enforces strict concurrency ceilings and handshake timeout fences on incoming TCP streams in Axum 0.8 deployments. Prevents file-descriptor starvation and heap exhaustion caused by slowloris attacks, hung TLS negotiations, and half-open HTTP/2 multiplexing state vectors. Guarantees that socket ingestion adheres to bounded resource pools and explicit socket teardown invariants.

Prohibited Anti-Pattern: Unbounded Listener Ingestion and Unfenced TLS/TCP Handshakes Inducing File Descriptor Exhaustion

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Axum 0.8 Connection Limiting and TCP Handshake Reaping Guardrail - Enforces strict concurrency ceilings and handshake timeout fences on incoming TCP streams in Axum 0.8 deployments. Prevents file-descriptor starvation and heap exhaustion caused by slowloris attacks, hung TLS negotiations, and half-open HTTP/2 multiplexing state vectors. Guarantees that socket ingestion adheres to bounded resource pools and explicit socket teardown invariants.
globs: src/**/*.rs
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/axum-08-makeservice-connection-limit-tcp-reaping"
---

# Axum 0.8 Connection Limiting and TCP Handshake Reaping Guardrail

> **Severity**: CRITICAL | **Category**: backend
> **Anti-Pattern Warning**: Unbounded Listener Ingestion and Unfenced TLS/TCP Handshakes Inducing File Descriptor Exhaustion

## System Constraints
You are a Principal Rust Systems Architect enforcing strict network safety invariants in Axum 0.8 and Tokio runtimes. Unbounded `axum::serve` accept loops without explicit concurrency quotas and handshake timeouts are banned. Enforce socket-level concurrency limiters, keep-alive fences, and explicit handshake reap deadlines.

## Strict Guidelines
- Engineers MUST ALWAYS enforce an upper bound on active TCP connections using an explicit semaphore or Tower `ConcurrencyLimitLayer` prior to socket processing.
- Engineers MUST NOT pass an unconstrained `tokio::net::TcpListener` directly to `axum::serve` in publicly accessible environments without edge termination or an explicit accept-rate limiter.
- Services MUST wrap socket-level TLS handshakes and initial HTTP frame negotiation within a strict timeout fence (e.g., `tokio::time::timeout` <= 5 seconds).
- Components NEVER allow half-open TCP connections to linger; `SO_KEEPALIVE` and `TCP_NODELAY` MUST be set alongside aggressive keepalive idle, interval, and probe thresholds via `socket2`.
- Code SHOULD track and drain active connection lifetimes using `tokio_util::task::TaskTracker` to guarantee deterministic resource reclamation during graceful shutdown.

## Bad vs Good Implementations
### Unbounded Serve Loop vs. Bounded Connection Semaphore with Handshake Timeout

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Directly running `axum::serve` on a naked `TcpListener` exposes the service to socket exhaustion. Malicious clients can negotiate TCP connections and stall TLS or HTTP/2 PREFACE frames indefinitely, leaking memory and exhausting file descriptors.
```rust
use axum::{routing::get, Router};
use tokio::net::TcpListener;

#[tokio::main]
async fn main() {
    let app = Router::new().route("/", get(|| async { "ok" }));
    let listener = TcpListener::bind("0.0.0.0:8080").await.unwrap();

    // CRITICAL ANTI-PATTERN: Direct unconstrained serve allows an attacker to open
    // tens of thousands of idle/slow TCP sockets, exhausting file descriptors
    // and OS buffer memory without triggering hyper request timeouts.
    axum::serve(listener, app).await.unwrap();
}
```

#### Production Standard (Correct)
> **Standard**: Wraps connection acquisition with an explicit Tokio Semaphore to enforce an absolute limit on concurrent open sockets. Uses `TokioIo` with Hyper's connection builder and wraps initial negotiation under a strict `timeout`, actively reclaiming hung sockets before resource starvation occurs.
```rust
use axum::{extract::Request, routing::get, Router};
use hyper_util::rt::{TokioExecutor, TokioIo};
use hyper_util::server::conn::auto::Builder;
use std::{net::SocketAddr, sync::Arc, time::Duration};
use tokio::{net::TcpListener, sync::Semaphore, time::timeout};
use tower_service::Service;

const MAX_CONNECTIONS: usize = 10_000;
const HANDSHAKE_TIMEOUT: Duration = Duration::from_secs(5);

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let app = Router::new().route("/", get(|| async { "ok" }));
    let listener = TcpListener::bind("0.0.0.0:8080").await?;
    let connection_pool = Arc::new(Semaphore::new(MAX_CONNECTIONS));

    loop {
        let permit = connection_pool.clone().acquire_owned().await?;
        let (stream, remote_addr): (tokio::net::TcpStream, SocketAddr) = listener.accept().await?;

        let tower_service = app.clone();
        tokio::spawn(async move {
            let _permit = permit; // RAII guard holds slot until connection closes
            let io = TokioIo::new(stream);
            let hyper_service = hyper::service::service_fn(move |req: Request<_>| {
                tower_service.clone().call(req)
            });

            let builder = Builder::new(TokioExecutor::new());
            // Enforce handshake and serving timeout fence
            let conn = builder.serve_connection_with_upgrades(io, hyper_service);
            tokio::pin!(conn);

            if let Err(err) = timeout(HANDSHAKE_TIMEOUT, conn.as_mut()).await {
                eprintln!("Connection timed out from {remote_addr}: {err}");
            }
        });
    }
}
```

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 Connection Limiting and TCP Handshake Reaping Guardrail

Axum 0.8 Connection Limiting and TCP Handshake Reaping Guardrail defines an industrial-grade behavioral standard for backend engineering. Enforces strict concurrency ceilings and handshake timeout fences on incoming TCP streams in Axum 0.8 deployments. Prevents file-descriptor starvation and heap exhaustion caused by slowloris attacks, hung TLS negotiations, and half-open HTTP/2 multiplexing state vectors. Guarantees that socket ingestion adheres to bounded resource pools and explicit socket teardown invariants. 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 Listener Ingestion and Unfenced TLS/TCP Handshakes Inducing File Descriptor Exhaustion 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 Listener Ingestion and Unfenced TLS/TCP Handshakes Inducing File Descriptor ExhaustionCritical
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 an upper bound on active TCP connections using an explicit semaphore or Tower `ConcurrencyLimitLayer` prior to socket processing.

Engineers MUST ALWAYS enforce an upper bound on active TCP connections using an explicit semaphore or Tower `ConcurrencyLimitLayer` prior to socket processing.

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 pass an unconstrained `tokio

Engineers MUST NOT pass an unconstrained `tokio::net::TcpListener` directly to `axum::serve` in publicly accessible environments without edge termination or an explicit accept-rate limiter.

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

Services MUST wrap socket-level TLS handshakes and initial HTTP frame negotiation within a strict timeout fence (e.g., `tokio

Services MUST wrap socket-level TLS handshakes and initial HTTP frame negotiation within a strict timeout fence (e.g., `tokio::time::timeout` <= 5 seconds).

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

Components NEVER allow half-open TCP connections to linger

Components NEVER allow half-open TCP connections to linger; `SO_KEEPALIVE` and `TCP_NODELAY` MUST be set alongside aggressive keepalive idle, interval, and probe thresholds via `socket2`.

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

Code SHOULD track and drain active connection lifetimes using `tokio_util

Code SHOULD track and drain active connection lifetimes using `tokio_util::task::TaskTracker` to guarantee deterministic resource reclamation 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.
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 Connection Limiting and TCP Handshake Reaping Guardrail critical for AI coding assistants?

Enforces strict concurrency ceilings and handshake timeout fences on incoming TCP streams in Axum 0.8 deployments. Prevents file-descriptor starvation and heap exhaustion caused by slowloris attacks, hung TLS negotiations, and half-open HTTP/2 multiplexing state vectors. Guarantees that socket ingestion adheres to bounded resource pools and explicit socket teardown invariants. 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 Listener Ingestion and Unfenced TLS/TCP Handshakes Inducing File Descriptor Exhaustion) 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