Platform Engineering · Lesson 239

Model Serving on Kubernetes: KServe, Autoscaling on Concurrency, and Cold Starts

A model server on one GPU is a demo; a serving platform is that same server behind a stable endpoint, with the model fetched from storage, a runtime chosen by the model's format, autoscaling on how many requests are in flight, safe rollouts between model versions, and metrics for every token. KServe gives Kubernetes that layer as one object, the InferenceService. This lesson follows one chat request through a KServe endpoint, from the gateway through the queue-proxy to prefill and decode, and shows what scale-to-zero costs the first caller and what happens when concurrency outruns the replicas.

Difficulty: Advanced · Know this first: Lesson 201, Lesson 231, Lesson 100

Run it as:

When it breaks, I check

One thing to remember

Where the time goes

This bar splits one chat request, in milliseconds. It is a worked example, not a measurement. Decoding the answer is most of a warm request; a cold start or a full batch adds more than the whole answer takes.

Try it: how many replicas does the endpoint need?

Set the peak request rate, the answer length, and what one replica can sustain. Little's law gives the requests in flight; the replica count follows.

one replica finishes tokens/s ÷ output tokens requests a second · needed = ceil(peak ÷ per-replica × 1.25) · in flight = peak × (0.4 s + tokens × 25 ms)

5replicas needed
237requests in flight
75%load on the replicas running

Enough replicas, with headroom

Check yourself

Three questions. No score is saved anywhere — this is just you against the material.

Basic to master

Model serving grows in four levels: first what an InferenceService is, then deploying one with the right runtime and storage, then autoscaling and rollouts, and finally running many models as a platform.

Basic — One object for a model behind an endpoint

