TExcelTAD
Home › Deployment & MLOps: Serving, Pipelines, Monitoring › Model Services on Kubernetes: Scaling and Resources

Model Services on Kubernetes: Scaling and Resources

The model image from the previous lesson has to run somewhere, as several copies, behind one address, with more copies when traffic grows and fewer at night. On Kubernetes that is a Deployment, a Service and an autoscaler, the same objects as for any web service (Deployments, Services, autoscaling). Models add three complications: pods are slow to start because the model must be loaded, each pod needs a lot of memory (and sometimes a GPU), and the right scaling signal is not always CPU. This lesson covers the manifests, the autoscaling formula, a capacity plan and the serving frameworks built on top of Kubernetes.

Deployment, Service and probes for a model

yaml
apiVersion: apps/v1
kind: Deployment
metadata:
  name: risk-model
  labels: {app: risk-model}
spec:
  replicas: 3
  selector:
    matchLabels: {app: risk-model}
  template:
    metadata:
      labels: {app: risk-model, model-version: "7"}
    spec:
      containers:
        - name: server
          image: registry.example.com/risk-model@sha256:4b1c...   # pin the digest
          ports: [{containerPort: 8000}]
          env:
            - {name: OMP_NUM_THREADS, value: "1"}
          resources:
            requests: {cpu: "2", memory: 3Gi}
            limits: {memory: 3500Mi}
          startupProbe:                  # model loading: up to 30 x 5 s
            httpGet: {path: /ready, port: 8000}
            periodSeconds: 5
            failureThreshold: 30
          readinessProbe:                # in the Service's endpoints only when it answers
            httpGet: {path: /ready, port: 8000}
            periodSeconds: 5
          livenessProbe:                 # restart only if the process is stuck
            httpGet: {path: /live, port: 8000}
            periodSeconds: 10
            failureThreshold: 3
---
apiVersion: v1
kind: Service
metadata:
  name: risk-model
spec:
  selector: {app: risk-model}
  ports: [{port: 80, targetPort: 8000}]
---
apiVersion: autoscaling/v2
kind: HorizontalPodAutoscaler
metadata:
  name: risk-model
spec:
  scaleTargetRef: {apiVersion: apps/v1, kind: Deployment, name: risk-model}
  minReplicas: 3
  maxReplicas: 20
  metrics:
    - type: Resource
      resource: {name: cpu, target: {type: Utilization, averageUtilization: 60}}
  behavior:
    scaleDown: {stabilizationWindowSeconds: 300}

What is specific to models:

  • Three probes with different jobs (probes). The startup probe gives the pod time to load the model (here up to 150 s) without the liveness probe killing it. The readiness probe keeps the pod out of the Service until /ready reports the model loaded and warmed up; during a rolling update, old pods keep serving until new ones are ready. The liveness probe should check only that the process responds, never a dependency such as a feature store, or a dependency outage restarts every pod at once.
  • Requests and limits (resources). The memory request must cover the model, the runtime and the worst batch, since a container over its memory limit is OOM-killed. The CPU request is what the scheduler reserves and what the CPU utilisation percentage is relative to. Many teams set no CPU limit (to avoid throttling) but always a memory limit.
  • Utilisation is relative to the request. averageUtilization: 60 means 60 % of the requested CPU, averaged over the pods.

The HPA formula

Every sync period (15 s by default) the Horizontal Pod Autoscaler computes

desired=⌈current⋅metrictarget⌉\text{desired} = \left\lceil \text{current} \cdot \frac{\text{metric}}{\text{target}} \right\rceil

where metric is the current average (CPU utilisation, or a custom metric such as requests in flight per pod or queue length) and target is its desired value. It skips the change when the ratio is within a tolerance of 1 (0.1 by default), clamps the result to [minReplicas, maxReplicas], and for scale-down uses the highest recommendation of the stabilisation window (300 s by default) so that a short dip does not remove pods. Pods that are not yet ready count as 0 % CPU when scaling up, so slow-starting pods do not cause overshoot.

python · try it yourself
import math

def hpa_desired(current, metric, target, tolerance=0.1, min_r=2, max_r=20):
    """The HPA rule: desired = ceil(current * metric / target), skipped inside the tolerance band."""
    ratio = metric / target
    if abs(ratio - 1.0) <= tolerance:
        return current
    return max(min_r, min(max_r, math.ceil(current * ratio)))

