This specification is maintained by the AgentRules Working Group. Have enhancements or want to claim maintainership?Submit Specification →
devopscritical PriorityID: ebpf-af-xdp-zerocopy-ratelimit-guardrail

Zero-Copy Driver-Level Ingress Rate Limiting with eBPF/XDP and AF_XDP

Enforces strict native/driver-mode XDP hook execution and UMEM ring buffer memory safety for AF_XDP zero-copy ingress filtering. Eliminates kernel SKB allocations during volumetric Layer 4 DDoS attacks by dropping abusive packets directly at the NIC ring buffer before kernel stack traversal.

Prohibited Anti-Pattern: Falling Back to Generic XDP Mode and Copying Packets During Layer 4 Flood Ingress

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: "Zero-Copy Driver-Level Ingress Rate Limiting with eBPF/XDP and AF_XDP - Enforces strict native/driver-mode XDP hook execution and UMEM ring buffer memory safety for AF_XDP zero-copy ingress filtering. Eliminates kernel SKB allocations during volumetric Layer 4 DDoS attacks by dropping abusive packets directly at the NIC ring buffer before kernel stack traversal."
globs: "**/*.c, **/*.h, src/bpf/**/*.c, src/network/**/*.c, infra/ebpf/**/*.c, deploy/xdp/**/*.yaml"
alwaysApply: true
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/ebpf-af-xdp-zerocopy-ratelimit-guardrail"
---

# Zero-Copy Driver-Level Ingress Rate Limiting with eBPF/XDP and AF_XDP

> **Severity**: CRITICAL | **Category**: devops
> **Anti-Pattern Warning**: Falling Back to Generic XDP Mode and Copying Packets During Layer 4 Flood Ingress

## System Constraints
You are a Principal Systems and Network Infrastructure Engineer enforcing strict standards for eBPF AF_XDP Zero-Copy Ingress Rate-Limiting Filters. Mandate zero SKB allocation under L4 DDoS attacks, enforce direct driver-mode (XDP_FLAGS_DRV_MODE) verification, bounds checks on all packet cursor dereferences, atomic token-bucket or sliding-window rate tracking using per-CPU BPF maps, and strict unaligned-mode UMEM alignment handling to prevent memory corruption and kernel panics.

## Strict Guidelines
- Engineers MUST ALWAYS verify XDP hook attachment in native/driver mode (XDP_FLAGS_DRV_MODE); generic SKB mode (XDP_FLAGS_SKB_MODE) is strictly forbidden in production as it allocates struct sk_buff prior to eBPF execution.
- Engineers MUST ALWAYS implement complete cursor bounds validation (data + offset <= data_end) before dereferencing any byte of Ethernet, IPv4/IPv6, UDP, or TCP headers to satisfy the BPF verifier.
- Engineers MUST use lockless BPF_MAP_TYPE_PERCPU_ARRAY or per-CPU BPF_MAP_TYPE_LRU_HASH for token-bucket rate state to avoid CPU cache-line bouncing and lock contention under multi-gigabit traffic rates.
- Engineers MUST immediately return XDP_DROP or redirect legitimate packets via bpf_redirect_map into AF_XDP (XSKMAP) using XDP_ZEROCOPY; copying packets to user space via XDP_COPY is prohibited for high-volume pipelines.
- Engineers MUST configure UMEM chunks with page-aligned sizes (e.g., 2048 or 4096 bytes) and ensure that packet metadata manipulation complies with XSK UMEM headroom specifications.
- Engineers MUST ensure BPF tail calls and maps are pre-allocated with BPF_F_NO_PREALLOC omitted or explicitly tested against high allocation latency under low-memory kernel conditions.

