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

eBPF TCX Kernel Ingress Token-Bucket Shaping and L4 SYN Flood Mitigation Standard

Defines strict invariants for high-throughput packet filtering using modern eBPF TCX (Traffic Control BPF link) hooks on network device ingress. Enforces per-IP and per-CIDR atomic token-bucket rate limiting and stateless SYN-cookie verification directly in the eBPF layer before SKB allocation occurs in the Linux network stack.

Prohibited Anti-Pattern: Naive Userspace or iptables Rate Limiting Incurring Kernel SKB Allocation Bottlenecks Under L4 Volumetric Floods

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: eBPF TCX Kernel Ingress Token-Bucket Shaping and L4 SYN Flood Mitigation Standard - Defines strict invariants for high-throughput packet filtering using modern eBPF TCX (Traffic Control BPF link) hooks on network device ingress. Enforces per-IP and per-CIDR atomic token-bucket rate limiting and stateless SYN-cookie verification directly in the eBPF layer before SKB allocation occurs in the Linux network stack.
globs: **/*.bpf.c, **/*.bpf.h, src/network/**/*.c, deploy/ebpf/**/*.c, infra/ebpf/**/*.go
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/ebpf-tcx-ingress-token-bucket-handshake-standard"
---

# eBPF TCX Kernel Ingress Token-Bucket Shaping and L4 SYN Flood Mitigation Standard

> **Severity**: CRITICAL | **Category**: devops
> **Anti-Pattern Warning**: Naive Userspace or iptables Rate Limiting Incurring Kernel SKB Allocation Bottlenecks Under L4 Volumetric Floods

## System Constraints
You are a Principal Linux Kernel and Systems Architect enforcing the eBPF TCX Kernel Ingress Token-Bucket Shaping and L4 Handshake Standard. Mandate that all packet parsing validates direct packet boundaries against data_end before dereferencing, token bucket updates use atomic intrinsics or BPF spinlocks to avoid race conditions under concurrency, and unauthenticated TCP SYN floods are strictly shaped or dropped via TCX_INGRESS return codes before socket allocations (sk_buff) trigger kernel CPU starvation.

## Strict Guidelines
- Engineers MUST ALWAYS verify packet bounds (e.g., `(void *)(iph + 1) > data_end`) before accessing any IPv4/IPv6 or TCP/UDP header fields to satisfy the BPF verifier.
- Engineers MUST NOT use un-synchronized read-modify-write patterns on BPF map elements; all token-bucket updates MUST utilize `__sync_fetch_and_add` or `bpf_spin_lock` to prevent concurrency leaks.
- Engineers MUST configure eBPF TC attachments using the modern TCX link API (`SEC("tc/ingress")` with `bpf_program__attach_tcx`) rather than legacy `clsact` qdisc netlink attachments to prevent hook detaching during daemon crashes.
- Programs MUST return `TCX_DROP` immediately upon rate exhaustion or invalid checksums rather than passing packets to `TCX_PASS` or delegating filtering to upper iptables/nftables layers.
- Map allocations for IP tracking MUST use `BPF_MAP_TYPE_LRU_HASH` or pre-allocated per-CPU hash maps to eliminate memory allocation latency under high-cardinality volumetric floods.

## Bad vs Good Implementations
### TCX Ingress Rate-Limiting and Packet Header Boundary Validation

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Fails verifier bounds checking on Ethernet, IP, and TCP headers, uses deprecated BPF map definitions prone to unbounded memory growth (BPF_MAP_TYPE_HASH instead of LRU), performs unsynchronized decrements leading to race conditions under multi-core traffic, and uses legacy TC return codes.
```c
#include <linux/bpf.h>
#include <bpf/bpf_helpers.h>
#include <linux/if_ether.h>
#include <linux/ip.h>
#include <linux/tcp.h>

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

SEC("tc")
int bad_filter(struct __sk_buff *skb) {
    void *data = (void *)(long)skb->data;
    void *data_end = (void *)(long)skb->data_end;
    
    // CRITICAL: Unchecked pointer dereference; verifier failure and kernel panic risk
    struct ethhdr *eth = data;
    struct iphdr *ip = (void *)(eth + 1);
    struct tcphdr *tcp = (void *)(ip + 1);
    
    // CRITICAL: Non-atomic access subject to race conditions and exhaustion under heavy traffic
    __u64 *tokens = bpf_map_lookup_elem(&ip_limits, &ip->saddr);
    if (tokens && *tokens > 0) {
        *tokens = *tokens - 1;
        return 0; // TC_ACT_OK
    }
    return 2; // TC_ACT_SHOT
}
```

