Video in progress
Autoscaling a WebSocket service in Kubernetes with a CPU-based HPA isn't working well. Why, and what do you scale on?
Connections live long: only new connections go to a new pod, old ones stay on the old pods, and scale-down cuts connections and causes a reconnect wave. CPU also correlates poorly with the number of connections. Scale on a custom metric like open connections per pod, with slow scale-down.
📖 Answer
With an HTTP service, HPA is simple: load went up, pods were added, new requests were spread evenly. With WebSocket that chain breaks.
Scale-up becomes useless. 40,000 connections on 4 pods, CPU at 80%. HPA adds 2 more pods. But those 40,000 connections don't move from where they are: the new pods are almost empty and the old pods are still hot. The average CPU drops a bit and HPA thinks "everything is fine".
Scale-down does damage. Load drops at night and HPA removes a pod; its 10,000 clients are cut off and pour onto the rest. If this "oscillation" happens several times a day, users notice frequent disconnects.
CPU is the wrong signal. 50,000 idle connections don't eat CPU, but they eat memory and file descriptors. The pod reaches OOM before CPU gives a signal.
The configuration I use:
behavior:
scaleDown:
stabilizationWindowSeconds: 1800
policies:
- type: Pods
value: 1
periodSeconds: 600
metrics:
- type: Pods
pods:
metric:
name: ws_active_connections
target:
type: AverageValue
averageValue: "15000"
The app exports the metric through Micrometer, and Prometheus Adapter or KEDA feeds it to HPA.
Also:
least connectionson the load balancer, so new pods get new connections first and fill up gradually;- on scale-down, the pod closes its connections not instantly but over several minutes with jitter;
- in a very uneven state you can deliberately cut a small share of connections from the fullest pods to rebalance, but do that carefully and slowly.
Sign up to mark studied questions and save your progress.