## Bad vs Good Implementations
### Driver-Level XDP Ingress Token Bucket Rate Limiting with AF_XDP Redirect

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: The BPF program accesses IP header fields without bounds checking against ctx->data_end, fails the BPF verifier, uses a non-per-CPU hash map which causes cache-line bouncing under multi-core DDoS conditions, and passes packets to the normal networking stack via XDP_PASS instead of terminating them via XDP_DROP or routing via AF_XDP.
```c
#include <linux/bpf.h>
#include <bpf/bpf_helpers.h>
#include <linux/if_ether.h>
#include <linux/ip.h>

// ANTI-PATTERN: Shared global map causes lock contention under multi-core volumetric flood.
// Fails to properly bounds check and falls back to passing to the kernel network stack.
struct { 
    __uint(type, BPF_MAP_TYPE_HASH);
    __uint(max_entries, 1024);
    __type(key, __u32);
    __type(value, __u64);
} rate_limit_map SEC(".maps");

SEC("xdp")
int xdp_filter_bad(struct xdp_md *ctx) {
    void *data = (void *)(long)ctx->data;
    void *data_end = (void *)(long)ctx->data_end;
    struct ethhdr *eth = data;

    // Incomplete boundary verification: verifier rejection or buffer overrun risk
    if ((void *)(eth + 1) > data_end) return XDP_PASS;
    struct iphdr *ip = (void *)(eth + 1);
    
    // Direct dereference without verifying ip + 1 <= data_end
    __u32 src_ip = ip->saddr;
    __u64 *tokens = bpf_map_lookup_elem(&rate_limit_map, &src_ip);
    if (tokens && *tokens > 100000) {
        // Relies on standard kernel stack processing instead of AF_XDP bypass
        return XDP_PASS;
    }
    return XDP_PASS;
}
```

#### Production Standard (Correct)
> **Standard**: Enforces complete bounds verification against data_end for all header layers, utilizes per-CPU array maps to guarantee lock-free sub-microsecond rate-limiting accounting without cache bouncing, instantly drops overflowing traffic via XDP_DROP before any kernel memory allocation, and redirects allowed traffic via AF_XDP zero-copy rings.
```c
#include <linux/bpf.h>
#include <bpf/bpf_helpers.h>
#include <linux/if_ether.h>
#include <linux/ip.h>
#include <bpf/bpf_endian.h>

#define RATE_LIMIT_PPS 100000
#define NANOS_PER_SEC 1000000000ULL

struct rate_limit_bucket {
    __u64 last_update_ns;
    __u64 tokens;
};

struct {
    __uint(type, BPF_MAP_TYPE_PERCPU_ARRAY);
    __uint(max_entries, 1);
    __type(key, __u32);
    __type(value, struct rate_limit_bucket);
} global_rate_limiter SEC(".maps");

struct {
    __uint(type, BPF_MAP_TYPE_XSKMAP);
    __uint(max_entries, 64);
    __type(key, __u32);
    __type(value, int);
} xsks_map SEC(".maps");

SEC("xdp")
int xdp_filter_good(struct xdp_md *ctx) {
    void *data = (void *)(long)ctx->data;
    void *data_end = (void *)(long)ctx->data_end;

    struct ethhdr *eth = data;
    if ((void *)(eth + 1) > data_end)
        return XDP_DROP;

    if (eth->h_proto != __bpf_constant_htons(ETH_P_IP))
        return XDP_PASS;

    struct iphdr *ip = (void *)(eth + 1);
    if ((void *)(ip + 1) > data_end)
        return XDP_DROP;

    __u32 key = 0;
    struct rate_limit_bucket *bucket = bpf_map_lookup_elem(&global_rate_limiter, &key);
    if (!bucket)
        return XDP_DROP;

    __u64 now = bpf_ktime_get_ns();
    __u64 elapsed = now - bucket->last_update_ns;
    bucket->last_update_ns = now;

    bucket->tokens += (elapsed * RATE_LIMIT_PPS) / NANOS_PER_SEC;
    if (bucket->tokens > RATE_LIMIT_PPS)
        bucket->tokens = RATE_LIMIT_PPS;

    if (bucket->tokens < 1) {
        // Volumetric threshold exceeded: drop at driver NIC ring before SKB allocation
        return XDP_DROP;
    }

    bucket->tokens--;
    // Divert valid packet to AF_XDP Zero-Copy socket for user space acceleration
    return bpf_redirect_map(&xsks_map, ctx->rx_queue_index, XDP_PASS);
}

char _license[] SEC("license") = "GPL";
```

