AlgoViz

Container and Kubernetes load balancing

medium 30 min

Containers come and go and their addresses change.

Video lesson · Chapter 1 of 5

Find the entrance to an otherwise ordinary pod

0:00 / 3:51

Theory

Read or listen first. About 2 min.

What it is

In Kubernetes your program runs in pods. A pod is one or a few containers that share an address. Pods are replaced all the time: on a new version, when a machine fails, when traffic grows or falls. Every new pod gets a new address.

A Service is a steady name and a steady address for a group of pods. Callers use the name. Kubernetes keeps the list of pods behind it and spreads connections over those that are ready.

A Service works with connections (layer 4). For web requests, with host names and paths, there is Ingress and its newer replacement, the Gateway API. A service mesh goes further and balances each request between services.

Why it exists

A classic load balancer has a list of servers that changes a few times a year. Here the list changes many times an hour. Nobody can edit it by hand, so the list must follow the pods by itself.

Container traffic also has two directions: from outside into the cluster, and between services inside it. Most of the traffic is inside. That part needs a balancer that costs almost nothing, so Kubernetes puts it into the network rules of every machine instead of into a separate box.

A short history

  1. 6 June 2014

    The first commit of Kubernetes is published.

  2. August 2020

    Kubernetes 1.19 makes the Ingress API stable (networking.k8s.io/v1).

  3. 31 October 2023

    Gateway API 1.0: the successor of Ingress becomes generally available.

  4. April 2025

    Kubernetes 1.33: the nftables mode of kube-proxy is stable and the old Endpoints API is deprecated in favour of EndpointSlices.

  5. December 2025

    Kubernetes 1.35 deprecates the IPVS mode of kube-proxy.

  6. March 2026

    Maintenance of the Ingress NGINX project ends. The Kubernetes project recommends Gateway.

Words to know

Pod
The smallest thing Kubernetes runs: containers that share one address.
Node
A machine of the cluster that runs pods.
Service
A steady name and virtual address for a set of pods.
Selector
The labels that say which pods belong to a Service.
EndpointSlice
The list of addresses behind a Service, in pieces of at most 100 by default.
kube-proxy
A program on each node that turns Services into network rules of the kernel.
Readiness probe
The check that decides if a pod may receive traffic.
Ingress, Gateway
Rules for traffic that enters the cluster by host and path. A controller must carry them out.
Sidecar
A proxy container next to the program in the same pod.

Understand it

Start here

The hive keeps its name

Bees come and go
Meadow

Nobody asks for bee number two. They ask for the hive.

In the gardenIn Kubernetes
BeePod
Hive with its nameService
Bees that can fly todayReady endpoints
Young bee on the boardPod that is not ready
SignpostIngress or Gateway

The idea

A Service is a name, a list and some rules

  1. 1

    Name

    The cluster's DNS answers my-service.production with one virtual address, for example 10.96.0.20.

  2. 2

    List

    A controller watches pods whose labels match the selector and writes the addresses, with a ready flag, into EndpointSlices.

  3. 3

    Rules

    On every node kube-proxy reads the list and writes rules into the kernel: traffic to 10.96.0.20 port 80 goes to one of these pods.

A Service inside the cluster

Inside one cluster a caller pod sends to the Service address. Rules in the kernel of the node send the connection to pod 1, pod 2 or pod 3. Beside it the EndpointSlice list feeds kube-proxy, which writes those rules.
The dashed path carries the list. The solid path carries traffic.

From a pod to a pod

Finding services by name is a subject of its own: service discovery. Kubernetes does server-side discovery with Services and client-side discovery with headless Services.

How it chooses

At random, not in turn

It is often said that Services use round robin. In the default iptables mode the kernel picks an endpoint at random for each new connection. The rules are a list, and each rule has a chance.

Why the chances differ but the shares are equal

