ByteGuideHub
Networking & Security • • 10 min read

Self-Hosted eBPF for Kubernetes Ingress Optimization: Dynamic Load Balancing and DDoS Mitigation

A practical guide to leveraging eBPF (via Cilium or custom programs) for Kubernetes ingress optimization, including dynamic load balancing, DDoS mitigation, and kernel-level tuning with deployment examples.

Sponsored / Ad Space

Self-Hosted eBPF for Kubernetes Ingress Optimization: Dynamic Load Balancing and DDoS Mitigation

Quick Summary (TL;DR)

  • What: Use eBPF (via Cilium) to replace or augment traditional Kubernetes ingress, moving load balancing and packet filtering into the Linux kernel.
  • Why: Lower latency (bypass kube-proxy/iptables), consistent hashing via Maglev, and line-rate DDoS mitigation with XDP.
  • How: Install Cilium with kubeProxyReplacement and ingressController enabled, tune Maglev/health-checking, then layer rate limiting and SYN-flood protection.
  • Watch out: Requires kernel ≥ 5.4 (recommended), careful MTU/BPF map sizing, and Hubble for observability.
  • Bottom line: Expect significant p99 latency and CPU savings at scale—if you’re willing to accept kernel-level debugging complexity.

Kubernetes ingress has a dirty secret: for all the elegance of a Service object, the datapath underneath is often a chain of iptables rules that grows linearly with your cluster. At a few hundred services, that’s fine. At a few thousand endpoints, you start paying for it in latency, CPU, and connection-tracking overhead. eBPF lets you move that work directly into the kernel with programmable, O(1)-lookup data structures—and it gives you a packet-filtering substrate that doubles as a DDoS shield.

This guide walks through a production-oriented deployment of self-hosted eBPF for ingress optimization using Cilium, with dynamic load balancing and kernel-level DDoS mitigation. Every step includes concrete configuration you can adapt.


Introduction to eBPF for Kubernetes Ingress

eBPF (extended Berkeley Packet Filter) is a Linux kernel technology that lets you run sandboxed programs at key hook points—XDP (driver level), TC (traffic control), and socket layers—without modifying kernel source or loading kernel modules. For Kubernetes ingress, the most valuable hooks are:

  • XDP for the earliest possible packet drop (before skb allocation).
  • TC/socket-level programs for L4 load balancing and connection tracking.
  • eBPF maps (hash, LRU, ring buffer) as the shared state store for backends, rates, and reputation lists.

Cilium is the most mature way to consume these primitives for Kubernetes. It ships an eBPF-based load balancer, an ingress controller, and a network policy engine—all operating in the kernel datapath.

Why eBPF for Ingress Optimization?

Traditional ingress (NGINX/HAProxy + kube-proxy) works well but has structural costs:

Concerniptables/kube-proxyeBPF (Cilium)
Rule lookupLinear chain traversalHash map, O(1)
Service scaleDegrades past ~5k servicesStable to tens of thousands
Latency (p99)Higher, variableLower, more predictable
DDoS filteringUserspace, after socketXDP, at driver
ObservabilityLogs/metricsPer-flow (Hubble)

The win is largest in high-connection-churn environments (API gateways, gRPC mesh) and in edge clusters where you want line-rate filtering before traffic reaches userspace.


Prerequisites and Environment Setup

Before touching Cilium, verify your nodes:

# Kernel version (5.4+ recommended)
uname -r

# BPF filesystem mounted
mount | grep /sys/fs/bpf

# Required kernel configs
grep -E 'CONFIG_BPF_SYSCALL|CONFIG_BPF_JIT|CONFIG_NET_CLS_BPF|CONFIG_NET_ACT_BPF' /boot/config-$(uname -r)

# bpftool availability
bpftool version

You’ll also need:

  • A CNI-free or Cilium-managed cluster (or the ability to migrate).
  • kubectl and helm v3.
  • Nodes with at least 2 vCPUs and BPF map memory headroom (they count against RLIMIT_MEMLOCK on older kernels; modern kernels use memcg).

Deploying Cilium as Your eBPF-Powered Ingress Controller

Step 1: Install Cilium with Ingress Support

Use Helm with kube-proxy replacement and the ingress controller enabled:

helm repo add cilium https://helm.cilium.io/
helm repo update

helm install cilium cilium/cilium --version 1.16.x \
  --namespace kube-system \
  --set kubeProxyReplacement=true \
  --set k8sServiceHost=<API_SERVER_IP> \
  --set k8sServicePort=6443 \
  --set ingressController.enabled=true \
  --set ingressController.loadbalancerMode=shared \
  --set l7Proxy=true \
  --set bpf.masquerade=true \
  --set routingMode=tunnel

Tip: If you’re migrating from kube-proxy, drain it first (kubectl -n kube-system delete ds kube-proxy) and confirm kubeProxyReplacement=true reports healthy via cilium status.