Architectural Specification & Invariant Rationale

Architectural Invariant Design: Zero-Copy Driver-Level Ingress Rate Limiting with eBPF/XDP and AF_XDP

Zero-Copy Driver-Level Ingress Rate Limiting with eBPF/XDP and AF_XDP defines an industrial-grade behavioral standard for devops engineering. Enforces strict native/driver-mode XDP hook execution and UMEM ring buffer memory safety for AF_XDP zero-copy ingress filtering. Eliminates kernel SKB allocations during volumetric Layer 4 DDoS attacks by dropping abusive packets directly at the NIC ring buffer before kernel stack traversal. 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: Falling Back to Generic XDP Mode and Copying Packets During Layer 4 Flood Ingress 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 DriftFalling Back to Generic XDP Mode and Copying Packets During Layer 4 Flood IngressCritical
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 verify XDP hook attachment in native/driver mode (XDP_FLAGS_DRV_MODE)

Engineers MUST ALWAYS verify XDP hook attachment in native/driver mode (XDP_FLAGS_DRV_MODE); generic SKB mode (XDP_FLAGS_SKB_MODE) is strictly forbidden in production as it allocates struct sk_buff prior to eBPF 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.
2

Engineers MUST ALWAYS implement complete cursor bounds validation (data + offset <= data_end) before dereferencing any byte of Ethernet, IPv4/IPv6, UDP, or TCP headers to satisfy the BPF verifier.

Engineers MUST ALWAYS implement complete cursor bounds validation (data + offset <= data_end) before dereferencing any byte of Ethernet, IPv4/IPv6, UDP, or TCP headers to satisfy the BPF verifier.

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 use lockless BPF_MAP_TYPE_PERCPU_ARRAY or per-CPU BPF_MAP_TYPE_LRU_HASH for token-bucket rate state to avoid CPU cache-line bouncing and lock contention under multi-gigabit traffic rates.

Engineers MUST use lockless BPF_MAP_TYPE_PERCPU_ARRAY or per-CPU BPF_MAP_TYPE_LRU_HASH for token-bucket rate state to avoid CPU cache-line bouncing and lock contention under multi-gigabit traffic rates.

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

Engineers MUST immediately return XDP_DROP or redirect legitimate packets via bpf_redirect_map into AF_XDP (XSKMAP) using XDP_ZEROCOPY

Engineers MUST immediately return XDP_DROP or redirect legitimate packets via bpf_redirect_map into AF_XDP (XSKMAP) using XDP_ZEROCOPY; copying packets to user space via XDP_COPY is prohibited for high-volume pipelines.

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

Engineers MUST configure UMEM chunks with page-aligned sizes (e.g., 2048 or 4096 bytes) and ensure that packet metadata manipulation complies with XSK UMEM headroom specifications.

Engineers MUST configure UMEM chunks with page-aligned sizes (e.g., 2048 or 4096 bytes) and ensure that packet metadata manipulation complies with XSK UMEM headroom specifications.

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

Engineers MUST ensure BPF tail calls and maps are pre-allocated with BPF_F_NO_PREALLOC omitted or explicitly tested against high allocation latency under low-memory kernel conditions.

Engineers MUST ensure BPF tail calls and maps are pre-allocated with BPF_F_NO_PREALLOC omitted or explicitly tested against high allocation latency under low-memory kernel conditions.

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 Zero-Copy Driver-Level Ingress Rate Limiting with eBPF/XDP and AF_XDP critical for AI coding assistants?

Enforces strict native/driver-mode XDP hook execution and UMEM ring buffer memory safety for AF_XDP zero-copy ingress filtering. Eliminates kernel SKB allocations during volumetric Layer 4 DDoS attacks by dropping abusive packets directly at the NIC ring buffer before kernel stack traversal. 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 (Falling Back to Generic XDP Mode and Copying Packets During Layer 4 Flood Ingress) 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

Zero-Copy