This specification is maintained by the AgentRules Working Group. Have enhancements or want to claim maintainership?Submit Specification →
devopscritical PriorityID: ebpf-so-reuseport-connection-draining-standard

eBPF SO_REUSEPORT Socket Map Connection Draining and Zero-Loss Handoff Standard

Enforces deterministic, zero-packet-loss rolling process deployments by orchestrating eBPF BPF_PROG_TYPE_SK_REUSEPORT programs and BPF_MAP_TYPE_REUSEPORT_SOCKARRAY maps. Mandates atomic ingress TCP socket redirection to new generation worker groups while draining established connections on legacy workers before SIGKILL/close. Eliminates kernel-level SYN backlog resets and RST injection caused by naive process termination or standard SO_REUSEPORT round-robin distribution during shutdown.

Prohibited Anti-Pattern: Terminating SO_REUSEPORT Listeners Without eBPF Socket Map Steering and Synchronized Backlog Evacuation

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: eBPF SO_REUSEPORT Socket Map Connection Draining and Zero-Loss Handoff Standard - Enforces deterministic, zero-packet-loss rolling process deployments by orchestrating eBPF BPF_PROG_TYPE_SK_REUSEPORT programs and BPF_MAP_TYPE_REUSEPORT_SOCKARRAY maps. Mandates atomic ingress TCP socket redirection to new generation worker groups while draining established connections on legacy workers before SIGKILL/close. Eliminates kernel-level SYN backlog resets and RST injection caused by naive process termination or standard SO_REUSEPORT round-robin distribution during shutdown.
globs: src/**/*.{c,h,rs,go,ts,js}, ebpf/**/*.{c,h}, deployments/**/*.{yaml,json}, scripts/**/*.{sh,py}
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/ebpf-so-reuseport-connection-draining-standard"
---

# eBPF SO_REUSEPORT Socket Map Connection Draining and Zero-Loss Handoff Standard

> **Severity**: CRITICAL | **Category**: devops
> **Anti-Pattern Warning**: Terminating SO_REUSEPORT Listeners Without eBPF Socket Map Steering and Synchronized Backlog Evacuation

## System Constraints
You are a Principal Systems and Infrastructure Architect enforcing deterministic zero-downtime rolling updates using Linux eBPF SO_REUSEPORT socket map filtering (BPF_PROG_TYPE_SK_REUSEPORT). Ensure that no worker process closes its listening socket or exits while unaccepted handshakes remain in the kernel SYN queue or reuseport array. Reject any deployment orchestration relying solely on user-space process SIGTERM signals or vanilla round-robin SO_REUSEPORT kernel load balancing.

## Strict Guidelines
- Engineers MUST ALWAYS attach a BPF_PROG_TYPE_SK_REUSEPORT eBPF program to the primary listening socket group prior to binding multiple SO_REUSEPORT instances across generation boundaries.
- Engineers MUST update the underlying BPF_MAP_TYPE_REUSEPORT_SOCKARRAY or BPF_MAP_TYPE_SOCKMAP atomically, routing new incoming SYN packets exclusively to newly provisioned worker processes before signaling the retiring worker process.
- Engineers MUST NOT rely on default kernel SO_REUSEPORT round-robin hashing (which routes SYN packets across all active sockets regardless of shutdown state, causing ECONNRESET/connection aborts if a process exits with unaccepted SYN backlog entries).
- Retiring worker services MUST enter a deterministic connection drain phase: stop accepting new handshakes from the eBPF map, fully consume all established entries in the existing listen backlog via accept4(2), wait for active in-flight L7 transactions to finish, and ONLY THEN close the listening file descriptor.
- Orchestration scripts MUST verify via bpftool or direct sockmap inspection that the old process socket file descriptor has been deleted from the reuseport sockarray before issuing SIGTERM to the old worker daemon.
- Rollback procedures MUST support atomic swap-back in the BPF map targeting healthy legacy worker sockets if new generation workers fail health checks prior to traffic cutover completion.