At the basic level you know what KServe adds. An InferenceService names a model, where it is stored (storageUri, such as s3://, gs://, pvc://, or hf://), and its format. KServe picks a ServingRuntime that can serve that format (vLLM or Hugging Face for LLMs, Triton, scikit-learn, XGBoost), downloads the model with a storage initializer, and gives it a URL.

Terms: predictor, transformer, ServingRuntime, Serverless and RawDeployment modes, revision, canary.

Where it breaks: a model format no installed runtime supports; the InferenceService never becomes Ready, and its status says why.

Try it: Basic

What does a ServingRuntime do in KServe?

Now do it: Run kubectl get clusterservingruntimes on a KServe cluster and list which formats each one supports.

Intermediate — Deploy a model properly

At the intermediate level you deploy an LLM with the right resources: a GPU limit, CPU and memory requests for tokenization and the runtime, a node selector for the GPU type, the model from object storage with credentials from a service account, and readiness after warm-up.

  • Expose the OpenAI-compatible API when clients expect it.
  • Pin the model by version in storage, never "latest".
  • Set minReplicas deliberately: 0 for rare internal use, at least 1 or 2 for anything interactive.

Troubleshooting: kubectl describe inferenceservice for conditions; the storage-initializer container's logs for download failures; the runtime's logs for out-of-memory at load time.

Try it: Intermediate

An InferenceService stays not Ready, and the storage-initializer container fails with AccessDenied. What is wrong?

Now do it: Write the InferenceService in Go deeper for a model in your own bucket and check which service account it uses.

Advanced — Autoscaling, rollouts, and cold starts

At the advanced level you size and change endpoints safely.

  • Sizing: Little's law for in-flight requests; replicas from tokens per second per replica and answer length; 20 to 30 percent headroom.
  • Autoscaling: scaleMetric: concurrency with a target near the measured per-replica limit; in RawDeployment mode, KEDA or an HPA on the server's queue metric.
  • Cold starts: image pull plus weights to GPU plus warm-up. Cut them with pre-pulled images, model caches on local disk, and smaller quantized models.
  • Rollouts: canaryTrafficPercent sends a share of traffic to the new revision; compare its TTFT, errors, and quality evaluations before promoting.

Failure scenarios: a canary of a bigger model that will not fit the same GPUs; scale-up stuck because no GPU node is free; a gateway timeout shorter than the longest streamed answer.

Try it: Advanced

You roll out a new model version to 10 percent of traffic. Its TTFT is fine but its answers are worse in the evaluation set. What do you do?

Now do it: Write down the three numbers that must pass before you promote a model canary: one latency, one error, one quality.

Master — Many models as a platform

At the master level you run dozens of models for many teams.

  • Placement: GPU pools by isolation need (whole GPUs or MIG for serving, shared for dev), and model packing by measured memory.
  • Routing: model-aware load balancing that sends requests to replicas with free KV cache or the right cached prefix; the Gateway API inference extension (InferencePool) is the Kubernetes standard emerging for this.
  • Cost: tokens per second per dollar per model, warm floors only where users wait, scale to zero for the long tail, and quantized variants for cheap tiers.
  • Governance: who may deploy which model, model provenance and licences, and an AI gateway in front for quotas and routing between providers.

Trade-off: a warm replica costs a GPU-hour every hour; a cold start costs the user a minute or more. Decide per endpoint from who is waiting.

Try it: Master

Forty internal models each get a few requests a day; three customer-facing models get constant traffic. How do you set the floors?

Now do it: For your models, list requests per day and the acceptable first-response time. Mark which ones may scale to zero.

Go deeper

Sizing an LLM endpoint is arithmetic once you know three numbers per replica. This script works out the time a request is in flight, what one replica can finish, the requests in flight at peak by Little's law, and the replicas needed with headroom. Standard library only; python3 serving_capacity.py.

Replicas from tokens and Little's law

# serving_capacity.py - how many model replicas does a chat endpoint need?
import math

ttft_s = 0.4            # time to first token under load
tpot_s = 0.025          # time per output token (decode), per request
out_tokens = 300        # average output length
replica_tps = 2400      # output tokens/s one replica sustains with continuous batching
peak_rps = 30           # requests per second at peak
headroom = 0.25         # keep 25% spare for bursts and a lost replica

latency_s = ttft_s + out_tokens * tpot_s           # how long one request is in flight
per_replica_rps = replica_tps / out_tokens         # requests/s one replica can finish
in_flight = peak_rps * latency_s                   # Little's law: L = lambda x W
replicas = math.ceil(peak_rps / per_replica_rps * (1 + headroom))

print(f"one request: {ttft_s}s to first token + {out_tokens} tokens x {tpot_s * 1000:.0f} ms = {latency_s:.1f} s")
print(f"one replica: {replica_tps} tokens/s / {out_tokens} tokens = {per_replica_rps:.0f} requests/s")
print(f"in flight at peak (Little's law): {peak_rps} x {latency_s:.1f} = {in_flight:.0f} requests")
print(f"replicas for {peak_rps} req/s with {headroom:.0%} headroom: {replicas}")
print(f"concurrency per replica at peak: {in_flight / replicas:.0f} (set the autoscaling target near it)")

cold_start_s = 60 + 30 + 5          # image pull + weights to GPU + warm-up, on a fresh node
print(f"scale-from-zero cold start: about {cold_start_s} s; the first caller waits all of it")
$ python3 serving_capacity.py
one request: 0.4s to first token + 300 tokens x 25 ms = 7.9 s
one replica: 2400 tokens/s / 300 tokens = 8 requests/s
in flight at peak (Little's law): 30 x 7.9 = 237 requests
replicas for 30 req/s with 25% headroom: 5
concurrency per replica at peak: 47 (set the autoscaling target near it)
scale-from-zero cold start: about 95 s; the first caller waits all of it

Read it like this: a 7.9-second request at 30 a second means 237 requests in flight; one replica finishes 8 a second, so 30 a second with 25 percent headroom needs 5 replicas, each holding about 47 at once, which is where the concurrency target goes. Measure the 2,400 tokens a second on your own GPU, model, and batch settings before you trust the answer.

An InferenceService for a chat model (Serverless mode)

apiVersion: serving.kserve.io/v1beta1
kind: InferenceService
metadata:
  name: chat
  namespace: models
spec:
  predictor:
    minReplicas: 2
    maxReplicas: 10
    scaleMetric: concurrency
    scaleTarget: 48
    serviceAccountName: model-reader
    nodeSelector:
      nvidia.com/gpu.product: NVIDIA-H100-80GB-HBM3
    model:
      modelFormat:
        name: huggingface
      storageUri: s3://models-prod/chat-8b/v3
      resources:
        requests:
          cpu: "4"
          memory: 32Gi
        limits:
          nvidia.com/gpu: "1"
          memory: 32Gi

Field names follow KServe's v1beta1 InferenceService; the manifest was parsed as YAML, not applied. For a canary, change storageUri to the new version and add canaryTrafficPercent: 10 under predictor; KServe keeps the previous revision serving the rest. Try it on a test cluster with KServe installed (its quick-start script installs Knative and a gateway) before using these numbers in production.

Watch it work

kubectl get inferenceservice chat -n models
kubectl get pods -n models -l serving.kserve.io/inferenceservice=chat
kubectl logs -n models deploy/chat-predictor-00003-deployment -c storage-initializer
curl -s https://chat.models.example.com/openai/v1/chat/completions \
  -H 'Content-Type: application/json' \
  -d '{"model":"chat","messages":[{"role":"user","content":"Say hello"}],"max_tokens":20}'

One time it broke

This is a composite of a failure pattern that keeps repeating; the numbers are illustrative. A team moved a customer-facing assistant to a new serving platform and kept its default of scaling to zero.

Timeline

  • Mon 08:55After a quiet weekend the endpoint has zero replicas. The first users of the day wait 90 to 120 seconds; many give up and retry, which queues more requests behind the cold start.
  • Mon 09:05The autoscaler asks for 8 replicas at once. Only 3 GPU nodes are free; the rest wait for new nodes, which take 6 minutes because the zone is short of capacity.
  • Mon 09:20Latency recovers. Support has 140 tickets.

What changed after

Interactive endpoints got minReplicas: 2 and a scheduled rise to the weekday floor at 08:30. Scale to zero stayed for batch and internal endpoints, with their callers told to expect a cold start. The platform's defaults were changed so that "scale to zero" is something a team turns on, not something it discovers.

If you remember nothing else

Design exercise

Design the serving platform for a company with one customer-facing chat model, a document summarizer used by staff, and 25 experimental models from the data science team.

Clarifying questions to ask

What latency does each caller accept, including the first request of the day? How many tokens per second does one replica of each model sustain on your GPUs? How often does each model change, and how will you know a new version is better? Who may deploy models?

Rough sizing

Say chat at 30 requests a second peak with 300-token answers, the summarizer at 2 a minute with 800-token answers, and experiments at a few requests a day each.

Shape of the answer

KServe with GPU node pools: chat with minReplicas 2, concurrency target from a load test, a scheduled weekday floor, and canaries gated on TTFT, errors, and an evaluation set; the summarizer with minReplicas 1 on a smaller GPU or MIG slice; experiments with scale to zero on a shared pool. Models pinned by version in object storage, service accounts per namespace, dashboards and alerts per InferenceService, and an AI gateway in front for quotas.

Trade-offs to name

Warm floors cost GPU-hours and remove cold starts where users notice. Serverless mode gives scale to zero and adds Knative to run; RawDeployment is simpler and never reaches zero. Canary gates on quality slow every rollout down and stop the ones that would have quietly made answers worse.

Saved on this device, in this browser.
Next in this series · Lesson 240
Monitoring Models in Production

A model in production is a piece of software that answers questions, and the questions keep coming after you ship it. Monitoring a model means watching those answers after they leave your hands.

Go to Lesson 240 →

Or browse the full course from the Lessons index.