Sub topic 12
Monitoring and troubleshooting a service
This chapter assumes you can deploy an InferenceService, read kubectl output, and understand the pieces covered earlier: serving runtimes, the storage initializer, deployment modes, and autoscaling. It shows where to look when a service is unhealthy or slow, and how to collect the signals that tell you before users do.
Where problems can occur
A request passes through several layers, and each layer has its own status and logs. Debug from the outside in, and stop at the first layer that looks wrong.
Start with the resource status
The InferenceService summarizes its health in status.conditions. Common conditions are PredictorReady, IngressReady, and the overall Ready. Serverless mode adds conditions that come from Knative, such as LatestDeploymentReady and RoutesReady.
kubectl get inferenceservice sklearn-iris
kubectl describe inferenceservice sklearn-iris
kubectl get inferenceservice sklearn-iris -o jsonpath='{.status.conditions}'Each failing condition has a reason and a message. The message often names the cause directly. For example, if no ServingRuntime supports the requested modelFormat, the message says that no runtime was found for the specified framework. In that case, fix the modelFormat name or create a matching runtime. Do not look at pods, because none exist yet.
Find the pods and read the right container
If the status points at the predictor, look at its pods. The names depend on the deployment mode. In Serverless mode you can also inspect the Knative objects.
kubectl get pods -l serving.kserve.io/inferenceservice=sklearn-iris
kubectl get ksvc,revision # Serverless mode only
kubectl describe pod <pod-name> # events at the bottomA predictor pod usually holds several containers. Choose the one that matches your symptom.
| Container | Present when | What its logs tell you |
|---|---|---|
| `storage-initializer` (init container) | `storageUri` is set | Download errors, bad credentials, wrong URI |
| `kserve-container` | Always | Model loading errors, prediction exceptions |
| `queue-proxy` | Serverless mode | Request queueing, concurrency, activator traffic |
| `agent` | Logger or batcher is enabled | Request logging and batching problems |
kubectl logs <pod-name> -c storage-initializer
kubectl logs <pod-name> -c kserve-container --tail=100
kubectl logs <pod-name> -c kserve-container --previous # after a crashUse --previous for a container in CrashLoopBackOff. The current container may have just started and have nothing useful in its log.
Common failures and their causes
| Symptom | Likely cause | Where to confirm |
|---|---|---|
| `READY` is `False`, no pods | No runtime matches `modelFormat` | `describe inferenceservice` message |
| Pod stuck in `Init:Error` or `Init:CrashLoopBackOff` | Wrong `storageUri`, missing permissions, missing secret or service account | `storage-initializer` logs |
| Pod `Pending` | Not enough CPU, memory, or GPU; quota exceeded; node selector or toleration mismatch | `describe pod` events |
| `OOMKilled` restarts | Memory limit below what the model needs | `describe pod`, last state |
| `ImagePullBackOff` | Wrong image name or missing pull secret | `describe pod` events |
| 404 or 503 from `curl`, pod is `Running` | Wrong `Host` header, wrong model name in the path, or the model has not finished loading | Readiness endpoint, URL in status |
| First request after idle is slow or times out | Scale from zero (cold start) | `kubectl get pods` during the call |
| Requests rejected with 4xx from the model | Payload does not match the protocol | `kserve-container` logs |
The Host header problem is the most frequent one for new users. When you call the cluster ingress by IP, the gateway routes on the service host name. Read it from the URL in the status and send it as Host.
SERVICE_HOSTNAME=$(kubectl get inferenceservice sklearn-iris \
-o jsonpath='{.status.url}' | cut -d "/" -f 3)
echo "$SERVICE_HOSTNAME"Check model readiness directly
A pod can be Running while the model is still loading or has failed to load. Ask the server. The V1 protocol exposes the model resource, and the V2 (Open Inference) protocol has health endpoints.
# V1: returns {"name": "...", "ready": true}
curl -H "Host: ${SERVICE_HOSTNAME}" \
http://${INGRESS_HOST}:${INGRESS_PORT}/v1/models/sklearn-iris
# V2: server and model readiness
curl -H "Host: ${SERVICE_HOSTNAME}" \
http://${INGRESS_HOST}:${INGRESS_PORT}/v2/health/ready
curl -H "Host: ${SERVICE_HOSTNAME}" \
http://${INGRESS_HOST}:${INGRESS_PORT}/v2/models/sklearn-iris/readyThe pod's readiness probe also depends on the model being ready. A model that never becomes ready keeps the pod out of the Service endpoints, so the revision never becomes ready.
The following script checks readiness and measures end-to-end latency from a client. It uses only the Python standard library. Set INGRESS_HOST, INGRESS_PORT, and SERVICE_HOSTNAME first.
import json
import os
import statistics
import time
import urllib.request
base = f"http://{os.environ['INGRESS_HOST']}:{os.environ['INGRESS_PORT']}"
host = os.environ["SERVICE_HOSTNAME"]
model = "sklearn-iris"
def call(path, body=None):
data = json.dumps(body).encode() if body is not None else None
req = urllib.request.Request(base + path, data=data)
req.add_header("Host", host)
req.add_header("Content-Type", "application/json")
with urllib.request.urlopen(req, timeout=30) as resp:
return json.loads(resp.read())
print("ready:", call(f"/v1/models/{model}"))
payload = {"instances": [[6.8, 2.8, 4.8, 1.4], [6.0, 3.4, 4.5, 1.6]]}
timings = []
for _ in range(20):
start = time.perf_counter()
call(f"/v1/models/{model}:predict", payload)
timings.append((time.perf_counter() - start) * 1000)
timings.sort()
print(f"median {statistics.median(timings):.1f} ms, "
f"max {timings[-1]:.1f} ms")A large gap between the median and the maximum often points to a cold start or to queueing. Compare it with server-side metrics to see which.
Metrics
KServe model servers expose Prometheus metrics on /metrics. The Python server records histograms for each stage of a request, such as request_preprocess_seconds, request_predict_seconds, and request_postprocess_seconds, labeled by model name. Comparing these with the client-side time separates model time from network, ingress, and queueing time.
Metric names and ports vary by runtime and KServe version. Check your runtime's /metrics output before you build dashboards on them. Prometheus finds the endpoint through pod annotations. You can set them on the InferenceService metadata.
apiVersion: serving.kserve.io/v1beta1
kind: InferenceService
metadata:
name: sklearn-iris
annotations:
serving.kserve.io/enable-prometheus-scraping: "true"
spec:
predictor:
model:
modelFormat:
name: sklearn
storageUri: gs://kfserving-examples/models/sklearn/1.0/modelBeyond model metrics, watch these signals from the platform:
- Request count, error rate, and latency percentiles at the ingress or
queue-proxy. - Replica count over time, compared with your
minReplicasandmaxReplicas. A service pinned atmaxReplicaswith rising latency needs more capacity or a higher limit. - Pod restarts and
OOMKilledevents. - GPU utilization and memory, for GPU workloads.
Alert on the error rate and on p95 or p99 latency, not on averages. Averages hide the slow tail that users notice.
Log requests and responses
To record what the model receives and returns, add a logger to the predictor. KServe sends each payload as a CloudEvent to the URL you give. The mode field is all, request, or response.
apiVersion: serving.kserve.io/v1beta1
kind: InferenceService
metadata:
name: sklearn-iris
spec:
predictor:
logger:
mode: all
url: http://message-dumper.default.svc.cluster.local
model:
modelFormat:
name: sklearn
storageUri: gs://kfserving-examples/models/sklearn/1.0/modelThe receiver must exist and accept CloudEvents. A simple event-display service is enough for debugging. Payload logs can contain personal data. Treat the sink as sensitive storage and consider logging only requests or only responses. Logging every payload also adds load to the request path, so measure latency before and after you enable it.
Cold starts and scale to zero
When minReplicas is 0, the first request after an idle period must wait for a pod to schedule, pull the image, download the model, and load it. Large models make this take minutes. Symptoms are slow first calls and timeouts from clients or the ingress. Check by watching kubectl get pods -w while you send a request.
Mitigations, from cheapest to most costly:
- Set
minReplicas: 1for services with latency targets. - Use a smaller image and a model that loads faster.
- Raise client and gateway timeouts to cover the worst cold start you accept.
Roll back first, investigate second
If a new revision fails after a canary rollout, send traffic back to the known good revision before you debug. Setting canaryTrafficPercent: 0 or reverting the storageUri restores service while you read logs. Debug the failed revision's pods while they are still around.
Exercise
A new InferenceService shows READY False. kubectl get pods shows one pod in Init:CrashLoopBackOff. Which container's logs do you read first, and name two likely causes?
Show answer
Read the storage-initializer init container logs: kubectl logs <pod> -c storage-initializer. Likely causes are an incorrect storageUri (the path or bucket does not exist) and missing or insufficient credentials, such as a service account or secret that lacks read access to the bucket.
Exercise
Clients report that the first request after a quiet period takes 90 seconds, but later requests take 40 ms. The service has minReplicas: 0. What is the cause, and what is the smallest configuration change that removes the delay?
Show answer
The delay is a cold start. With scale to zero, a pod must be scheduled, its image pulled, and its model downloaded and loaded before it can answer. Setting minReplicas: 1 keeps one replica running and removes the delay, at the cost of one always-running pod.