This specification is maintained by the AgentRules Working Group. Have enhancements or want to claim maintainership?Submit Specification →
devopscritical PriorityID: ebpf-xdp-l4-ingress-kernel-bypass-rate-limiting-guardrail

eBPF/XDP Layer-4 Ingress Kernel-Bypass Rate-Limiting Guardrail

Offloading L4 connection tracking and volumetric packet filtering to the eBPF XDP hook eliminates kernel network stack overhead and CPU starvation during ingress volumetric bursts. Software systems must leverage driver-mode or native XDP with per-CPU BPF maps and lockless token-bucket rate limiters prior to sk_buff allocation. Failure to decouple rate limiting from the sk_buff allocation pipeline leaves infrastructure vulnerable to softirq saturation and kernel-level denial of service.

Prohibited Anti-Pattern: Processing Layer-4 Rate-Limiting in User Space or Standard iptables/Netfilter Sk_buff Pipeline

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: eBPF/XDP Layer-4 Ingress Kernel-Bypass Rate-Limiting Guardrail - Offloading L4 connection tracking and volumetric packet filtering to the eBPF XDP hook eliminates kernel network stack overhead and CPU starvation during ingress volumetric bursts. Software systems must leverage driver-mode or native XDP with per-CPU BPF maps and lockless token-bucket rate limiters prior to sk_buff allocation. Failure to decouple rate limiting from the sk_buff allocation pipeline leaves infrastructure vulnerable to softirq saturation and kernel-level denial of service.
globs: infra/ebpf/**/*.c, src/network/**/*.c, src/ebpf/**/*.c, src/network/**/*.rs, infra/network/**/*.bpf.c
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/ebpf-xdp-l4-ingress-kernel-bypass-rate-limiting-guardrail"
---

# eBPF/XDP Layer-4 Ingress Kernel-Bypass Rate-Limiting Guardrail

> **Severity**: CRITICAL | **Category**: devops
> **Anti-Pattern Warning**: Processing Layer-4 Rate-Limiting in User Space or Standard iptables/Netfilter Sk_buff Pipeline

## System Constraints
You are a Principal Systems and Network Architect enforcing strict eBPF/XDP Layer-4 kernel-bypass rate limiting. Mandate that volumetric rate limiting and connection tracking invariants are implemented at the earliest possible hook in the network path (XDP native/driver mode) before the kernel allocates an sk_buff. Ensure that all BPF maps use per-CPU variants or lock-free concurrency primitives (e.g., atomic operations or BPF spinlocks with verified bounded iterations) and explicitly guard memory access against packet boundary overflows.

## Strict Guidelines
- Engineers MUST ALWAYS verify packet boundaries using data and data_end pointers before reading IP/L4 headers to guarantee eBPF verifier compliance.
- Engineers MUST ALWAYS implement rate limiting using per-CPU BPF maps (BPF_MAP_TYPE_PERCPU_HASH or BPF_MAP_TYPE_PERCPU_ARRAY) to eliminate cross-CPU spinlock contention under multi-gigabit ingress loads.
- Engineers MUST NOT rely on userspace agents or netfilter/iptables rules for mitigating volumetric L4 UDP/TCP SYN floods, as sk_buff allocation causes ksoftirqd CPU starvation.
- Code MUST return XDP_DROP immediately upon exceeding rate limits without emitting socket buffers up the kernel network stack.
- Services MUST expose control-plane metrics using lockless ring buffers (BPF_MAP_TYPE_RINGBUF) rather than synchronous userspace socket I/O.

## Bad vs Good Implementations
### eBPF XDP Ingress Token Bucket Rate Limiter with Strict Bounds Checking

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Accessing packet structures without validating against ctx->data_end causes immediate verifier rejection or kernel panic. Using a standard BPF_MAP_TYPE_HASH instead of per-CPU maps causes cross-core cache-line bouncing and lock contention, while passing traffic to the stack under flood conditions defeats the purpose of XDP mitigation.
```c
#include <linux/bpf.h>
#include <bpf/bpf_helpers.h>
#include <linux/if_ether.h>
#include <linux/ip.h>

// ANTI-PATTERN: Using global shared hash map with mutex contention, missing bounds check
struct { 
    __uint(type, BPF_MAP_TYPE_HASH);
    __type(key, __u32);
    __type(value, __u64);
    __uint(max_entries, 10240);
} rate_limit_map SEC(".maps");

SEC("xdp")
int xdp_rate_limiter_bad(struct xdp_md *ctx) {
    void *data = (void *)(long)ctx->data;
    struct ethhdr *eth = data;
    // BUG: Missing data_end bounds check triggers verifier error or out-of-bounds read
    struct iphdr *ip = (void *)(eth + 1);
    
    __u32 src_ip = ip->saddr;
    __u64 *tokens = bpf_map_lookup_elem(&rate_limit_map, &src_ip);
    if (tokens && *tokens > 1000) {
        // Handing off to userspace or default stack incurs massive sk_buff overhead
        return XDP_PASS;
    }
    return XDP_PASS;
}
```

