This specification is maintained by the AgentRules Working Group. Have enhancements or want to claim maintainership?Submit Specification →
securitycritical PriorityID: ebpf-tc-ddow-rate-fencing-standard

eBPF TC Ingress Rate-Fencing for L7 Distributed Denial-of-Wallet (DDoW) Prevention

Enforces pre-socket drop semantics at the Linux Traffic Control (TC) clsact qdisc layer using eBPF maps to terminate unauthenticated, replay-heavy, or abusive LLM/serverless API traffic before TCP handshakes and user-space allocations occur. Protects downstream token generation and pay-per-execution cloud billing pipelines from algorithmic economic exhaustion attacks.

Prohibited Anti-Pattern: Delegating High-Volume L7 Rate Limiting and Token Validation to User-Space Application Gateways

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: eBPF TC Ingress Rate-Fencing for L7 Distributed Denial-of-Wallet (DDoW) Prevention - Enforces pre-socket drop semantics at the Linux Traffic Control (TC) clsact qdisc layer using eBPF maps to terminate unauthenticated, replay-heavy, or abusive LLM/serverless API traffic before TCP handshakes and user-space allocations occur. Protects downstream token generation and pay-per-execution cloud billing pipelines from algorithmic economic exhaustion attacks.
globs: src/bpf/**/*.{c,h}, src/network/**/*.{ts,go,rs,c}, infra/k8s/**/*.{yaml,json}, src/security/rate_limiter/**/*.{ts,go,rs}
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/ebpf-tc-ddow-rate-fencing-standard"
---

# eBPF TC Ingress Rate-Fencing for L7 Distributed Denial-of-Wallet (DDoW) Prevention

> **Severity**: CRITICAL | **Category**: security
> **Anti-Pattern Warning**: Delegating High-Volume L7 Rate Limiting and Token Validation to User-Space Application Gateways

## System Constraints
You are a Principal Systems & Network Security Architect enforcing kernel-level eBPF Traffic Control (TC) ingress rate-fencing. You mandate that high-cost LLM API endpoints and serverless functions protect their network perimeter by dropping invalid signatures, malformed API keys, and burst quotas at the Linux kernel packet scheduler level (TC clsact ingress), preventing socket buffer allocation (sk_buff) propagation to user-space runtimes.

## Strict Guidelines
- Engineers MUST ALWAYS enforce rate limits at the eBPF TC (Traffic Control) ingress hook (clsact) before packet transit to the socket layer when cost-per-request exceeds standard I/O baseline.
- Engineers MUST NOT rely exclusively on user-space reverse proxies (e.g., Envoy, Nginx, Node.js gateways) for DDoS/DDoW mitigation against pay-per-token LLM endpoints.
- Code SHOULD inspect raw sk_buff payload offsets via bpf_skb_load_bytes to validate HMAC signatures or prefixed API bearer tokens without full TLS termination where eBPF kTLS or Layer 4 proxy handoff is available.
- Services MUST synchronize user-space token buckets into BPF_MAP_TYPE_LRU_HASH or BPF_MAP_TYPE_PERCPU_ARRAY structures with lockless atomics (__sync_fetch_and_add) to prevent cross-core cache invalidation.
- Components NEVER allow unmetered syn-floods or TCP handshakes to reach user-space endpoints when BPF map lookups indicate token exhaustion; they must return TC_ACT_SHOT immediately.

## Bad vs Good Implementations
### Kernel-Level Token Bucket Ingress Filter in eBPF C

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Forwarding every packet to user-space forces the kernel to complete TCP reassembly and socket buffering, allowing an adversary to execute hundreds of thousands of cheap unauthenticated HTTP requests that deplete serverless runtimes and trigger costly inference pipelines.
```c
// ANTI-PATTERN: Passing all traffic to user-space gateway, deferring rate check to Node.js / Envoy
#include <linux/bpf.h>
#include <bpf/bpf_helpers.h>

SEC("tc")
int handle_ingress(struct __sk_buff *skb) {
    // Incurring full kernel network stack traversal, sk_buff allocation,
    // context switching, and user-space memory allocation for every packet.
    return 0; // TC_ACT_OK -> Forwarding directly to user-space proxy
}
```