P1=13,P2=23⋅12=13,P3=23⋅12⋅1=13P_1 = \tfrac{1}{3}, \quad P_2 = \tfrac{2}{3} \cdot \tfrac{1}{2} = \tfrac{1}{3}, \quad P_3 = \tfrac{2}{3} \cdot \tfrac{1}{2} \cdot 1 = \tfrac{1}{3}
Three pods: rule 1 fires with chance 1/3, rule 2 with 1/2 of what is left, rule 3 takes the rest.

Modes of kube-proxy on Linux

ModeChoiceRemember
iptablesRandomDefault as of 1.37. The time to find a Service grows with their number
nftablesRandomStable since 1.33. One lookup whatever the number of Services
ipvsRound robin, least connections and moreDeprecated since 1.35
Some networks, such as Cilium, replace kube-proxy completely.

The choice is made per connection. All requests on one open connection go to the same pod. That matters below for gRPC.

Types

Four types, each on top of the last

Service types

  • ClusterIP

    The default. A virtual address inside the cluster only. Address 10.96.0.20 port 80 to the pods.

  • NodePort

    The same port on every node, 30000 to 32767 by default. Node address port 30080 to the Service.

  • LoadBalancer

    Asks the cloud for an external balancer, which sends to the node ports or straight to pods.

  • ExternalName

    Only a DNS alias (CNAME) to a name outside. No proxy, no balancing.

Ingress is not a Service type. It is a separate kind of object that uses Services. ExternalName can surprise you with HTTP and TLS, because the caller's host name differs from the real one.

The way in

Users reach a cloud load balancer. It sends to gateway pods in the cluster. The gateway pods send requests for api to the api Service with two pods and requests for web to the web Service with one pod.
One external balancer, one gateway, many Services. Cheaper than one external balancer per Service.

Which type?

External traffic

An extra hop and a lost address

An external balancer sends a connection to some node. The pod may be on another node, so the packet travels once more, and the sender's address is usually replaced on the way. The setting externalTrafficPolicy: Local keeps traffic on the node where it arrives. The address survives and the hop goes away, but the load can become unequal.

SettingExtra hopClient addressBalance
Cluster (default)PossibleUsually replacedEven over pods
LocalNoKeptEven over nodes, not over pods
Two nodes with 1 and 3 pods and Local: one pod gets 50%, the others 16.7% each.

If the external balancer can send straight to pod addresses, both problems disappear. Then you may switch off node ports with allocateLoadBalancerNodePorts: false.

Ready

Readiness decides who gets traffic

ProbeQuestionIf it fails
StartupHas it started?Wait, other probes are off, then restart
ReadinessMay it get traffic now?Taken off the list, not restarted
LivenessIs it stuck?Restarted

Removing a pod is the dangerous half. Two things start at the same time: the pod is told to stop, and its address is removed from lists on all nodes. Rules on some nodes can be late, so a pod that exits at once refuses connections that are still on their way.

A shutdown without errors

The preStop pause covers the time the nodes need. The grace period is 30 seconds by default.

Choose the grace period

tgrace≥tpreStop+tlongest request+tmargint_{\text{grace}} \ge t_{\text{preStop}} + t_{\text{longest request}} + t_{\text{margin}}
A pause of 10 s, requests of up to 25 s and 5 s of margin need 40 s. The default of 30 would cut them off.

Web traffic

Ingress, and Gateway after it

An Ingress holds rules: this host and path go to that Service. It does nothing by itself. A controller must run in the cluster and carry the rules out.

Routing example

RequestService
api.example.com/v1/...api-v1
api.example.com/v2/...api-v2
web.example.com/...web

Part of the Ingress API: host rules, path rules and TLS. Offered by controllers through annotations: URL rewriting, rate limits, cookies and more. Annotations differ between controllers, so they tie you to one.

  • Known controllers: Traefik, HAProxy Ingress, Kong, and the AWS Load Balancer Controller (once called the ALB Ingress Controller).
  • Ingress NGINX, long the most familiar one, is retired since March 2026. Do not choose it for something new.
  • The Ingress API is stable but frozen: no new features. The Kubernetes project recommends Gateway.