Step 2: Configure Cilium Ingress Controller

Create a CiliumIngressClass and a sample Ingress:

apiVersion: networking.k8s.io/v1
kind: Ingress
metadata:
  name: demo-ingress
spec:
  ingressClassName: cilium
  tls:
  - hosts: [demo.example.com]
    secretName: demo-tls
  rules:
  - host: demo.example.com
    http:
      paths:
      - path: /
        pathType: Prefix
        backend:
          service:
            name: demo-app
            port:
              number: 80

Cilium Ingress supports header-based routing, traffic splitting (via CiliumEnvoyConfig), and TLS termination—enough for most production HTTP workloads.

Step 3: Enable Advanced Load Balancing Features

Turn on Maglev and health checking:

helm upgrade cilium cilium/cilium --reuse-values \
  --set loadBalancer.algorithm=maglev \
  --set maglev.tableSize=65521 \
  --set loadBalancer.mode=dsr \
  --set loadBalancer.dsrDispatch=opt \
  --set enableHealthCheckNodePort=true

maglev.tableSize should be a prime number; 65521 is a common choice balancing memory and distribution quality.


Implementing Dynamic Load Balancing with eBPF

flowchart LR
    C[Client] -->|SYN| XDP[XDP / TC hook]
    XDP --> LB{eBPF LB map}
    LB -->|Maglev hash| B1[Backend Pod A]
    LB -->|Maglev hash| B2[Backend Pod B]
    LB -->|Maglev hash| B3[Backend Pod C]
    B1 -.health fail.-> HC[Health Checker]
    HC -->|remove from map| LB

Maglev Consistent Hashing

Maglev assigns each backend a fixed set of slots in a lookup table. When a backend is added or removed, only a small fraction of flows remap—critical for cache-friendly services. Cilium’s eBPF program performs the hash and slot lookup entirely in the kernel.

Session Affinity and Client IP Preservation

For stateful backends, enable client IP preservation so pods see the real source:

apiVersion: v1
kind: Service
metadata:
  name: demo-app
  annotations:
    service.cilium.io/affinity: "local"
spec:
  externalTrafficPolicy: Local   # preserves client IP
  sessionAffinity: ClientIP
  sessionAffinityConfig:
    clientIP:
      timeoutSeconds: 10800

Health Checking and Failover

Cilium performs active health checks and removes failing endpoints from the Maglev table within one check interval. Tune this:

--set healthChecking.enabled=true \
--set healthChecking.interval=5s

DDoS Mitigation at the Kernel Level

Rate Limiting with eBPF

Cilium’s CiliumNetworkPolicy supports per-endpoint rate limiting:

apiVersion: cilium.io/v2
kind: CiliumNetworkPolicy
metadata:
  name: edge-rate-limit
spec:
  endpointSelector:
    matchLabels:
      app: demo-app
  ingress:
  - fromEntities:
    - world
    toPorts:
    - ports:
      - port: "80"
        protocol: TCP
      rules:
        http:
        - rateLimit:
            requestsPerSecond: 200

SYN Flood Protection

Enable kernel SYN cookies and tune the backlog:

sysctl -w net.ipv4.tcp_syncookies=1
sysctl -w net.ipv4.tcp_max_syn_backlog=8192
sysctl -w net.ipv4.tcp_synack_retries=2

Cilium’s XDP path can drop malformed SYNs before they hit the socket layer—pair this with a custom XDP program (below) for edge clusters.

IP Reputation and Blocklisting

Maintain a dynamic blocklist via CiliumNetworkPolicy (deny rules) or a CiliumClusterwideNetworkPolicy fed by an external threat feed:

apiVersion: cilium.io/v2
kind: CiliumClusterwideNetworkPolicy
metadata:
  name: block-known-bad
spec:
  endpointSelector: {}
  ingress:
  - fromCIDRSet:
    - cidr: 203.0.113.0/24
      except:
      - 203.0.113.10/32   # allowlisted

Custom eBPF Programs for Advanced Use Cases

Writing a Simple XDP Program for DDoS Filtering

A minimal XDP program that drops packets exceeding a per-IP rate (simplified):

#include <linux/bpf.h>
#include <bpf/bpf_helpers.h>

struct {
    __uint(type, BPF_MAP_TYPE_LRU_HASH);
    __uint(max_entries, 65536);
    __type(key, __u32);   // source IP
    __type(value, __u64); // last-seen timestamp (ns)
} seen SEC(".maps");

SEC("xdp")
int xdp_ratelimit(struct xdp_md *ctx) {
    void *data = (void *)(long)ctx->data;
    void *data_end = (void *)(long)ctx->data_end;
    struct ethhdr *eth = data;
    if ((void *)(eth + 1) > data_end) return XDP_PASS;
    if (eth->h_proto != __builtin_bswap16(0x0800)) return XDP_PASS;

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

    __u64 now = bpf_ktime_get_ns();
    __u32 src = ip->saddr;
    __u64 *last = bpf_map_lookup_elem(&seen, &src);
    if (last && (now - *last) < 1000000ULL) return XDP_DROP; // <1ms apart
    bpf_map_update_elem(&seen, &src, &now, BPF_ANY);
    return XDP_PASS;
}

