This specification is maintained by the AgentRules Working Group. Have enhancements or want to claim maintainership?Submit Specification →
backendcritical PriorityID: axum-08-zero-allocation-extractor-pipeline

Axum 0.8 Zero-Allocation Request Extractor Pipeline

Enforces strict zero-allocation extraction patterns in Axum 0.8 request pipelines to eliminate intermediate heap buffers and prevent multi-gigabit throughput degradation. Guarantees compile-time lifetime safety and bound constraints across contiguous raw network byte buffers.

Prohibited Anti-Pattern: Heap-Cloning Deserializers and Unbounded Intermediate Buffers in High-Throughput Request Paths

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Axum 0.8 Zero-Allocation Request Extractor Pipeline - Enforces strict zero-allocation extraction patterns in Axum 0.8 request pipelines to eliminate intermediate heap buffers and prevent multi-gigabit throughput degradation. Guarantees compile-time lifetime safety and bound constraints across contiguous raw network byte buffers.
globs: src/**/*.rs, crates/**/*.rs
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/axum-08-zero-allocation-extractor-pipeline"
---

# Axum 0.8 Zero-Allocation Request Extractor Pipeline

> **Severity**: CRITICAL | **Category**: backend
> **Anti-Pattern Warning**: Heap-Cloning Deserializers and Unbounded Intermediate Buffers in High-Throughput Request Paths

## System Constraints
You are a Principal Rust Systems Architect enforcing zero-allocation request pipelines in Axum 0.8. You must eradicate redundant buffer clones, heap reallocations, and unconstrained deserialization of owned types (`String`, `Vec<u8>`) on hot HTTP ingestion paths.

## Strict Guidelines
- Engineers MUST ALWAYS bound request payload sizes before reading payloads using `DefaultBodyLimit::max` or `axum::body::to_bytes(body, MAX_LIMIT)`.
- Engineers MUST NOT use `axum::Json<T>` where `T` contains owned heap allocations (`String`, `Vec<T>`) inside multi-gigabit throughput routes.
- Engineers MUST leverage `bytes::Bytes` directly, parsing via `serde::Deserialize<'de>` with borrowed references (`&'a str`, `&'a [u8]`) or cow references (`Cow<'a, str>`).
- Services MUST extract the unbuffered `axum::extract::Request` or `Bytes` directly to prevent intermediate `axum::body::Body` reallocation copies.
- Components NEVER call `.to_vec()`, `String::from_utf8()`, or `.clone()` on incoming request buffers during extractor execution.

## Bad vs Good Implementations
### Zero-Copy Ingestion Handler with Borrowed Bytes Deserialization

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Using standard `axum::Json` with owned `String` fields forces the allocator to create multiple heap allocations per request, discarding HTTP buffer contiguity and causing severe allocator lock contention under multi-gigabit loads.
```rust
use axum::{response::IntoResponse, Json};
use serde::Deserialize;

// ANTI-PATTERN: Forces three separate heap allocations for every incoming request.
// Under multi-gigabit throughput, the allocator faces massive contention and cache thrashing.
#[derive(Deserialize)]
pub struct TelemetryIngest {
    pub device_id: String,
    pub sensor_type: String,
    pub payload_b64: String,
}

pub async fn ingest_handler(Json(payload): Json<TelemetryIngest>) -> impl IntoResponse {
    axum::http::StatusCode::ACCEPTED
}
```

#### Production Standard (Correct)
> **Standard**: The fix extracts body bytes with an explicit upper bound using `to_bytes`, preventing unconstrained memory attacks, and deserializes into a lifetime-bounded view (`TelemetryView<'a>`) borrowing directly from the network buffer slice without intermediate heap allocations.
```rust
use axum::{
    body::to_bytes,
    extract::Request,
    http::StatusCode,
    response::{IntoResponse, Response},
};
use serde::Deserialize;

const MAX_INGEST_BYTES: usize = 64 * 1024; // 64 KiB bounded threshold

// PRODUCTION FIX: Zero-allocation view over contiguous network buffer.
#[derive(Deserialize)]
pub struct TelemetryView<'a> {
    #[serde(borrow)]
    pub device_id: &'a str,
    #[serde(borrow)]
    pub sensor_type: &'a str,
    #[serde(borrow)]
    pub payload_b64: &'a str,
}

pub async fn ingest_handler(req: Request) -> Result<impl IntoResponse, Response> {
    // Bounded extraction directly into shared, reference-counted contiguous Bytes
    let (_parts, body) = req.into_parts();
    let bytes = to_bytes(body, MAX_INGEST_BYTES)
        .await
        .map_err(|_| StatusCode::PAYLOAD_TOO_LARGE.into_response())?;

    // Zero-allocation deserialization borrowing from the bounded buffer
    let payload: TelemetryView = serde_json::from_slice(&bytes)
        .map_err(|_| StatusCode::UNPROCESSABLE_ENTITY.into_response())?;

    // Read fields through references without re-allocating memory
    let _ = (payload.device_id, payload.sensor_type);

    Ok(StatusCode::ACCEPTED)
}
```

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 Zero-Allocation Request Extractor Pipeline

Axum 0.8 Zero-Allocation Request Extractor Pipeline defines an industrial-grade behavioral standard for backend engineering. Enforces strict zero-allocation extraction patterns in Axum 0.8 request pipelines to eliminate intermediate heap buffers and prevent multi-gigabit throughput degradation. Guarantees compile-time lifetime safety and bound constraints across contiguous raw network byte buffers. 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: Heap-Cloning Deserializers and Unbounded Intermediate Buffers in High-Throughput Request Paths 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 DriftHeap-Cloning Deserializers and Unbounded Intermediate Buffers in High-Throughput Request PathsCritical
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 bound request payload sizes before reading payloads using `DefaultBodyLimit

Engineers MUST ALWAYS bound request payload sizes before reading payloads using `DefaultBodyLimit::max` or `axum::body::to_bytes(body, MAX_LIMIT)`.

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 use `axum

Engineers MUST NOT use `axum::Json<T>` where `T` contains owned heap allocations (`String`, `Vec<T>`) inside multi-gigabit throughput routes.

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 leverage `bytes

Engineers MUST leverage `bytes::Bytes` directly, parsing via `serde::Deserialize<'de>` with borrowed references (`&'a str`, `&'a [u8]`) or cow references (`Cow<'a, str>`).

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 extract the unbuffered `axum

Services MUST extract the unbuffered `axum::extract::Request` or `Bytes` directly to prevent intermediate `axum::body::Body` reallocation copies.

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 call `.to_vec()`, `String

Components NEVER call `.to_vec()`, `String::from_utf8()`, or `.clone()` on incoming request buffers during extractor execution.

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 Zero-Allocation Request Extractor Pipeline critical for AI coding assistants?

Enforces strict zero-allocation extraction patterns in Axum 0.8 request pipelines to eliminate intermediate heap buffers and prevent multi-gigabit throughput degradation. Guarantees compile-time lifetime safety and bound constraints across contiguous raw network byte buffers. 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 (Heap-Cloning Deserializers and Unbounded Intermediate Buffers in High-Throughput Request Paths) 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