## Bad vs Good Implementations
### eBPF Socket Map Steering vs Naive Signal-Based Listener Termination (Go Orchestration Engine)

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Default kernel SO_REUSEPORT randomly distributes new SYN packets across all matching listening sockets. Sending SIGTERM leaves the retiring socket in the kernel table, meaning new connections continue to arrive until the FD closes. When closed, pending unaccepted connections in the socket's backlog receive connection resets (TCP RST), causing immediate 5xx outages during deployments.
```go
package deployer

import (
	"context"
	"os"
	"syscall"
	"time"
)

// BAD: Naive rollout terminates old process directly relying on vanilla SO_REUSEPORT.
// Incoming SYNs routed by kernel hash to oldPid during termination will be RST'd.
func RollingUpdateNaive(ctx context.Context, oldPid int, newPid int) error {
	// Wait arbitrary delay for new service initialization
	time.Sleep(2 * time.Second)

	// Send SIGTERM directly; kernel SO_REUSEPORT continues hashing connections to oldPid
	// until oldPid closes its FD, discarding connections currently in SYN queue.
	if err := syscall.Kill(oldPid, syscall.SIGTERM); err != nil {
		return err
	}

	// Wait fixed duration and force kill
	time.Sleep(10 * time.Second)
	_ = syscall.Kill(oldPid, syscall.SIGKILL)
	return nil
}
```

#### Production Standard (Correct)
> **Standard**: Atomically updates the eBPF reuseport sockarray before terminating the old worker. The kernel eBPF program instantaneously redirects all new SYN handshakes to the new process socket, while the old process receives a custom drain signal allowing it to accept remaining backlog connections and complete active transactions without dropping connections.
```go
package deployer

import (
	"context"
	"fmt"
	"syscall"
	"time"

	"github.com/cilium/ebpf"
)

// GOOD: Uses eBPF reuseport sockarray to atomically steer SYNs to new generation
// and drains pending backlogs before signaling the retiring worker.
func RollingUpdateEBPF(
	ctx context.Context,
	reuseMap *ebpf.Map,
	oldWorkerSlot uint32,
	newWorkerSlot uint32,
	oldPid int,
) error {
	// 1. Validate that new generation worker is registered and healthy in the eBPF map
	var newFd uint64
	if err := reuseMap.Lookup(newWorkerSlot, &newFd); err != nil || newFd == 0 {
		return fmt.Errorf("target worker slot %d not populated in eBPF sockmap: %w", newWorkerSlot, err)
	}

	// 2. Atomically delete old listener from eBPF reuseport map to stop SYN routing immediately
	if err := reuseMap.Delete(oldWorkerSlot); err != nil {
		return fmt.Errorf("failed to unbind old worker from eBPF reuseport map: %w", err)
	}

	// 3. Signal old worker to stop accepting and flush backlog via custom drain signal (SIGUSR1)
	if err := syscall.Kill(oldPid, syscall.SIGUSR1); err != nil {
		return fmt.Errorf("failed to send drain signal to PID %d: %w", oldPid, err)
	}

	// 4. Poll until legacy process completes draining of in-flight sessions and exits gracefully
	deadline := time.Now().Add(30 * time.Second)
	for time.Now().Before(deadline) {
		if err := syscall.Kill(oldPid, 0); err != nil {
			return nil // Process has exited cleanly with 0 dropped packets
		}
		select {
		case <-ctx.Done():
			return ctx.Err()
		case <-time.After(200 * time.Millisecond):
		}
	}

	// Force kill only as fallback after validated backlog flush window
	return syscall.Kill(oldPid, syscall.SIGKILL)
}
```

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 SO_REUSEPORT Socket Map Connection Draining and Zero-Loss Handoff Standard

