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

eBPF XDP Line-Rate Rate-Limiting & Lockless Map Invariants

Enforces lockless eBPF LRU/Per-CPU map synchronization and atomic token bucket rate-limiting at the XDP driver hook to preserve host kernel CPU headroom during volumetric L4 DDoS attacks. Prohibits global spinlocks, non-per-cpu allocations, and blocking user-space batch synchronization operations that induce softirq tail drops.

Prohibited Anti-Pattern: Global BPF Hash Map Mutations Under Volumetric L4 Ingress Inducing Softirq Saturation and Driver Ring Buffer Drops

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: eBPF XDP Line-Rate Rate-Limiting & Lockless Map Invariants - Enforces lockless eBPF LRU/Per-CPU map synchronization and atomic token bucket rate-limiting at the XDP driver hook to preserve host kernel CPU headroom during volumetric L4 DDoS attacks. Prohibits global spinlocks, non-per-cpu allocations, and blocking user-space batch synchronization operations that induce softirq tail drops.
globs: **/*.bpf.c, **/*.bpf.h, src/network/**/*.c, src/ebpf/**/*.rs, pkg/ebpf/**/*.go
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/ebpf-xdp-ratelimit-map-sync-guardrail"
---

# eBPF XDP Line-Rate Rate-Limiting & Lockless Map Invariants

> **Severity**: CRITICAL | **Category**: devops
> **Anti-Pattern Warning**: Global BPF Hash Map Mutations Under Volumetric L4 Ingress Inducing Softirq Saturation and Driver Ring Buffer Drops

## System Constraints
You are a Principal Linux Kernel and Network Systems Engineer specializing in eBPF XDP high-throughput packet processing. Mandate zero-copy, lockless map access patterns, bounded verifier-compliant token bucket rate-limiters, and per-cpu data structures. Prohibit any pattern that causes ksoftirqd CPU starvation, unbounded map lookups, or user-space sync stalls under multi-million packet-per-second (Mpps) loads.

## Strict Guidelines
- Engineers MUST ALWAYS use BPF_MAP_TYPE_LRU_PERCPU_HASH or BPF_MAP_TYPE_PERCPU_ARRAY for high-frequency tracking maps to prevent cross-core cache-line bouncing and global spinlock contention.
- Engineers MUST ALWAYS implement lockless token bucket rate limiting using __sync_fetch_and_add or atomic compare-and-swap primitives over raw 64-bit integer state when updating shared flow counters.
- Engineers MUST NOT invoke bpf_map_update_elem from the XDP fast path with BPF_NOEXIST on standard BPF_MAP_TYPE_HASH when facing spoofed-IP volumetric attacks; use LRU maps to avoid dynamic slab memory allocations.
- Code MUST return XDP_DROP immediately at the earliest possible verification boundary (after minimal header parsing) when ingress packet metrics exceed configured token bucket capacities.
- Services MUST synchronize state from kernel to user space using BPF_MAP_LOOKUP_AND_DELETE_BATCH or ring buffers (BPF_MAP_TYPE_RINGBUF) rather than executing individual synchronous syscall lookups per flow.
- Components NEVER execute unbounded packet-walking loops; loops must be bounded with #pragma unroll or verifier-bounded induction variables with static upper limits (<= 64).

## Bad vs Good Implementations
### Lockless XDP Token Bucket Rate Limiting with Per-CPU LRU Maps

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Using standard BPF_MAP_TYPE_HASH with bpf_spin_lock and dynamic insertions under L4 DDoS attacks causes catastrophic softirq CPU starvation, cache line contention across RX queues, and slab memory exhaustion.
```c
#include <linux/bpf.h>
#include <bpf/bpf_helpers.h>

// ANTI-PATTERN: Global Hash Map with blocking spinlock and dynamic slab allocation
struct rate_limit_entry {
    struct bpf_spin_lock lock;
    __u64 last_time;
    __u64 tokens;
};

struct {
    __uint(type, BPF_MAP_TYPE_HASH);
    __uint(max_entries, 1000000);
    __type(key, __u32); // IPv4
    __type(value, struct rate_limit_entry);
} flow_map SEC(".maps");

SEC("xdp")
int xdp_drop_flow(struct xdp_md *ctx) {
    void *data = (void *)(long)ctx->data;
    void *data_end = (void *)(long)ctx->data_end;
    // Omitted: parse headers to find src_ip
    __u32 src_ip = 0x0A000001;

    struct rate_limit_entry *entry = bpf_map_lookup_elem(&flow_map, &src_ip);
    if (!entry) {
        struct rate_limit_entry new_entry = {0};
        // Severe latency: allocates in softirq context, locks out other cores
        bpf_map_update_elem(&flow_map, &src_ip, &new_entry, BPF_NOEXIST);
        return XDP_PASS;
    }

    bpf_spin_lock(&entry->lock);
    // Lock contention halts CPU cores processing other RX queues
    entry->tokens += 100;
    bpf_spin_unlock(&entry->lock);
    return XDP_PASS;
}
```