#### Production Standard (Correct)
> **Standard**: Implements strict bounds verification against ctx->data_end for every packet header layer, satisfies the eBPF verifier, and employs BPF_MAP_TYPE_PERCPU_HASH to guarantee lockless, zero-contention token-bucket evaluation. Packets exceeding thresholds are dropped immediately with XDP_DROP before sk_buff memory allocation.
```c
#include <linux/bpf.h>
#include <bpf/bpf_helpers.h>
#include <linux/if_ether.h>
#include <linux/ip.h>
#include <linux/in.h>

struct rate_bucket {
    __u64 last_time_ns;
    __u64 tokens;
};

struct {
    __uint(type, BPF_MAP_TYPE_PERCPU_HASH);
    __type(key, __u32);
    __type(value, struct rate_bucket);
    __uint(max_entries, 65536);
} client_buckets SEC(".maps");

#define BUCKET_CAPACITY 100000000ULL // 100MB burst capacity
#define TOKEN_RATE_NS   10ULL        // Replenish rate

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

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

    __u32 src_ip = ip->saddr;
    __u64 now = bpf_ktime_get_ns();
    __u64 packet_len = (__u64)(data_end - data);

    struct rate_bucket *bucket = bpf_map_lookup_elem(&client_buckets, &src_ip);
    if (!bucket) {
        struct rate_bucket new_bucket = {
            .last_time_ns = now,
            .tokens = BUCKET_CAPACITY,
        };
        bpf_map_update_elem(&client_buckets, &src_ip, &new_bucket, BPF_ANY);
        return XDP_PASS;
    }

    __u64 elapsed = now - bucket->last_time_ns;
    bucket->last_time_ns = now;
    bucket->tokens += elapsed / TOKEN_RATE_NS;
    if (bucket->tokens > BUCKET_CAPACITY)
        bucket->tokens = BUCKET_CAPACITY;

    if (bucket->tokens < packet_len)
        return XDP_DROP;

    bucket->tokens -= packet_len;
    return XDP_PASS;
}

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

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: eBPF/XDP Layer-4 Ingress Kernel-Bypass Rate-Limiting Guardrail

eBPF/XDP Layer-4 Ingress Kernel-Bypass Rate-Limiting Guardrail defines an industrial-grade behavioral standard for devops engineering. Offloading L4 connection tracking and volumetric packet filtering to the eBPF XDP hook eliminates kernel network stack overhead and CPU starvation during ingress volumetric bursts. Software systems must leverage driver-mode or native XDP with per-CPU BPF maps and lockless token-bucket rate limiters prior to sk_buff allocation. Failure to decouple rate limiting from the sk_buff allocation pipeline leaves infrastructure vulnerable to softirq saturation and kernel-level denial of service. 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: Processing Layer-4 Rate-Limiting in User Space or Standard iptables/Netfilter Sk_buff Pipeline 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 DriftProcessing Layer-4 Rate-Limiting in User Space or Standard iptables/Netfilter Sk_buff PipelineCritical
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 packet boundaries using data and data_end pointers before reading IP/L4 headers to guarantee eBPF verifier compliance.

Engineers MUST ALWAYS verify packet boundaries using data and data_end pointers before reading IP/L4 headers to guarantee eBPF verifier compliance.

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 rate limiting using per-CPU BPF maps (BPF_MAP_TYPE_PERCPU_HASH or BPF_MAP_TYPE_PERCPU_ARRAY) to eliminate cross-CPU spinlock contention under multi-gigabit ingress loads.

Engineers MUST ALWAYS implement rate limiting using per-CPU BPF maps (BPF_MAP_TYPE_PERCPU_HASH or BPF_MAP_TYPE_PERCPU_ARRAY) to eliminate cross-CPU spinlock contention under multi-gigabit ingress loads.

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 NOT rely on userspace agents or netfilter/iptables rules for mitigating volumetric L4 UDP/TCP SYN floods, as sk_buff allocation causes ksoftirqd CPU starvation.

Engineers MUST NOT rely on userspace agents or netfilter/iptables rules for mitigating volumetric L4 UDP/TCP SYN floods, as sk_buff allocation causes ksoftirqd CPU starvation.

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 MUST return XDP_DROP immediately upon exceeding rate limits without emitting socket buffers up the kernel network stack.

Code MUST return XDP_DROP immediately upon exceeding rate limits without emitting socket buffers up the kernel network stack.

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 expose control-plane metrics using lockless ring buffers (BPF_MAP_TYPE_RINGBUF) rather than synchronous userspace socket I/O.

Services MUST expose control-plane metrics using lockless ring buffers (BPF_MAP_TYPE_RINGBUF) rather than synchronous userspace socket I/O.

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 Layer-4 Ingress Kernel-Bypass Rate-Limiting Guardrail critical for AI coding assistants?

Offloading L4 connection tracking and volumetric packet filtering to the eBPF XDP hook eliminates kernel network stack overhead and CPU starvation during ingress volumetric bursts. Software systems must leverage driver-mode or native XDP with per-CPU BPF maps and lockless token-bucket rate limiters prior to sk_buff allocation. Failure to decouple rate limiting from the sk_buff allocation pipeline leaves infrastructure vulnerable to softirq saturation and kernel-level denial of service. 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 (Processing Layer-4 Rate-Limiting in User Space or Standard iptables/Netfilter Sk_buff Pipeline) 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/XDP