Gateway API

  • Roles: platform team owns the Gateway, app teams own routes.
  • Weights, header matches and gRPC routes are in the API.
  • The same file works with many controllers.

Ingress

  • One object for everybody.
  • Anything beyond host, path and TLS needs annotations.
  • Frozen.
YAML
apiVersion: gateway.networking.k8s.io/v1kind: HTTPRoutemetadata:  name: apispec:  parentRefs:    - name: public-gateway  hostnames: ["api.example.com"]  rules:    - matches:        - path: { type: PathPrefix, value: /v1 }      backendRefs:        - { name: api-stable, port: 80, weight: 90 }        - { name: api-canary, port: 80, weight: 10 }
A Gateway route that splits traffic 90 to 10 between two versions.

Every request

Service mesh

A Service balances connections. A mesh balances requests. It puts a proxy next to each program, which picks a pod for every request, retries, breaks circuits, encrypts and measures. The program itself does not change.

MeshProxyKnown for
IstioEnvoy sidecars, or ambient mode without sidecarsMany features; by default picks the less busy of two random pods
LinkerdIts own small proxy in RustSimplicity; sends to the fastest pods by a moving average
ConsulEnvoy usuallyWorks with HashiCorp tools, inside and outside Kubernetes

A mesh costs memory and some delay for each pod, and knowledge to run it. Two services that need a circuit breaker do not need a mesh: see circuit breaker. Forty services in five languages may.

Patterns

Four patterns worth knowing

  1. 1

    Even spread (default)

    New connections go to all ready pods, at random in the default mode, so the spread is even over time.

  2. 2

    Session affinity

    sessionAffinity: ClientIP sends one client address to one pod, for up to 10,800 seconds (3 hours) by default. Cookies need layer 7. See sticky sessions.

  3. 3

    Weighted routing

    90% to version 1 and 10% to version 2, with a Gateway or a mesh. Without one, only the number of pods can set the share. More in load balancing patterns.

  4. 4

    Headless Service

    clusterIP: None. DNS returns all pod addresses and the client balances itself. Databases and gRPC clients use this.

A canary by counting pods

share=nnewnnew+nstable\text{share} = \frac{n_{\text{new}}}{n_{\text{new}} + n_{\text{stable}}}
1 new pod and 9 stable pods give 10%. For 1% you would need 99 stable pods. With weights you need one of each.

A trap

gRPC and HTTP/2 stick to one pod

HTTP/2 sends many requests through one long connection. The Service chose a pod when the connection opened. So one busy caller sends everything to one pod, and new pods from the autoscaler stay idle.

How uneven a few connections are

P(a pod gets none)=(1−1n)kP(\text{a pod gets none}) = \left(1 - \tfrac{1}{n}\right)^{k}
10 connections over 5 pods: 0.8 to the power of 10 is about 11%. With 2 connections it is 64%.
RemedyHowCost
Client balancingHeadless Service and round robin in the clientClient support, DNS refresh
Mesh or layer 7 proxyBalances each requestA proxy to run
Limit connection ageServer closes connections after some minutesOnly eases it

Debugging

The Service does not answer

Follow the chain

The most frequent cause is dull: labels of the pods and selector of the Service do not match, or targetPort is not the port the program listens on.

Summary

The whole topic in one minute.

Pods change, the Service stays. Labels choose the pods, readiness decides which of them get traffic, and rules on every node spread the connections, by default at random.

Use ClusterIP inside, LoadBalancer or a Gateway for the way in, headless when the client wants to choose, and a mesh when you must balance single requests. Readiness and a careful shutdown decide whether a deployment drops requests.

  • A Service is a steady name and address over changing pods.
  • kube-proxy writes rules; the kernel balances connections, at random by default.
  • ClusterIP inside, NodePort 30000 to 32767, LoadBalancer for outside, ExternalName is only DNS. Ingress is not a type.
  • Readiness puts pods on and off the list. A pause before stopping saves requests.
  • Ingress is frozen, Ingress NGINX is retired, Gateway is the recommendation.
  • gRPC needs request balancing: headless client, proxy or mesh.

Sources