#### Production Standard (Correct)
> **Standard**: Utilizes BPF_MAP_TYPE_LRU_PERCPU_HASH to completely eliminate cross-CPU lock contention and memory allocation overhead. Drops non-conforming packets instantly at the XDP driver level, preserving driver ring buffer integrity.
```c
#include <linux/bpf.h>
#include <bpf/bpf_helpers.h>

// PRODUCTION INVARIANT: Per-CPU LRU prevents contention and slab memory exhaustion
struct token_bucket {
    __u64 last_ns;
    __u64 tokens;
};

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

#define RATE_LIMIT_NS   1000000000ULL
#define BURST_CAPACITY  50000ULL
#define COST_PER_PKT    1ULL

SEC("xdp")
int xdp_ratelimit_ingress(struct xdp_md *ctx) {
    void *data = (void *)(long)ctx->data;
    void *data_end = (void *)(long)ctx->data_end;
    // Verify boundary constraints for verifier safety
    if (data + sizeof(__u32) > data_end)
        return XDP_DROP;

    __u32 src_ip = *(__u32 *)data; // Simplified header access
    __u64 now = bpf_ktime_get_ns();

    struct token_bucket *bucket = bpf_map_lookup_elem(&rate_limit_map, &src_ip);
    if (!bucket) {
        struct token_bucket init_bucket = { .last_ns = now, .tokens = BURST_CAPACITY - COST_PER_PKT };
        bpf_map_update_elem(&rate_limit_map, &src_ip, &init_bucket, BPF_ANY);
        return XDP_PASS;
    }

    // Lockless update inside per-cpu context: zero cross-core cache invalidation
    __u64 elapsed = now - bucket->last_ns;
    bucket->last_ns = now;
    bucket->tokens += (elapsed * BURST_CAPACITY) / RATE_LIMIT_NS;
    if (bucket->tokens > BURST_CAPACITY)
        bucket->tokens = BURST_CAPACITY;

    if (bucket->tokens < COST_PER_PKT)
        return XDP_DROP; // Drop at NIC driver boundary

    bucket->tokens -= COST_PER_PKT;
    return XDP_PASS;
}
```

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 Line-Rate Rate-Limiting & Lockless Map Invariants

eBPF XDP Line-Rate Rate-Limiting & Lockless Map Invariants defines an industrial-grade behavioral standard for devops engineering. Enforces lockless eBPF LRU/Per-CPU map synchronization and atomic token bucket rate-limiting at the XDP driver hook to preserve host kernel CPU headroom during volumetric L4 DDoS attacks. Prohibits global spinlocks, non-per-cpu allocations, and blocking user-space batch synchronization operations that induce softirq tail drops. 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: Global BPF Hash Map Mutations Under Volumetric L4 Ingress Inducing Softirq Saturation and Driver Ring Buffer Drops 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 DriftGlobal BPF Hash Map Mutations Under Volumetric L4 Ingress Inducing Softirq Saturation and Driver Ring Buffer DropsCritical
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 use BPF_MAP_TYPE_LRU_PERCPU_HASH or BPF_MAP_TYPE_PERCPU_ARRAY for high-frequency tracking maps to prevent cross-core cache-line bouncing and global spinlock contention.

Engineers MUST ALWAYS use BPF_MAP_TYPE_LRU_PERCPU_HASH or BPF_MAP_TYPE_PERCPU_ARRAY for high-frequency tracking maps to prevent cross-core cache-line bouncing and global spinlock contention.

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 lockless token bucket rate limiting using __sync_fetch_and_add or atomic compare-and-swap primitives over raw 64-bit integer state when updating shared flow counters.

Engineers MUST ALWAYS implement lockless token bucket rate limiting using __sync_fetch_and_add or atomic compare-and-swap primitives over raw 64-bit integer state when updating shared flow counters.

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 invoke bpf_map_update_elem from the XDP fast path with BPF_NOEXIST on standard BPF_MAP_TYPE_HASH when facing spoofed-IP volumetric attacks

Engineers MUST NOT invoke bpf_map_update_elem from the XDP fast path with BPF_NOEXIST on standard BPF_MAP_TYPE_HASH when facing spoofed-IP volumetric attacks; use LRU maps to avoid dynamic slab memory allocations.

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 at the earliest possible verification boundary (after minimal header parsing) when ingress packet metrics exceed configured token bucket capacities.

Code MUST return XDP_DROP immediately at the earliest possible verification boundary (after minimal header parsing) when ingress packet metrics exceed configured token bucket capacities.

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 synchronize state from kernel to user space using BPF_MAP_LOOKUP_AND_DELETE_BATCH or ring buffers (BPF_MAP_TYPE_RINGBUF) rather than executing individual synchronous syscall lookups per flow.

Services MUST synchronize state from kernel to user space using BPF_MAP_LOOKUP_AND_DELETE_BATCH or ring buffers (BPF_MAP_TYPE_RINGBUF) rather than executing individual synchronous syscall lookups per flow.

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

Components NEVER execute unbounded packet-walking loops

Components NEVER execute unbounded packet-walking loops; loops must be bounded with #pragma unroll or verifier-bounded induction variables with static upper limits (<= 64).

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 Line-Rate Rate-Limiting & Lockless Map Invariants critical for AI coding assistants?

Enforces lockless eBPF LRU/Per-CPU map synchronization and atomic token bucket rate-limiting at the XDP driver hook to preserve host kernel CPU headroom during volumetric L4 DDoS attacks. Prohibits global spinlocks, non-per-cpu allocations, and blocking user-space batch synchronization operations that induce softirq tail drops. 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 (Global BPF Hash Map Mutations Under Volumetric L4 Ingress Inducing Softirq Saturation and Driver Ring Buffer Drops) 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