#### Production Standard (Correct)
> **Standard**: Implements rigorous pointer bounds verification passing the eBPF verifier, uses modern BTF-defined `BPF_MAP_TYPE_LRU_HASH` preventing out-of-memory kernel locks, encapsulates critical token replenishment math in `bpf_spin_lock`, and utilizes standard TCX hook return conventions.
```c
#include "vmlinux.h"
#include <bpf/bpf_helpers.h>
#include <bpf/bpf_endian.h>

#define TCX_PASS 0
#define TCX_DROP 2
#define RATE_LIMIT_TOKENS 1000

struct bucket_val {
    struct bpf_spin_lock lock;
    __u64 last_update_ns;
    __s64 tokens;
};

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

SEC("tc/ingress")
int ingress_token_bucket(struct __sk_buff *skb) {
    void *data = (void *)(long)skb->data;
    void *data_end = (void *)(long)skb->data_end;

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

    if (eth->h_proto != bpf_htons(ETH_P_IP))
        return TCX_PASS;

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

    if (ip->protocol != IPPROTO_TCP)
        return TCX_PASS;

    struct tcphdr *tcp = (void *)(ip + 1);
    if ((void *)(tcp + 1) > data_end)
        return TCX_DROP;

    __u32 src_ip = ip->saddr;
    struct bucket_val *b = bpf_map_lookup_elem(&rate_limit_map, &src_ip);
    if (!b) {
        struct bucket_val initial = { .last_update_ns = bpf_ktime_get_ns(), .tokens = RATE_LIMIT_TOKENS - 1 };
        bpf_map_update_elem(&rate_limit_map, &src_ip, &initial, BPF_NOEXIST);
        return TCX_PASS;
    }

    bpf_spin_lock(&b->lock);
    __u64 now = bpf_ktime_get_ns();
    __u64 elapsed = now - b->last_update_ns;
    b->last_update_ns = now;
    // Refill 1 token per 100 microseconds (10,000 pkts/sec)
    b->tokens += (elapsed / 100000ULL);
    if (b->tokens > RATE_LIMIT_TOKENS)
        b->tokens = RATE_LIMIT_TOKENS;

    if (b->tokens <= 0) {
        bpf_spin_unlock(&b->lock);
        return TCX_DROP;
    }

    b->tokens--;
    bpf_spin_unlock(&b->lock);
    return TCX_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 TCX Kernel Ingress Token-Bucket Shaping and L4 SYN Flood Mitigation Standard

eBPF TCX Kernel Ingress Token-Bucket Shaping and L4 SYN Flood Mitigation Standard defines an industrial-grade behavioral standard for devops engineering. Defines strict invariants for high-throughput packet filtering using modern eBPF TCX (Traffic Control BPF link) hooks on network device ingress. Enforces per-IP and per-CIDR atomic token-bucket rate limiting and stateless SYN-cookie verification directly in the eBPF layer before SKB allocation occurs in the Linux network stack. 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: Naive Userspace or iptables Rate Limiting Incurring Kernel SKB Allocation Bottlenecks Under L4 Volumetric Floods 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 DriftNaive Userspace or iptables Rate Limiting Incurring Kernel SKB Allocation Bottlenecks Under L4 Volumetric FloodsCritical
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 bounds (e.g., `(void *)(iph + 1) > data_end`) before accessing any IPv4/IPv6 or TCP/UDP header fields to satisfy the BPF verifier.

Engineers MUST ALWAYS verify packet bounds (e.g., `(void *)(iph + 1) > data_end`) before accessing any IPv4/IPv6 or TCP/UDP header fields 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.
2

Engineers MUST NOT use un-synchronized read-modify-write patterns on BPF map elements

Engineers MUST NOT use un-synchronized read-modify-write patterns on BPF map elements; all token-bucket updates MUST utilize `__sync_fetch_and_add` or `bpf_spin_lock` to prevent concurrency leaks.

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 configure eBPF TC attachments using the modern TCX link API (`SEC("tc/ingress")` with `bpf_program__attach_tcx`) rather than legacy `clsact` qdisc netlink attachments to prevent hook detaching during daemon crashes.

Engineers MUST configure eBPF TC attachments using the modern TCX link API (`SEC("tc/ingress")` with `bpf_program__attach_tcx`) rather than legacy `clsact` qdisc netlink attachments to prevent hook detaching during daemon crashes.

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

Programs MUST return `TCX_DROP` immediately upon rate exhaustion or invalid checksums rather than passing packets to `TCX_PASS` or delegating filtering to upper iptables/nftables layers.

Programs MUST return `TCX_DROP` immediately upon rate exhaustion or invalid checksums rather than passing packets to `TCX_PASS` or delegating filtering to upper iptables/nftables layers.

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

Map allocations for IP tracking MUST use `BPF_MAP_TYPE_LRU_HASH` or pre-allocated per-CPU hash maps to eliminate memory allocation latency under high-cardinality volumetric floods.

Map allocations for IP tracking MUST use `BPF_MAP_TYPE_LRU_HASH` or pre-allocated per-CPU hash maps to eliminate memory allocation latency under high-cardinality volumetric floods.

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 TCX Kernel Ingress Token-Bucket Shaping and L4 SYN Flood Mitigation Standard critical for AI coding assistants?

Defines strict invariants for high-throughput packet filtering using modern eBPF TCX (Traffic Control BPF link) hooks on network device ingress. Enforces per-IP and per-CIDR atomic token-bucket rate limiting and stateless SYN-cookie verification directly in the eBPF layer before SKB allocation occurs in the Linux network stack. 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 (Naive Userspace or iptables Rate Limiting Incurring Kernel SKB Allocation Bottlenecks Under L4 Volumetric Floods) 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