eBPF SO_REUSEPORT Socket Map Connection Draining and Zero-Loss Handoff Standard defines an industrial-grade behavioral standard for devops engineering. Enforces deterministic, zero-packet-loss rolling process deployments by orchestrating eBPF BPF_PROG_TYPE_SK_REUSEPORT programs and BPF_MAP_TYPE_REUSEPORT_SOCKARRAY maps. Mandates atomic ingress TCP socket redirection to new generation worker groups while draining established connections on legacy workers before SIGKILL/close. Eliminates kernel-level SYN backlog resets and RST injection caused by naive process termination or standard SO_REUSEPORT round-robin distribution during shutdown. 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: Terminating SO_REUSEPORT Listeners Without eBPF Socket Map Steering and Synchronized Backlog Evacuation 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 DriftTerminating SO_REUSEPORT Listeners Without eBPF Socket Map Steering and Synchronized Backlog EvacuationCritical
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 attach a BPF_PROG_TYPE_SK_REUSEPORT eBPF program to the primary listening socket group prior to binding multiple SO_REUSEPORT instances across generation boundaries.

Engineers MUST ALWAYS attach a BPF_PROG_TYPE_SK_REUSEPORT eBPF program to the primary listening socket group prior to binding multiple SO_REUSEPORT instances across generation boundaries.

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 update the underlying BPF_MAP_TYPE_REUSEPORT_SOCKARRAY or BPF_MAP_TYPE_SOCKMAP atomically, routing new incoming SYN packets exclusively to newly provisioned worker processes before signaling the retiring worker process.

Engineers MUST update the underlying BPF_MAP_TYPE_REUSEPORT_SOCKARRAY or BPF_MAP_TYPE_SOCKMAP atomically, routing new incoming SYN packets exclusively to newly provisioned worker processes before signaling the retiring worker process.

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 default kernel SO_REUSEPORT round-robin hashing (which routes SYN packets across all active sockets regardless of shutdown state, causing ECONNRESET/connection aborts if a process exits with unaccepted SYN backlog entries).

Engineers MUST NOT rely on default kernel SO_REUSEPORT round-robin hashing (which routes SYN packets across all active sockets regardless of shutdown state, causing ECONNRESET/connection aborts if a process exits with unaccepted SYN backlog entries).

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

Retiring worker services MUST enter a deterministic connection drain phase

Retiring worker services MUST enter a deterministic connection drain phase: stop accepting new handshakes from the eBPF map, fully consume all established entries in the existing listen backlog via accept4(2), wait for active in-flight L7 transactions to finish, and ONLY THEN close the listening file descriptor.

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

Orchestration scripts MUST verify via bpftool or direct sockmap inspection that the old process socket file descriptor has been deleted from the reuseport sockarray before issuing SIGTERM to the old worker daemon.

Orchestration scripts MUST verify via bpftool or direct sockmap inspection that the old process socket file descriptor has been deleted from the reuseport sockarray before issuing SIGTERM to the old worker daemon.

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

Rollback procedures MUST support atomic swap-back in the BPF map targeting healthy legacy worker sockets if new generation workers fail health checks prior to traffic cutover completion.

Rollback procedures MUST support atomic swap-back in the BPF map targeting healthy legacy worker sockets if new generation workers fail health checks prior to traffic cutover completion.

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 SO_REUSEPORT Socket Map Connection Draining and Zero-Loss Handoff Standard critical for AI coding assistants?

Enforces deterministic, zero-packet-loss rolling process deployments by orchestrating eBPF BPF_PROG_TYPE_SK_REUSEPORT programs and BPF_MAP_TYPE_REUSEPORT_SOCKARRAY maps. Mandates atomic ingress TCP socket redirection to new generation worker groups while draining established connections on legacy workers before SIGKILL/close. Eliminates kernel-level SYN backlog resets and RST injection caused by naive process termination or standard SO_REUSEPORT round-robin distribution during shutdown. 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 (Terminating SO_REUSEPORT Listeners Without eBPF Socket Map Steering and Synchronized Backlog Evacuation) 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