#### Production Standard (Correct)
> **Standard**: The BPF program enforces strict leaky/token bucket limits at the TC ingress layer. Dropped packets (TC_ACT_SHOT) bypass user-space socket processing entirely, terminating DDoW amplification and preserving computational billing quotas.
```c
// PRODUCTION STANDARD: Pre-socket rate-drop using eBPF TC and Per-CPU LRU Hash Maps
#include <linux/bpf.h>
#include <linux/pkt_cls.h>
#include <bpf/bpf_helpers.h>
#include <bpf/bpf_endian.h>

struct client_metric {
    __u64 last_timestamp_ns;
    __u32 tokens_remaining;
};

struct {
    __uint(type, BPF_MAP_TYPE_LRU_HASH);
    __uint(max_entries, 1000000);
    __type(key, __u32); // IPv4 src address
    __type(value, struct client_metric);
} rate_limit_map SEC(".maps");

#define BUCKET_BURST_CAP 100
#define REFILL_INTERVAL_NS 1000000000ULL // 1 second

SEC("tc")
int handle_ingress(struct __sk_buff *skb) {
    void *data = (void *)(long)skb->data;
    void *data_end = (void *)(long)skb->data_end;
    
    // Parse IP header
    struct iphdr *ip = data + sizeof(struct ethhdr);
    if ((void *)(ip + 1) > data_end) {
        return TC_ACT_OK;
    }

    __u32 src_ip = ip->saddr;
    __u64 now = bpf_ktime_get_ns();
    struct client_metric *metric = bpf_map_lookup_elem(&rate_limit_map, &src_ip);

    if (!metric) {
        struct client_metric init_m = { .last_timestamp_ns = now, .tokens_remaining = BUCKET_BURST_CAP - 1 };
        bpf_map_update_elem(&rate_limit_map, &src_ip, &init_m, BPF_ANY);
        return TC_ACT_OK;
    }

    // Token refill calculation
    if (now - metric->last_timestamp_ns > REFILL_INTERVAL_NS) {
        metric->tokens_remaining = BUCKET_BURST_CAP;
        metric->last_timestamp_ns = now;
    }

    if (metric->tokens_remaining == 0) {
        // HARD DROP: Mitigate DDoW at driver layer
        return TC_ACT_SHOT;
    }

    __sync_fetch_and_sub(&metric->tokens_remaining, 1);
    return TC_ACT_OK;
}
```

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 TC Ingress Rate-Fencing for L7 Distributed Denial-of-Wallet (DDoW) Prevention

eBPF TC Ingress Rate-Fencing for L7 Distributed Denial-of-Wallet (DDoW) Prevention defines an industrial-grade behavioral standard for security engineering. Enforces pre-socket drop semantics at the Linux Traffic Control (TC) clsact qdisc layer using eBPF maps to terminate unauthenticated, replay-heavy, or abusive LLM/serverless API traffic before TCP handshakes and user-space allocations occur. Protects downstream token generation and pay-per-execution cloud billing pipelines from algorithmic economic exhaustion attacks. 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 High-Volume L7 Rate Limiting and Token Validation to User-Space Application Gateways 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 High-Volume L7 Rate Limiting and Token Validation to User-Space Application GatewaysCritical
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 enforce rate limits at the eBPF TC (Traffic Control) ingress hook (clsact) before packet transit to the socket layer when cost-per-request exceeds standard I/O baseline.

Engineers MUST ALWAYS enforce rate limits at the eBPF TC (Traffic Control) ingress hook (clsact) before packet transit to the socket layer when cost-per-request exceeds standard I/O baseline.

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 rely exclusively on user-space reverse proxies (e.g., Envoy, Nginx, Node.js gateways) for DDoS/DDoW mitigation against pay-per-token LLM endpoints.

Engineers MUST NOT rely exclusively on user-space reverse proxies (e.g., Envoy, Nginx, Node.js gateways) for DDoS/DDoW mitigation against pay-per-token LLM endpoints.

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 SHOULD inspect raw sk_buff payload offsets via bpf_skb_load_bytes to validate HMAC signatures or prefixed API bearer tokens without full TLS termination where eBPF kTLS or Layer 4 proxy handoff is available.

Code SHOULD inspect raw sk_buff payload offsets via bpf_skb_load_bytes to validate HMAC signatures or prefixed API bearer tokens without full TLS termination where eBPF kTLS or Layer 4 proxy handoff is available.

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 synchronize user-space token buckets into BPF_MAP_TYPE_LRU_HASH or BPF_MAP_TYPE_PERCPU_ARRAY structures with lockless atomics (__sync_fetch_and_add) to prevent cross-core cache invalidation.

Services MUST synchronize user-space token buckets into BPF_MAP_TYPE_LRU_HASH or BPF_MAP_TYPE_PERCPU_ARRAY structures with lockless atomics (__sync_fetch_and_add) to prevent cross-core cache invalidation.

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 allow unmetered syn-floods or TCP handshakes to reach user-space endpoints when BPF map lookups indicate token exhaustion

Components NEVER allow unmetered syn-floods or TCP handshakes to reach user-space endpoints when BPF map lookups indicate token exhaustion; they must return TC_ACT_SHOT immediately.

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 TC Ingress Rate-Fencing for L7 Distributed Denial-of-Wallet (DDoW) Prevention critical for AI coding assistants?

Enforces pre-socket drop semantics at the Linux Traffic Control (TC) clsact qdisc layer using eBPF maps to terminate unauthenticated, replay-heavy, or abusive LLM/serverless API traffic before TCP handshakes and user-space allocations occur. Protects downstream token generation and pay-per-execution cloud billing pipelines from algorithmic economic exhaustion attacks. 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 High-Volume L7 Rate Limiting and Token Validation to User-Space Application Gateways) 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