PART 2: ADVANCED CONCEPTS
6. CNI Deep Dive
Flannel (Simple Overlay)
| Aspect | Details |
| Approach | VXLAN overlay |
| Policy | ❌ None |
| Performance | Good, but encapsulation overhead |
| Use Case | K3s default, simple clusters |
Flannel's design philosophy is "do one thing well." A user-space daemon manages subnet allocation, while the kernel's VXLAN and bridge code handles forwarding. No policy, no observability — just connectivity.
Calico (Policy Powerhouse)
| Aspect | Details |
| Approach | BGP routing, iptables/eBPF |
| Policy | ✅ Excellent NetworkPolicy |
| Performance | Excellent (no encapsulation by default) |
| Use Case | Production, policy-heavy |
Calico supports multiple data planes — iptables, nftables, eBPF, Windows HNS, and VPP — allowing operators to choose the best fit. The control plane includes Felix (per-node agent) and BIRD (BGP daemon).
Cilium (eBPF Native)
| Aspect | Details |
| Approach | eBPF (kernel-native) |
| Policy | ✅ L3/L4/L7 |
| Performance | Best (O(1) lookups) |
| Use Case | Modern, high-performance |
Cilium was purpose-built around eBPF. Every packet passes through eBPF programs attached to network interfaces. The architecture consists of:
- Cilium Agent — DaemonSet per node, translates policies into eBPF programs
- Cilium Operator — Cluster-wide IPAM, garbage collection
- Hubble — Built-in observability from eBPF data paths
Cilium's policy model is identity-based rather than IP-based. Pods are assigned cryptographic identities derived from Kubernetes labels, service accounts, and namespaces. Policies survive pod rescheduling and IP changes.
AWS VPC CNI
| Aspect | Details |
| Approach | Native VPC IPs |
| Policy | ✅ (via Calico) |
| Performance | Excellent (native VPC) |
| Use Case | AWS EKS |
The Amazon VPC CNI assigns pods real VPC IP addresses, enabling native VPC networking. Security groups, NACLs, and flow logs all work natively.
Two components:
- CNI binary — invoked by kubelet on pod add/remove
- ipamd (aws-node DaemonSet) — manages ENIs and maintains a warm pool of IPs
Modes:
| Mode | IP Usage | Pod Density |
| Secondary IP (default) | 1 IP per pod | Limited by ENI × IPs |
| Prefix Delegation | /28 prefix per ENI slot | ~4-16× more pods |
| Custom Networking | Different subnet for pods | Separate CIDR |
Prefix Delegation assigns /28 prefixes (16 IPs each) to ENI slots, dramatically increasing pod density. With prefix mode, an m5.large can support 110 pods vs 29 in secondary IP mode.
CNI Comparison Table
| CNI | Approach | Policy | Performance | Best For |
| Flannel | VXLAN overlay | ❌ | Good | Simple clusters |
| Calico | BGP, iptables/eBPF | ✅ Full | Excellent | Policy-heavy |
| Cilium | eBPF | ✅ L3/L4/L7 | Best | Modern, high-performance |
| AWS VPC CNI | Native VPC | ✅ (via Calico) | Excellent | EKS |
| Azure CNI | Native VNET | ✅ | Excellent | AKS |
| GKE Dataplane V2 | Cilium-based | ✅ | Best | GKE |
7. Cilium and eBPF
Why eBPF Changes Everything
Traditional networking (iptables) uses linear rule chains. eBPF uses hash tables with O(1) lookups. The time to resolve a service is constant regardless of whether you have 10 or 10,000 services.
Cilium Architecture
text
┌─────────────────────────────────────────────────────────────┐
│ CILIUM ARCHITECTURE │
│ │
│ ┌─────────────────────────────────────────────────────┐ │
│ │ Cilium Agent (DaemonSet) │ │
│ │ • Watches K8s API for Pods, Services, Policies │ │
│ │ • Compiles policies into eBPF programs │ │
│ │ • Loads programs into kernel │ │
│ └──────────────────────┬──────────────────────────────┘ │
│ │ │
│ ▼ │
│ ┌─────────────────────────────────────────────────────┐ │
│ │ eBPF Programs (attached to veth interfaces) │ │
│ │ • Process packets at TC/XDP hooks │ │
│ │ • O(1) map lookups │ │
│ │ • Identity-based policies │ │
│ └─────────────────────────────────────────────────────┘ │
│ │
│ ┌─────────────────────────────────────────────────────┐ │
│ │ Hubble (Observability) │ │
│ │ • Real-time flow visibility │ │
│ │ • DNS query logging │ │
│ │ • L7 protocol inspection │ │
│ └─────────────────────────────────────────────────────┘ │
└─────────────────────────────────────────────────────────────┘
Cilium vs Calico Performance
Benchmarks show Cilium delivers approximately 25% higher throughput in service routing scenarios.
| Metric | Cilium (eBPF) | Calico (iptables) |
| Service routing | O(1) | O(n) |
| Throughput | 25% higher | Baseline |
| CPU at scale | Stable | Increases |
| Latency | Lower | Higher |
Cilium Features
| Feature | Description |
| kube-proxy replacement | eBPF service load balancing |
| L7 policies | HTTP, gRPC, Kafka |
| Hubble | Flow-level observability |
| Cluster Mesh | Multi-cluster networking |
| Service Mesh | Sidecarless mesh |
| Runtime security | Tetragon |
Kernel Requirements
Cilium requires Linux kernel 4.19.57 or newer for full eBPF functionality. Modern managed Kubernetes (GKE, AKS, EKS) all meet this requirement.
8. kube-proxy Replacement with eBPF
Why Replace kube-proxy
Traditional kube-proxy modes have scaling issues:
- iptables: Every packet traverses a chain that grows with service count
- IPVS: Improves with hash tables but still requires netfilter hooks and conntrack overhead
How eBPF Replacement Works
eBPF-based implementations attach directly to network interfaces and cgroups, processing service traffic before the normal kube-proxy datapath. Service lookups use eBPF maps with O(1) complexity. Connection tracking happens in eBPF maps rather than iptables state.
Installing Cilium with kube-proxy Replacement
bash
# Initialize without kube-proxy
kubeadm init --skip-phases=addon/kube-proxy \
--pod-network-cidr=10.244.0.0/16
# Install Cilium
helm repo add cilium https://helm.cilium.io/
helm install cilium cilium/cilium \
--namespace kube-system \
--set kubeProxyReplacement=true \
--set k8sServiceHost=API_SERVER_IP \
--set k8sServicePort=API_SERVER_PORT \
--set bpf.masquerade=true \
--set ipam.mode=kubernetes
Verifying the Replacement
bash
# Check Cilium status
kubectl -n kube-system exec ds/cilium -- cilium-dbg status | grep KubeProxyReplacement
# Should show: KubeProxyReplacement: True
# Verify no kube-proxy pods
kubectl get pods -n kube-system -l k8s-app=kube-proxy
# Should return no resources
Benefits of eBPF Replacement
| Benefit | Description |
| O(1) service lookup | Constant regardless of service count |
| No conntrack race | Eliminates UDP DNS timeout |
| DSR support | Direct Server Return |
| Maglev hashing | Better load distribution |
| Session affinity without conntrack | Simpler, faster |
| Faster failover | Endpoint changes propagate faster |
9. NetworkPolicy
NetworkPolicy is the Kubernetes firewall for Pods.
Default Behavior
By default, all Pods can talk to all Pods. This is a security risk.
The Default Deny Pattern
The core best practice is to default-deny all traffic and then explicitly allow only what each workload needs. Apply default-deny for both ingress and egress in each namespace.
Default Deny All
yaml
apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
name: default-deny
namespace: production
spec:
podSelector: {}
policyTypes:
- Ingress
- Egress
Empty podSelector: {} = all Pods in the namespace.
Allow Specific Ingress
yaml
apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
name: allow-frontend-to-backend
namespace: production
spec:
podSelector:
matchLabels:
app: backend
policyTypes:
- Ingress
ingress:
- from:
- podSelector:
matchLabels:
app: frontend
ports:
- protocol: TCP
port: 8080
Allow Specific Egress
yaml
spec:
podSelector:
matchLabels:
app: backend
policyTypes:
- Egress
egress:
- to:
- namespaceSelector:
matchLabels:
name: kube-system
ports:
- protocol: UDP
port: 53
NetworkPolicy Best Practices
| Practice | Why |
| Start with default deny per namespace | Foundation of zero-trust |
| Label everything consistently | Policies rely on selectors |
| Test in monitor mode first | Avoid breaking traffic |
| Enforce both ingress and egress | Egress prevents exfiltration |
| Review effective policy regularly | Detect drift |
| Never flip the whole cluster at once | Roll out per namespace |
NetworkPolicy Limitations
Native NetworkPolicies operate at L3/L4. They cannot:
- Filter by HTTP path or method
- Match DNS names
- Inspect gRPC methods
- See application-layer data
For L7 policies, you need Cilium NetworkPolicy.
10. Cilium NetworkPolicy (L7 Policies)
CiliumNetworkPolicy extends NetworkPolicy with L7 (application layer) rules.
L7 HTTP Policy
yaml
apiVersion: cilium.io/v2
kind: CiliumNetworkPolicy
metadata:
name: allow-http-get
spec:
endpointSelector:
matchLabels:
app: backend
ingress:
- fromEndpoints:
- matchLabels:
app: frontend
toPorts:
- ports:
- port: "8080"
protocol: TCP
rules:
http:
- method: "GET"
path: "/api/.*"
This allows only GET requests to /api/*.
gRPC Policy
Cilium treats gRPC as HTTP/2 traffic. Each gRPC method maps to an HTTP POST path such as /package.Service/Method. Cilium's HTTP L7 policy engine can match and filter gRPC calls using path regex, enabling method-level access control.
yaml
apiVersion: cilium.io/v2
kind: CiliumNetworkPolicy
metadata:
name: allow-grpc-method
spec:
endpointSelector:
matchLabels:
app: grpc-server
ingress:
- fromEndpoints:
- matchLabels:
app: grpc-client
toPorts:
- ports:
- port: "50051"
protocol: TCP
rules:
http:
- method: "POST"
path: "/helloworld.Greeter/SayHello"
When to Use L7 Policies
| Scenario | L7 Policy |
| API gateway restrictions | ✅ Yes |
| gRPC method-level access | ✅ Yes |
| Kafka topic restrictions | ✅ Yes |
| Simple L3/L4 isolation | ❌ Use native NetworkPolicy |
| High-throughput traffic | ⚠️ L7 has performance cost |
Performance note: Benchmarks show eBPF-based Cilium maintains 8.9K Mbps under complex L3/L4 policies, but drops to 94 Mbps with L7 processing. Use L7 policies selectively.
11. Ingress Controllers
An Ingress Controller implements Ingress resources — HTTP/HTTPS routing into the cluster.
Why Ingress Controllers
| Without Ingress | With Ingress |
| One LoadBalancer per app (expensive) | One external IP, many routes |
| No path-based routing | Path and host-based routing |
| No TLS termination | Centralized TLS |
Ingress Controller Comparison
| Controller | Performance | Auto TLS | gRPC | TCP/UDP |
| NGINX Ingress | ~20K RPS | cert-manager | ✅ | ✅ |
| Traefik | ~19K RPS | Built-in | ✅ | ✅ |
| HAProxy Ingress | ~100K+ RPS | cert-manager | ✅ | ✅ |
| Envoy | ~18.5K RPS | cert-manager | ✅ | ✅ |
HAProxy Ingress is the performance leader, documented at over 100K requests/second per replica with tuning.
NGINX Ingress (Most Popular)
yaml
apiVersion: networking.k8s.io/v1
kind: Ingress
metadata:
name: web-ingress
annotations:
nginx.ingress.kubernetes.io/rewrite-target: /
spec:
ingressClassName: nginx
tls:
- hosts:
- app.example.com
secretName: tls-secret
rules:
- host: app.example.com
http:
paths:
- path: /
pathType: Prefix
backend:
service:
name: web
port:
number: 80
Traefik (Built-in TLS)
Traefik has built-in Let's Encrypt support, eliminating the need for cert-manager.
yaml
apiVersion: traefik.containo.us/v1alpha1
kind: IngressRoute
metadata:
name: web
spec:
entryPoints:
- websecure
routes:
- match: Host(`app.example.com`)
kind: Rule
services:
- name: web
port: 80
tls:
certResolver: letsencrypt
HAProxy Ingress (Performance Leader)
HAProxy is the performance leader for TCP/UDP load balancing scenarios.
Ingress Class
yaml
spec:
ingressClassName: nginx
If multiple Ingress controllers exist, ingressClassName selects which one handles the Ingress.
Common Ingress Annotations
| Annotation | Purpose |
nginx.ingress.kubernetes.io/rewrite-target | Rewrite path |
nginx.ingress.kubernetes.io/ssl-redirect | Force HTTPS |
nginx.ingress.kubernetes.io/proxy-body-size | Max upload |
nginx.ingress.kubernetes.io/rate-limit | Rate limiting |
cert-manager.io/cluster-issuer | Auto TLS |
12. Gateway API
The Gateway API is the official successor to Ingress.
Why Gateway API
Ingress limitations:
- Annotation overload — Advanced features require controller-specific annotations that are not portable.
- No role separation — The same resource defines infrastructure and application routing.
- Limited protocol support — Only HTTP/HTTPS. No TCP, UDP, or gRPC-native routing.
- No header-based routing — Cannot route based on headers without annotations.
- No traffic splitting — Canary deployments require non-standard annotations.
Gateway API Resources
| Resource | Owner | Purpose |
| GatewayClass | Infrastructure | Defines the controller |
| Gateway | Infrastructure | Listener configuration |
| HTTPRoute | Application | HTTP routing rules |
| GRPCRoute | Application | gRPC routing |
| TLSRoute | Application | TLS passthrough |
| ReferenceGrant | Application | Cross-namespace refs |
Gateway API Example
Infrastructure team creates the Gateway:
yaml
apiVersion: gateway.networking.k8s.io/v1
kind: Gateway
metadata:
name: main-gateway
namespace: gateway-system
spec:
gatewayClassName: istio
listeners:
- name: http
protocol: HTTP
port: 80
allowedRoutes:
namespaces:
from: All
- name: https
protocol: HTTPS
port: 443
tls:
mode: Terminate
certificateRefs:
- name: wildcard-tls
Application team creates routes:
yaml
apiVersion: gateway.networking.k8s.io/v1
kind: HTTPRoute
metadata:
name: app-routes
namespace: default
spec:
parentRefs:
- name: main-gateway
namespace: gateway-system
rules:
- matches:
- path:
type: PathPrefix
value: /api
backendRefs:
- name: api-service
port: 80
Gateway API Status (2026)
As of 2026, core Gateway API resources — GatewayClass, Gateway, HTTPRoute, GRPCRoute, TLSRoute, and ReferenceGrant — have reached GA (General Availability) and are production-ready. Some route types (TCPRoute, UDPRoute) are still experimental.
13. Ingress vs Gateway API
The Retirement of Ingress NGINX
Ingress NGINX maintenance ends in March 2026. This gives infrastructure teams a deadline and an opportunity to re-evaluate their ingress strategy.
Comparison Table
| Aspect | Ingress | Gateway API |
| Status | Stable (maintenance mode) | GA (recommended) |
| Role separation | ❌ No | ✅ Yes |
| Protocol support | HTTP/HTTPS | HTTP, HTTPS, gRPC, TCP, UDP |
| Header routing | Annotations only | ✅ Native |
| Traffic splitting | Annotations only | ✅ Native |
| Cross-namespace | Limited | ✅ ReferenceGrant |
| Portability | Controller-specific | ✅ Standard |
Migration Guide
Step 1: Deploy a Gateway API controller
Options: Istio, Cilium, Envoy Gateway, NGINX Gateway Fabric, Kong, Traefik.
Step 2: Create GatewayClass and Gateway
yaml
apiVersion: gateway.networking.k8s.io/v1
kind: GatewayClass
metadata:
name: my-gateway-class
spec:
controllerName: gateway.envoyproxy.io/gatewayclass-controller
---
apiVersion: gateway.networking.k8s.io/v1
kind: Gateway
metadata:
name: my-gateway
spec:
gatewayClassName: my-gateway-class
listeners:
- name: http
protocol: HTTP
port: 80
Step 3: Create HTTPRoutes (migrate from Ingress)
Step 4: Test, then remove Ingress resources
Migration Strategy
| Phase | Action |
| 1. Pilot | Deploy Gateway API for one service |
| 2. Validate | Test routing, TLS, observability |
| 3. Expand | Migrate more services |
| 4. Retire | Remove Ingress resources |
Gateway API is recommended over Ingress for new clusters as of 2026.
14. DNS in Kubernetes
The ndots:5 Problem
Every Pod gets:
text
options ndots:5
Impact: Names with fewer than 5 dots trigger search-domain expansion.
For api.stripe.com:
- Query 1:
api.stripe.com.default.svc.cluster.local - Query 2:
api.stripe.com.svc.cluster.local - Query 3:
api.stripe.com.cluster.local - Query 4:
api.stripe.com.
4 queries for 1 logical lookup.
Fixes
Option 1: Use trailing dots
bash
curl http://api.stripe.com.
The trailing dot means "absolute name" — no search domain expansion.
Option 2: Lower ndots
yaml
spec:
dnsConfig:
options:
- name: ndots
value: "2"
Now api.stripe.com (2 dots) is treated as absolute.
The 5-Second DNS Timeout
Problem: Parallel A and AAAA UDP queries from the same socket hit the conntrack race condition in the Linux kernel. One packet is dropped. The resolver waits for its 5-second timeout.
Solution: NodeLocal DNSCache.
NodeLocal DNSCache improves cluster DNS performance and resolves the DNAT conntrack contention issue by running a DaemonSet-based DNS caching proxy on cluster nodes.
How it works:
| Step | What Happens |
| 1 | Pod queries 169.254.20.10 (local link) |
| 2 | NodeLocal DNSCache receives UDP |
| 3 | Cache hit → answer locally (sub-ms) |
| 4 | Cache miss → forward over TCP to CoreDNS |
| 5 | TCP conntrack entries are short-lived |
Result: Eliminates the 5-second timeout.
CoreDNS Metrics to Monitor
| Metric | What It Shows |
coredns_dns_requests_total | Total queries |
coredns_dns_responses_total | Responses by rcode |
coredns_cache_hits_total | Cache hits |
coredns_forward_requests_total | Upstream queries |
coredns_dns_request_duration_seconds | Query latency |
15. Headless Services
A Headless Service (clusterIP: None) returns Pod IPs directly instead of a ClusterIP.
How Headless Works
| Aspect | Normal Service | Headless Service |
| ClusterIP | Virtual IP | None |
| DNS returns | ClusterIP | All Pod IPs |
| Load balancing | kube-proxy | Client-side |
| Use case | Stateless | StatefulSets |
Headless Service Example
yaml
apiVersion: v1
kind: Service
metadata:
name: db-headless
spec:
clusterIP: None
selector:
app: postgres
ports:
- port: 5432
DNS for Headless
text
db-headless.default.svc.cluster.local → 10.244.1.5, 10.244.2.8, 10.244.3.2
Each Pod also gets its own DNS:
text
postgres-0.db-headless.default.svc.cluster.local
postgres-1.db-headless.default.svc.cluster.local
postgres-2.db-headless.default.svc.cluster.local
Use Cases
| Use Case | Why Headless |
| StatefulSets | Stable identity per Pod |
| Databases | Clients connect to specific replicas |
| Message queues | Brokers need stable IDs |
| Peer discovery | Pods find each other directly |
16. Multi-Cluster Networking
Cluster Mesh (Cilium)
Cilium's Cluster Mesh connects multiple Kubernetes clusters with:
- Cross-cluster service discovery
- Global load balancing
- Unified network policy
- Cross-cluster pod-to-pod communication
Submariner
Submariner connects clusters across clouds and on-premises. It uses a gateway node in each cluster to establish tunnels.
Multi-Cluster Service Discovery
| Approach | Tool |
| Cluster Mesh | Cilium |
| Submariner | Open source |
| Service Mirroring | Admiralty |
| DNS-based | CoreDNS federation |
1:1 copy of the class Google Doc, code in code blocks.