print("4 pods at 90 % CPU, target 60 %  ->", hpa_desired(4, 90, 60))
print("4 pods at 64 % CPU, target 60 %  ->", hpa_desired(4, 64, 60), "(inside the 10 % tolerance)")
print("6 pods at 25 % CPU, target 60 %  ->", hpa_desired(6, 25, 60))
print("5 pods, 14 in-flight requests per pod, target 8 ->", hpa_desired(5, 14, 8))

def simulate(target, startup_min, window_min=5, cap_rps=40.0):
    """Minute by minute: traffic, HPA decisions, pods that need startup_min minutes to load the model."""
    traffic = [120] * 30 + [120 + 30 * i for i in range(1, 11)] + [420] * 40 + [420 - 30 * i for i in range(1, 11)] + [120] * 30
    ready, starting, history = 3, [], []
    overload = pod_minutes = 0
    for minute, rps in enumerate(traffic):
        ready += sum(1 for t in starting if t == minute)       # pods that finished loading
        starting = [t for t in starting if t > minute]
        current = ready + len(starting)
        overload += rps > ready * cap_rps                      # ready pods above 100 % CPU
        pod_minutes += current
        util = 100 * rps / (current * cap_rps)                 # like the HPA: starting pods count as 0 % CPU
        history.append(hpa_desired(current, util, target))
        desired = max(history[-window_min:])                   # scale-down stabilisation window
        if desired > current:
            starting += [minute + startup_min] * (desired - current)
        elif desired < current:
            ready -= current - desired
    return overload, pod_minutes, len(traffic)

print("\ntraffic 120 -> 420 -> 120 req/s, 40 req/s per pod at 100 % CPU")
for target in (60, 80):
    for startup in (1, 4):
        over, pm, n = simulate(target, startup)
        print(f"target {target} %, model load {startup} min: {over:2d} of {n} minutes above 100 % CPU, {pm} pod-minutes")
4 pods at 90 % CPU, target 60 %  -> 6
4 pods at 64 % CPU, target 60 %  -> 4 (inside the 10 % tolerance)
6 pods at 25 % CPU, target 60 %  -> 3
5 pods, 14 in-flight requests per pod, target 8 -> 9

traffic 120 -> 420 -> 120 req/s, 40 req/s per pod at 100 % CPU
target 60 %, model load 1 min:  0 of 120 minutes above 100 % CPU, 1255 pod-minutes
target 60 %, model load 4 min:  3 of 120 minutes above 100 % CPU, 1255 pod-minutes
target 80 %, model load 1 min:  0 of 120 minutes above 100 % CPU, 924 pod-minutes
target 80 %, model load 4 min: 10 of 120 minutes above 100 % CPU, 924 pod-minutes

The formula first: 4 pods at 90 % with a 60 % target need ⌈4⋅1.5⌉=6\lceil 4 \cdot 1.5 \rceil = 6; at 64 % the ratio 1.067 is inside the tolerance and nothing changes; 6 pods at 25 % shrink to 3; a custom metric of 14 requests in flight per pod against a target of 8 gives 9 pods.

The simulation runs a two-hour day: 120 requests per second, a ramp to 420, and back. Each pod handles 40 req/s at 100 % CPU, and a new pod takes 1 or 4 minutes to load its model. With a 60 % target, the ready pods never ran above 100 % CPU when a pod loads in 1 minute, and for 3 of the 120 minutes when it needs 4 minutes; both used 1,255 pod-minutes, because the autoscaler asks for the same pods and only their arrival is later. An 80 % target is cheaper (924 pod-minutes, 26 % less), and fine with 1-minute loads, but with 4-minute loads the ready pods are overloaded for 10 minutes: during the ramp, traffic grows faster than new pods become ready.

The HPA reacts to load it already sees, so the time to ready is part of the capacity plan: the target utilisation must leave enough headroom to absorb the traffic growth during one model load. Faster loading (a smaller model, ONNX, quantization, a node-local model cache), a higher minReplicas before known peaks, or scaling on a leading signal such as requests in flight are the usual remedies.

