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

eBPF XDP Ingress Token Bucket Rate Limiting Production Standard

Enforces bare-metal NIC-level packet filtering via eBPF XDP driver mode to drop volumetric ingress traffic before socket buffer (sk_buff) allocation. Eliminates ksoftirqd CPU starvation and nf_conntrack table exhaustion by utilizing lockless token bucket algorithms with strictly bounded verifier memory access.

Prohibited Anti-Pattern: Delegating Volumetric L7 Flood Mitigation to Userspace Proxies or Kernel Conntrack

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: eBPF XDP Ingress Token Bucket Rate Limiting Production Standard - Enforces bare-metal NIC-level packet filtering via eBPF XDP driver mode to drop volumetric ingress traffic before socket buffer (sk_buff) allocation. Eliminates ksoftirqd CPU starvation and nf_conntrack table exhaustion by utilizing lockless token bucket algorithms with strictly bounded verifier memory access.
globs: **/*.bpf.c, **/*.bpf.h, src/bpf/**/*.c, kernel/**/*.c
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/ebpf-xdp-stateless-token-bucket-guardrail"
---

# eBPF XDP Ingress Token Bucket Rate Limiting Production Standard

> **Severity**: CRITICAL | **Category**: devops
> **Anti-Pattern Warning**: Delegating Volumetric L7 Flood Mitigation to Userspace Proxies or Kernel Conntrack

## System Constraints
You are a Principal Linux Kernel and Systems Reliability Engineer enforcing NIC-level ingress guardrails. When writing or refactoring eBPF XDP programs for volumetric flood protection, mandate lockless token-bucket rate limiting at the driver level (native XDP). Never allocate kernel socket buffers (sk_buff), invoke userspace hooks, or engage connection tracking (nf_conntrack) for high-rate line-rate ingress decisions. Ensure all memory reads strictly validate data and data_end boundaries to satisfy the eBPF kernel verifier without dynamic heap overhead.

## Strict Guidelines
- Engineers MUST ALWAYS attach eBPF ingress rate limiters at the XDP driver hook (xdpdrv) or offloaded hook (xdpoffload), never deferring volumetric filtering to TC (Traffic Control) or userspace proxies.
- Engineers MUST NOT utilize global kernel spinlocks or blocking synchronization primitives inside high-throughput XDP packet evaluation loops; rely on atomic primitives (`__sync_fetch_and_add`) or per-CPU array maps.
- Code MUST strictly validate direct packet access pointers (`data + offset > data_end`) prior to dereferencing IP and transport protocol headers to satisfy Linux BPF verifier boundary safety.
- Services MUST implement token bucket replenish logic statelessly or via BPF LRU maps (`BPF_MAP_TYPE_LRU_HASH`) using nanosecond monotonic timestamps (`bpf_ktime_get_ns()`) to prevent unbounded map growth and memory exhaustion.
- Components NEVER pass uninspected flood traffic across the network stack; excessive packets exceeding the committed burst rate (CBR) MUST immediately return `XDP_DROP` without generating ICMP unreachable responses.

## Bad vs Good Implementations
### XDP Token Bucket Rate Limiter with Direct Packet Bounds Validation

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Accessing packet headers without checking against ctx->data_end causes immediate verifier rejection. Using BPF_MAP_TYPE_HASH with non-atomic mutations introduces data races across CPU cores and exposes edge clusters to memory exhaustion without LRU eviction.
```c
#include <linux/bpf.h>
#include <bpf/bpf_helpers.h>

struct bpf_map_def SEC("maps") fallback_map = {
    .type = BPF_MAP_TYPE_HASH,
    .key_size = sizeof(__u32),
    .value_size = sizeof(__u64),
    .max_entries = 10000000,
};

SEC("xdp")
int xdp_bad_ratelimit(struct xdp_md *ctx) {
    // ANTI-PATTERN: Missing bounds check on packet data access
    void *data = (void *)(long)ctx->data;
    struct iphdr *iph = data + sizeof(struct ethhdr);
    __u32 src_ip = iph->saddr; 

    // Unbounded map lookup without atomic token refresh or per-CPU isolation
    __u64 *tokens = bpf_map_lookup_elem(&fallback_map, &src_ip);
    if (tokens && *tokens > 0) {
        *tokens -= 1; // Race condition: non-atomic access across multiple cores
        return XDP_PASS;
    }
    return XDP_DROP;
}
```

