This specification is maintained by the AgentRules Working Group. Have enhancements or want to claim maintainership?Submit Specification →
devopscritical PriorityID: ebpf-sockmap-zero-copy-flow-control-standard

eBPF Sockmap Zero-Copy Socket Redirection Flow-Control Standard

Bypasses the full TCP/IP kernel stack overhead for node-local service-mesh sidecar hops using verified BPF sockops redirection with active backpressure detection. Mandates sk_msg redirection bounds checking, write-buffer occupancy telemetry, and explicit fallback paths to prevent silent socket stall and ring-buffer starvation.

Prohibited Anti-Pattern: Blind BPF_SOCK_OPS socket redirection without write-queue backpressure monitoring and fallback routing

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: eBPF Sockmap Zero-Copy Socket Redirection Flow-Control Standard - Bypasses the full TCP/IP kernel stack overhead for node-local service-mesh sidecar hops using verified BPF sockops redirection with active backpressure detection. Mandates sk_msg redirection bounds checking, write-buffer occupancy telemetry, and explicit fallback paths to prevent silent socket stall and ring-buffer starvation.
globs: bpf/**/*.c, bpf/**/*.h, src/mesh/ebpf/**/*.go, src/mesh/ebpf/**/*.rs, src/mesh/ebpf/**/*.c, pkg/ebpf/**/*.go
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/ebpf-sockmap-zero-copy-flow-control-standard"
---

# eBPF Sockmap Zero-Copy Socket Redirection Flow-Control Standard

> **Severity**: CRITICAL | **Category**: devops
> **Anti-Pattern Warning**: Blind BPF_SOCK_OPS socket redirection without write-queue backpressure monitoring and fallback routing

## System Constraints
You are a Principal Systems & DevOps Engineer enforcing kernel-grade standards for eBPF sockmap redirection. When accelerating node-local service-mesh proxies (e.g., Envoy sidecars) via sockops and sockmap, you must enforce strict memory backpressure detection, atomic map updates, and deterministic fallbacks to standard TCP/IP. Never allow blind bpf_msg_redirect_hash calls without verifying write-queue capacity and handling BPF_F_INGRESS drops.

## Strict Guidelines
- Engineers MUST ALWAYS inspect socket write-queue thresholds (sk_wmem_alloc vs. sk_sndbuf) before invoking bpf_msg_redirect_hash or bpf_msg_redirect_map.
- Engineers MUST ALWAYS implement a deterministic fallback to standard TCP/IP processing (returning SK_PASS) whenever redirection fails or target socket maps lack capacity.
- Programs MUST verify 5-tuple locality (both src and dst loopback/node-local addresses) within BPF_SOCK_OPS_ACTIVE_ESTABLISHED_CB before inserting sockets into the sock_hash map.
- Engineers MUST NOT issue bpf_sock_hash_update without holding or validating synchronization primitives to eliminate races during rapid socket teardown (BPF_SOCK_OPS_STATE_CB).
- Sockmap programs MUST register error counters using BPF per-CPU telemetry maps to track SK_DROP events caused by socket buffer overflow.
- Engineers MUST compile with strict BPF CO-RE (Compile Once – Run Everywhere) conventions and guard against kernel-version-dependent struct sock offset shifts.

## Bad vs Good Implementations
### Bypass Full TCP Stack with Active Backpressure and Safe Fallback (C/eBPF)

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Directly redirecting without checking write buffer exhaustion or socket ingress thresholds drops packets on overflow, causing silent connection timeouts and mesh desynchronization.
```c
#include <linux/bpf.h>
#include <bpf/bpf_helpers.h>

struct {
    __uint(type, BPF_MAP_TYPE_SOCKHASH);
    __uint(max_entries, 65535);
    __type(key, struct sock_key);
    __type(value, __u64);
} sock_ops_map SEC(".maps");

SEC("sk_msg")
int bpf_tcp_msg_redirect(struct sk_msg_md *msg) {
    struct sock_key key = {};
    // ANTI-PATTERN: Blind redirection without inspecting socket send buffer
    // or verifying if destination is saturated. Returns SK_DROP on failure,
    // completely blackholing the sidecar connection during high ingress load.
    int ret = bpf_msg_redirect_hash(msg, &sock_ops_map, &key, BPF_F_INGRESS);
    if (ret != SK_PASS) {
        return SK_DROP;
    }
    return SK_PASS;
}
```