Which metric? CPU works for CPU-bound models. For GPU models CPU stays low while the GPU is saturated, and GPU utilisation is a poor signal too (a GPU can look 100 % busy at low throughput). Better signals are requests in flight per pod, queue length or latency, exported as custom metrics (Prometheus plus an adapter) or through KEDA, an event-driven autoscaler that can also scale to zero.

Capacity planning

The autoscaler handles the day; capacity planning sizes the maximum. From the peak arrival rate λ\lambda, the CPU time per request cc (measured under load) and a target utilisation uu:

pods=⌈λ cu⋅cores per pod⌉,L=λW    (Little’s law: requests in flight)\text{pods} = \left\lceil \frac{\lambda \, c}{u \cdot \text{cores per pod}} \right\rceil, \qquad L = \lambda W \;\;\text{(Little's law: requests in flight)}

Utilisation below 1 is not waste: queueing delay grows sharply as utilisation approaches 1 (queueing, capacity planning). Memory decides how many pods fit on a node, and with models it often binds before CPU.

python · try it yourself
import math

peak_rps = 900                # forecast peak, requests per second
cpu_ms = 18                   # CPU time per request (measured, one core)
target_util = 0.6             # leave headroom for bursts and for a lost node
cores_per_pod = 2             # one worker process per core
model_gib, runtime_gib = 4.0, 0.4  # resident memory of the model (1B parameters in fp32) and of one worker without it

rps_per_core = 1000 / cpu_ms * target_util
pods = math.ceil(peak_rps / (rps_per_core * cores_per_pod))
print(f"one core at {target_util:.0%}: {rps_per_core:.1f} req/s; pods for {peak_rps} req/s: {pods}")
print(f"Little's law: in flight = rate x latency = {peak_rps} x 0.050 s = {peak_rps * 0.05:.0f} requests")

for label, copies in (("model copy per worker", cores_per_pod), ("one shared copy per pod", 1)):
    mem = copies * model_gib + cores_per_pod * runtime_gib
    node_cpu, node_mem = 15.5, 58.0           # allocatable on a 16 vCPU / 64 GiB node
    per_node = min(int(node_cpu // cores_per_pod), int(node_mem // mem))
    nodes = math.ceil(pods / per_node) + 1    # +1 so that losing a node keeps capacity
    print(f"{label:24s}: memory request {mem:.1f} GiB/pod, {per_node} pods per node, {nodes} nodes (N+1)")
one core at 60%: 33.3 req/s; pods for 900 req/s: 14
Little's law: in flight = rate x latency = 900 x 0.050 s = 45 requests
model copy per worker   : memory request 8.8 GiB/pod, 6 pods per node, 4 nodes (N+1)
one shared copy per pod : memory request 4.8 GiB/pod, 7 pods per node, 3 nodes (N+1)

At 18 ms of CPU per request and 60 % target utilisation, a core serves 33.3 req/s, so 900 req/s need 14 pods of 2 cores, with 45 requests in flight at a 50 ms latency. Memory is where model services differ: with a 4 GiB model loaded separately by each of the two worker processes, a pod needs 8.8 GiB and only 6 fit on a 64 GiB node, so 4 nodes are needed including one spare. Sharing one copy per pod (threads instead of processes, or a runtime that memory-maps the weights) brings the pod to 4.8 GiB; then CPU binds at 7 pods per node and 3 nodes suffice.

GPUs on Kubernetes

GPUs are an extended resource: a device plugin (NVIDIA's, usually installed by the GPU operator) advertises nvidia.com/gpu on each GPU node, and a pod asks for whole GPUs with resources.limits: {nvidia.com/gpu: 1}. By default a GPU is never shared between pods. Sharing exists in several forms: time-slicing (several pods take turns, no memory isolation), MIG on data-centre GPUs (a GPU split into isolated slices with their own memory) and MPS. GPU nodes are expensive, so they usually carry a taint that keeps ordinary pods away, and GPU pods carry the matching toleration plus a node selector or affinity for the GPU type (scheduling). Model loading on GPUs is slower still (download, then copy to GPU memory), which makes startup probes and warm spare capacity more important. See GPU inference for batching and memory on the GPU itself.

Serving frameworks on Kubernetes

Writing the Deployment, Service and HPA by hand is fine for one model. Platforms that serve many models add their own layers; a short map (check the current documentation, these projects move quickly):

  • KServe (started in Kubeflow as KFServing, a CNCF incubating project since 2025): an InferenceService custom resource that names a model location and a framework; KServe creates the Deployment with a matching model server, optional Knative-based scale-to-zero, canary traffic splits between revisions, and transformers for pre- and post-processing. It implements the Open Inference Protocol (the "v2" REST/gRPC API).
  • Seldon Core: deploys models and inference graphs (chains, ensembles, routers) on Kubernetes, with MLServer as its Python model server and the same v2 protocol; experiments and explainers are built in. Since January 2024 new releases of Seldon Core are under the Business Source License 1.1 (free for non-production use, a commercial licence in production; each version reverts to Apache 2.0 after four years), while MLServer stays open source.
  • BentoML: a Python framework to define a service around a model and package it, with its dependencies, into a "Bento" that builds into an image; deploys to any container platform or to the vendor's cloud.
  • Ray Serve: Python-first serving on a Ray cluster (on Kubernetes via KubeRay), strong at composing several models and business logic in one application, with autoscaling on requests in flight per replica and fractional GPU allocation.
  • NVIDIA Triton Inference Server (since 2025 branded Dynamo-Triton, part of NVIDIA's Dynamo platform): a high-performance model server for TensorRT, ONNX, PyTorch, TensorFlow and Python models from a model repository, with dynamic batching and several models or copies per GPU; often the model server inside KServe or Seldon.

They differ in who owns what, but the mechanics underneath are those of this lesson: images, probes, resources, autoscaling on a well-chosen metric.

Pitfalls

  • No startup or readiness probe: traffic reaches pods before the model is loaded and fails, or liveness probes kill pods that are still loading, in a crash loop.
  • Memory request below the real peak: pods are OOM-killed under the largest batch. Measure resident memory with real inputs.
  • Scaling GPU services on CPU utilisation: the HPA never scales.
  • minReplicas 1: one node failure or one slow model load is an outage. Keep at least 2 to 3 and a PodDisruptionBudget.
  • Ignoring time to ready: the autoscaler cannot add capacity faster than a pod can load its model.

Practice

  1. 8 pods run at 75 % average CPU with a 50 % target. What does the HPA ask for? And at 53 %?
Answer

⌈8⋅75/50⌉=12\lceil 8 \cdot 75/50 \rceil = 12. At 53 % the ratio is 1.06, inside the 0.1 tolerance, so it stays at 8.

  1. In the capacity example, the CPU time per request drops from 18 ms to 6 ms after quantization. How many pods are needed at 900 req/s?
Answer

One core at 60 % serves 1000/6⋅0.6=1001000/6 \cdot 0.6 = 100 req/s, a 2-core pod 200 req/s, so ⌈900/200⌉=5\lceil 900/200 \rceil = 5 pods instead of 14. Change cpu_ms in the code to check.

  1. A GPU model service scales on CPU utilisation and never adds pods, although latency doubles at peak. Suggest a better metric and how to get it to the HPA.
Answer

Requests in flight (or queue length) per pod, exported by the server as a Prometheus metric and exposed to the HPA through a metrics adapter as a Pods metric, or through KEDA. Its target comes from load tests: the in-flight count at which latency is still within the SLO.

Test yourself

5 pods report 14 requests in flight per pod and the HPA target is 8. How many replicas does it request?

  1. 9
  2. 8
  3. 14
  4. 5

Why does a model service need a startup probe in addition to a liveness probe?

  1. Loading the model can take longer than the liveness probe allows, so the pod would be killed while loading
  2. Startup probes make the image smaller
  3. Liveness probes cannot use HTTP
  4. Startup probes replace resource requests

A pod runs two worker processes that each load a 4 GiB model. What does sharing one copy per pod change in the capacity example?

  1. Memory per pod falls from 8.8 to 4.8 GiB and CPU becomes the binding limit, 3 nodes instead of 4
  2. Nothing, CPU was always the limit
  3. It doubles the CPU time per request
  4. It removes the need for a memory limit

How does a pod request a GPU on Kubernetes with the NVIDIA device plugin?

  1. resources.limits with nvidia.com/gpu: 1
  2. An environment variable CUDA=1
  3. A label gpu=true on the pod
  4. A memory request above 16Gi