char _license[] SEC("license") = "GPL";

Compile with clang -O2 -target bpf -c xdp_ratelimit.c -o xdp_ratelimit.o and load with ip link set dev eth0 xdp obj xdp_ratelimit.o sec xdp.

Attaching eBPF Programs to Cilium

Cilium supports custom programs via CiliumEnvoyConfig for L7 and via its bpf CLI for XDP/TC. For XDP at the node edge, load directly on the interface (as above); for TC, use tc filter add dev eth0 ingress bpf da obj prog.o sec classifier.


Performance Tuning and Monitoring

Kernel Parameters and eBPF Map Tuning

# Increase BPF map memory
sysctl -w net.core.bpf_jit_enable=1
sysctl -w net.core.bpf_jit_harden=1

# Connection tracking
sysctl -w net.netfilter.nf_conntrack_max=1048576
sysctl -w net.netfilter.nf_conntrack_tcp_timeout_established=600

Size Maglev and CT maps to your peak endpoint count. Under-sized maps cause silent drops—monitor cilium bpf ct list and map utilization metrics.

Observability with Hubble

cilium hubble enable --ui
cilium hubble port-forward &
hubble observe --namespace default --follow

Hubble exposes per-flow verdicts (FORWARDED, DROPPED), which is invaluable for debugging why a packet was dropped—whether by policy, rate limit, or health check.


Comparison: eBPF vs. Traditional Ingress Controllers

FeatureNGINX IngressHAProxy IngressCilium (eBPF) Ingress
DatapathUserspace proxyUserspace proxyKernel eBPF
kube-proxy neededYesYesNo (replaced)
LB algorithmRound-robin/least-connManyMaglev, RR, least-conn
DDoS at line rateLimitedLimitedXDP (yes)
ObservabilityAccess logsStatsHubble per-flow
ComplexityLowMediumMedium-High
Best forSimple HTTPAdvanced L7Scale + security

Conclusion

Self-hosted eBPF ingress isn’t a magic switch—it’s a datapath investment. You trade some operational familiarity for kernel-level performance, consistent hashing, and a genuinely powerful DDoS substrate. If your cluster runs thousands of services, experiences connection churn, or sits at the edge of a hostile internet, the payback is real. Start with Cilium’s managed features (Maglev, health checking, network policies), then graduate to custom XDP only when you have a specific filtering need.


Frequently Asked Questions

Q: What are the minimum kernel requirements for running eBPF with Cilium? Cilium requires Linux kernel 4.9 or later, but for full feature support (including advanced load balancing and DDoS mitigation), kernel 5.4 or later is recommended. Ensure your nodes have the BPF filesystem mounted at /sys/fs/bpf and that the kernel is compiled with CONFIG_BPF_SYSCALL, CONFIG_BPF_JIT, and other relevant options enabled.

Q: Can I use eBPF for ingress without replacing my existing ingress controller? Yes, you can leverage eBPF for specific functions like DDoS mitigation or load balancing while keeping your existing ingress controller. For example, deploy Cilium in direct routing mode and use its eBPF-based load balancer for services while still using NGINX Ingress for HTTP routing. For full benefits, replacing the ingress controller with Cilium Ingress is recommended.

Q: How does eBPF-based DDoS mitigation compare to cloud-based solutions? eBPF-based DDoS mitigation operates at the kernel level on your nodes, providing low-latency, high-throughput protection without external dependencies. It is highly effective for volumetric and protocol attacks but may not match the scale of cloud-based scrubbing centers for massive attacks. For comprehensive protection, combine eBPF with cloud DDoS services.

Q: Is Cilium Ingress production-ready? Yes, Cilium Ingress has been production-ready since Cilium 1.13 and is widely used in production environments. It supports standard Ingress resources, TLS termination, and advanced features like header-based routing and traffic splitting. Evaluate its feature set against your specific requirements.

Q: What are the trade-offs of using eBPF for load balancing? eBPF load balancing offers high performance and low latency by bypassing kube-proxy, but it introduces complexity in debugging and requires kernel-level knowledge. It may not support all features of traditional load balancers (e.g., advanced health checks). For most Kubernetes ingress use cases, eBPF provides a robust and efficient solution.

Q: How can I monitor eBPF performance and troubleshoot issues? Use Cilium’s Hubble for deep observability into network flows, and tools like bpftool and perf to inspect eBPF programs and maps. Monitor key metrics such as packet drops, CPU usage of eBPF programs, and map utilization. Cilium also exposes Prometheus metrics for integration with monitoring systems.

Sponsored / Ad Space