#### Production Standard (Correct)
> **Standard**: Validates boundary access on both Ethernet and IP headers, guarding verifier compliance. Uses BPF_MAP_TYPE_LRU_HASH to cap map allocation memory, and applies a stateless token replenish delta using monotonic time, mitigating line-rate DDoS attacks with zero sk_buff overhead.
```c
#include <linux/bpf.h>
#include <linux/if_ether.h>
#include <linux/ip.h>
#include <bpf/bpf_helpers.h>

struct rate_limit_entry {
    __u64 last_update_ns;
    __u64 tokens;
};

struct {
    __uint(type, BPF_MAP_TYPE_LRU_HASH);
    __uint(max_entries, 131072);
    __type(key, __u32);
    __type(value, struct rate_limit_entry);
} rate_limit_map SEC(".maps");

#define RATE_LIMIT_TOKENS_PER_SEC 100000ULL
#define BURST_CAPACITY 50000ULL
#define NSEC_PER_SEC 1000000000ULL

SEC("xdp")
int xdp_token_bucket_limit(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 != __builtin_bswap16(ETH_P_IP))
        return XDP_PASS;

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

    __u32 src_ip = iph->saddr;
    __u64 now = bpf_ktime_get_ns();

    struct rate_limit_entry *entry = bpf_map_lookup_elem(&rate_limit_map, &src_ip);
    if (!entry) {
        struct rate_limit_entry initial = {
            .last_update_ns = now,
            .tokens = BURST_CAPACITY - 1
        };
        bpf_map_update_elem(&rate_limit_map, &src_ip, &initial, BPF_NOEXIST);
        return XDP_PASS;
    }

    __u64 elapsed = now - entry->last_update_ns;
    __u64 generated = (elapsed * RATE_LIMIT_TOKENS_PER_SEC) / NSEC_PER_SEC;
    __u64 current_tokens = entry->tokens + generated;

    if (current_tokens > BURST_CAPACITY)
        current_tokens = BURST_CAPACITY;

    if (current_tokens < 1) {
        return XDP_DROP;
    }

    entry->tokens = current_tokens - 1;
    entry->last_update_ns = now;
    return XDP_PASS;
}
```

Architectural Specification & Invariant Rationale

Architectural Invariant Design: eBPF XDP Ingress Token Bucket Rate Limiting Production Standard

eBPF XDP Ingress Token Bucket Rate Limiting Production Standard defines an industrial-grade behavioral standard for devops engineering. Enforces bare-metal NIC-level packet filtering via eBPF XDP driver mode to drop volumetric ingress traffic before socket buffer (sk_buff) allocation. Eliminates ksoftirqd CPU starvation and nf_conntrack table exhaustion by utilizing lockless token bucket algorithms with strictly bounded verifier memory access. 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: Delegating Volumetric L7 Flood Mitigation to Userspace Proxies or Kernel Conntrack 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 DriftDelegating Volumetric L7 Flood Mitigation to Userspace Proxies or Kernel ConntrackCritical
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 attach eBPF ingress rate limiters at the XDP driver hook (xdpdrv) or offloaded hook (xdpoffload), never deferring volumetric filtering to TC (Traffic Control) or userspace proxies.

Engineers MUST ALWAYS attach eBPF ingress rate limiters at the XDP driver hook (xdpdrv) or offloaded hook (xdpoffload), never deferring volumetric filtering to TC (Traffic Control) or userspace proxies.

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 utilize global kernel spinlocks or blocking synchronization primitives inside high-throughput XDP packet evaluation loops

Engineers MUST NOT utilize global kernel spinlocks or blocking synchronization primitives inside high-throughput XDP packet evaluation loops; rely on atomic primitives (`__sync_fetch_and_add`) or per-CPU array maps.

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 MUST strictly validate direct packet access pointers (`data + offset > data_end`) prior to dereferencing IP and transport protocol headers to satisfy Linux BPF verifier boundary safety.

Code MUST strictly validate direct packet access pointers (`data + offset > data_end`) prior to dereferencing IP and transport protocol headers to satisfy Linux BPF verifier boundary safety.

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 implement token bucket replenish logic statelessly or via BPF LRU maps (`BPF_MAP_TYPE_LRU_HASH`) using nanosecond monotonic timestamps (`bpf_ktime_get_ns()`) to prevent unbounded map growth and memory exhaustion.

Services MUST implement token bucket replenish logic statelessly or via BPF LRU maps (`BPF_MAP_TYPE_LRU_HASH`) using nanosecond monotonic timestamps (`bpf_ktime_get_ns()`) to prevent unbounded map growth and memory exhaustion.

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 pass uninspected flood traffic across the network stack

Components NEVER pass uninspected flood traffic across the network stack; excessive packets exceeding the committed burst rate (CBR) MUST immediately return `XDP_DROP` without generating ICMP unreachable responses.

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 eBPF XDP Ingress Token Bucket Rate Limiting Production Standard critical for AI coding assistants?

Enforces bare-metal NIC-level packet filtering via eBPF XDP driver mode to drop volumetric ingress traffic before socket buffer (sk_buff) allocation. Eliminates ksoftirqd CPU starvation and nf_conntrack table exhaustion by utilizing lockless token bucket algorithms with strictly bounded verifier memory access. 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 (Delegating Volumetric L7 Flood Mitigation to Userspace Proxies or Kernel Conntrack) 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

eBPF