#### Production Standard (Correct)
> **Standard**: Enforces deterministic SK_PASS fallback when sockmap hash routing encounters full queues or unmapped targets, accompanied by atomic telemetry counters to track kernel stack escalations.
```c
#include <linux/bpf.h>
#include <linux/bpf_common.h>
#include <bpf/bpf_helpers.h>
#include <bpf/bpf_core_read.h>

struct sock_key {
    __u32 sip4;
    __u32 dip4;
    __u16 sport;
    __u16 dport;
};

struct {
    __uint(type, BPF_MAP_TYPE_SOCKHASH);
    __uint(max_entries, 65535);
    __type(key, struct sock_key);
    __type(value, __u64);
} sock_ops_map SEC(".maps");

struct {
    __uint(type, BPF_MAP_TYPE_PERCPU_ARRAY);
    __uint(max_entries, 1);
    __type(key, __u32);
    __type(value, __u64);
} drop_metrics SEC(".maps");

SEC("sk_msg")
int bpf_tcp_msg_redirect(struct sk_msg_md *msg) {
    struct sock_key key = {
        .sip4 = msg->local_ip4,
        .dip4 = msg->remote_ip4,
        .sport = msg->local_port,
        .dport = msg->remote_port,
    };

    // Invariant: Always test redirection and fall back smoothly to the standard TCP stack (SK_PASS)
    // when socket buffer headroom is constrained or sockmap lookup fails.
    long ret = bpf_msg_redirect_hash(msg, &sock_ops_map, &key, BPF_F_INGRESS);
    if (ret != SK_PASS) {
        __u32 zero = 0;
        __u64 *drop_cnt = bpf_map_lookup_elem(&drop_metrics, &zero);
        if (drop_cnt) {
            __sync_fetch_and_add(drop_cnt, 1);
        }
        // Graceful fallback to TCP/IP network stack without dropping the frame
        return SK_PASS;
    }

    return SK_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 Sockmap Zero-Copy Socket Redirection Flow-Control Standard

eBPF Sockmap Zero-Copy Socket Redirection Flow-Control Standard defines an industrial-grade behavioral standard for devops engineering. Bypasses the full TCP/IP kernel stack overhead for node-local service-mesh sidecar hops using verified BPF sockops redirection with active backpressure detection. Mandates sk_msg redirection bounds checking, write-buffer occupancy telemetry, and explicit fallback paths to prevent silent socket stall and ring-buffer starvation. 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: Blind BPF_SOCK_OPS socket redirection without write-queue backpressure monitoring and fallback routing 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 DriftBlind BPF_SOCK_OPS socket redirection without write-queue backpressure monitoring and fallback routingCritical
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 inspect socket write-queue thresholds (sk_wmem_alloc vs. sk_sndbuf) before invoking bpf_msg_redirect_hash or bpf_msg_redirect_map.

Engineers MUST ALWAYS inspect socket write-queue thresholds (sk_wmem_alloc vs. sk_sndbuf) before invoking bpf_msg_redirect_hash or bpf_msg_redirect_map.

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 a deterministic fallback to standard TCP/IP processing (returning SK_PASS) whenever redirection fails or target socket maps lack capacity.

Engineers MUST ALWAYS implement a deterministic fallback to standard TCP/IP processing (returning SK_PASS) whenever redirection fails or target socket maps lack capacity.

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

Programs MUST verify 5-tuple locality (both src and dst loopback/node-local addresses) within BPF_SOCK_OPS_ACTIVE_ESTABLISHED_CB before inserting sockets into the sock_hash map.

Programs MUST verify 5-tuple locality (both src and dst loopback/node-local addresses) within BPF_SOCK_OPS_ACTIVE_ESTABLISHED_CB before inserting sockets into the sock_hash map.

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

Engineers MUST NOT issue bpf_sock_hash_update without holding or validating synchronization primitives to eliminate races during rapid socket teardown (BPF_SOCK_OPS_STATE_CB).

Engineers MUST NOT issue bpf_sock_hash_update without holding or validating synchronization primitives to eliminate races during rapid socket teardown (BPF_SOCK_OPS_STATE_CB).

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

Sockmap programs MUST register error counters using BPF per-CPU telemetry maps to track SK_DROP events caused by socket buffer overflow.

Sockmap programs MUST register error counters using BPF per-CPU telemetry maps to track SK_DROP events caused by socket buffer overflow.

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

Engineers MUST compile with strict BPF CO-RE (Compile Once – Run Everywhere) conventions and guard against kernel-version-dependent struct sock offset shifts.

Engineers MUST compile with strict BPF CO-RE (Compile Once – Run Everywhere) conventions and guard against kernel-version-dependent struct sock offset shifts.

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 Sockmap Zero-Copy Socket Redirection Flow-Control Standard critical for AI coding assistants?

Bypasses the full TCP/IP kernel stack overhead for node-local service-mesh sidecar hops using verified BPF sockops redirection with active backpressure detection. Mandates sk_msg redirection bounds checking, write-buffer occupancy telemetry, and explicit fallback paths to prevent silent socket stall and ring-buffer starvation. 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 (Blind BPF_SOCK_OPS socket redirection without write-queue backpressure monitoring and fallback routing) 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