Startup, Readiness and Liveness Probes: What Each One Does and How to Tune The Numbers
From the publisher’s feed, collected in the ZeroLabs newsroom.
A pod can be “running” and still be unable to answer a single request. Probes are how Kubernetes finds out.When you deploy an app on Kubernetes, the pod’s status says Running as soon as its process has started. That tells you very little. A web server that is still loading a 2 GB model is “running”. So is one that has frozen. Without more information, Kubernetes would send traffic to both.Probes are the extra information. A probe is a small check that Kubernetes runs against your app, again and again: “are you done starting?”, “can you take requests?”, “are you stuck?”. Based on the answers, Kubernetes decides when to send traffic and when to restart a container.There are three kinds, and picking the wrong settings for any of them causes real problems: users hitting pods that cannot answer, healthy pods restarted in a loop, or stuck pods nobody replaces. This post explains what each probe does and how to choose its numbers, using a GPU OCR service as the example.The example: an OCR service on a GPUOur example reads text from images. It is a small web app that loads an OCR model (PaddleOCR) onto a GPU and answers POST /ocr with the text it finds in an image crop.Starting it takes time. The process has to import several gigabytes of libraries and load the model onto the GPU. For a heavy ML service like this, a normal start takes 45 to 60 seconds from the container starting to the app being ready. For that whole time the process exists, but it cannot serve anything.The app has three endpoints. /ocr does the work. The other two exist only for probes:import os, threadingimport cv2, numpy as npfrom fastapi import FastAPI, HTTPException, Response, UploadFilefrom paddleocr import PaddleOCRMODEL_DIR = os.environ["MODEL_DIR"]app = FastAPI()ocr = None # stays None until the model has finished loadingdef load_model(): global ocr ocr = PaddleOCR( text_detection_model_name="PP-OCRv6_tiny_det", text_detection_model_dir=f"{MODEL_DIR}/det", text_recognition_model_name="PP-OCRv6_tiny_rec", text_recognition_model_dir=f"{MODEL_DIR}/rec", use_doc_orientation_classify=False, use_doc_unwarping=False, use_textline_orientation=False)# Load in the background, so the server can answer probes while the model loadsthreading.Thread(target=load_model, daemon=True).start()@app.get("/live")def live(): # no work: proves the process is up and not stuck return {"live": True}@app.get("/ready")def ready(response: Response): if ocr is None: response.status_code = 503 # "not ready yet" return {"ready": ocr is not None}@app.post("/ocr")def read_text(image: UploadFile): if ocr is None: raise HTTPException(status_code=503, detail="model not loaded") img = cv2.imdecode(np.frombuffer(image.file.read(), np.uint8), cv2.IMREAD_COLOR) return {"lines": ocr.predict(img)[0]["rec_texts"]}/live always answers 200 and does no work. It means "the process is up and not frozen"./ready answers 200 only once the model has loaded, and 503 before that. It means "I can serve requests".The model loads in a background thread, so the server starts answering immediately.All three endpoints are plain def functions, so FastAPI runs each request in a thread pool. A long OCR call therefore cannot block the probe endpoints. The liveness section shows what happens if you write them as async def instead.#!/bin/sh# One worker, no --preload. --timeout 0 stops gunicorn from killing a busy worker.exec gunicorn app:app --workers 1 --worker-class uvicorn.workers.UvicornWorker --bind 0.0.0.0:8080 --timeout 0Three probes, three questionsImage 1: The three probes: what each asks and what a failure doesEach container can have up to three probes. They differ in the question they ask and in what Kubernetes does when the answer is “no”:Startup probe: “Has the app finished starting?” It runs only during boot. When it first succeeds, it stops for good. If it keeps failing until its limit runs out, Kubernetes restarts the container.Readiness probe: “Can the app take traffic right now?” It runs for the pod’s whole life. When it fails, the pod is taken out of traffic: the Service stops sending it new requests. The pod is not restarted. When the probe succeeds again, traffic returns.Liveness probe: “Is the app stuck?” It also runs for the pod’s whole life. When it fails enough times, Kubernetes restarts the container.The key difference: readiness is about traffic, and the other two are about restarts. Taking a pod out of traffic is cheap and reversible. A restart throws away everything the app had loaded, including the model on the GPU.Image 2: A pod’s life: when each probe runsThe timeline shows when each probe is active. Two details are easy to miss. First, readiness and liveness are switched off until the startup probe succeeds, so a slow boot cannot be mistaken for a hang. Second, the image pull happens before any probe starts, so it does not count against the startup budget.How a probe checks your appEvery probe uses one of four methods:httpGet: Kubernetes sends an HTTP GET to a path and port. Status 200 means success.tcpSocket: Kubernetes tries to open a connection to a port. If it connects, that is a success.exec: Kubernetes runs a command inside the container. Exit code 0 means success.grpc: for services that implement the gRPC health protocol.For a web service, use httpGet and make the endpoint answer truthfully. A TCP check proves only that something is listening on the port, which is often not the same as “the app is ready”. Here is why.Take the most common way to write such an app: it loads the model when the file is imported. Many Python apps run under gunicorn, whose master process opens the port first and then starts a worker, and the worker imports the app. For the whole time the worker is busy loading, the port is already open.On a real pod of this kind, the port was open after about 1 second, but the app answered its first HTTP request only after about 54 seconds.Image 3: One pod, two checks: the TCP check says Ready long before the app can answerWith a TCP check, Kubernetes would have marked that pod Ready after the first second and sent it requests that then sat waiting for the rest of the load. They did not fail at once: the connection was accepted and the request hung. (Plain uvicorn behaves differently. It imports the app before it opens the port, so there the port opens only when the app is ready, and a TCP check happens to work. Do not count on that, since many setups put gunicorn in front.) An HTTP check on an endpoint that answers only when the app is ready marks the pod Ready at the right moment in both cases.Our example app avoids the waiting: it loads the model in a background thread, so the server answers at once and /ready says 503 until the model is loaded. A TCP check would still be wrong for it. The port is open from the first second, so the pod would be marked Ready and receive requests that /ocr can only answer with a 503.readinessProbe: tcpSocket: port: 8080 # gunicorn opens the port before the worker has loaded the model, # so this passes while the app cannot answer yetThe five numbers on every probeEvery probe has the same five settings. The defaults are meant for small, fast apps, so for a heavy service you will change most of them.Image 4: The five settings on every probe, their defaults and good starting valuesTwo formulas cover most of the tuning:Startup budget = periodSeconds × failureThreshold. This is how long the app may take to start before Kubernetes gives up and restarts it.Time to notice a failure = (failureThreshold − 1) × periodSeconds, plus timeoutSeconds if the app hangs instead of refusing the connection.For example, a readiness probe with periodSeconds: 5, timeoutSeconds: 3 and failureThreshold: 3 takes a dead pod (connection refused) out of traffic after 10 seconds, and a hung pod (no reply) after 13 seconds.Image 5: How long a readiness probe takes to notice a dead pod and a hung podThe failures must be in a row. One success between failures resets the count, so a single slow reply does not remove a healthy pod. A small calculator for these formulas:Tuning the startup probeThe startup probe answers one question: how long should Kubernetes wait for the app to start before it restarts it? Kubernetes checks every periodSeconds and gives up after failureThreshold failed checks, so the app gets periodSeconds × failureThreshold seconds. To set it:Measure the start. On a PaddleOCR GPU service we measured 49 and 60 seconds from container start to the first successful readiness check. That is only two starts, so measure your own, several times if you can.Allow well over the slowest start. The Kubernetes documentation only says to make failureThreshold × periodSeconds long enough to cover the worst-case startup time. Our own rule of thumb is about three times the slowest start we have seen: 3 × 60 = 180 seconds.Turn it into settings. Checking every 5 seconds: 180 ÷ 5 = 36, so failureThreshold: 36.The defaults are a trap. With periodSeconds: 10 and failureThreshold: 3 the app gets 30 seconds. A service that needs 49 to 60 seconds is restarted at about 30 seconds, before it is ready, and again after every restart.A long window costs nothing. The probe stops at its first success, so a pod that is ready at 60 seconds serves at 60 seconds, not at 180. The window only matters when the app is really stuck, and then three minutes to a restart, instead of 30 seconds, is a fair price.Tuning the readiness probeReadiness should be quick to remove a bad pod and quick to bring a good one back. A good starting point is periodSeconds: 5, timeoutSeconds: 3 and failureThreshold: 3: a failing pod is out of traffic within about 10 to 13 seconds, and a recovered pod is back within one period.Readiness also controls rolling updates. When you deploy a new version, Kubernetes starts new pods and waits for them to become Ready before it stops old ones. A readiness probe that passes too early (like the TCP check above) lets Kubernetes retire the old pods while the new ones still cannot answer, which is a short outage you caused yourself.Two things to avoid:Making it too sensitive. With failureThreshold: 1 and a 1 second timeout, one slow reply under load removes the pod. Its share of the traffic moves to the other pods, which get slower, fail their checks too, and the whole service can fall out of rotation together.Making it depend on things you have not thought through. “Model loaded” belongs in readiness. Here the startup and readiness probes both ask /ready: the startup probe covers the first load and then stops for good, while readiness keeps asking for the pod’s whole life. That matters because the model can go away without the container restarting. If a gunicorn worker crashes, the gunicorn master starts a new one, which loads the model again. The startup probe does not run again, but /ready answers 503 and readiness keeps the pod out of traffic until the model is back.Tuning the liveness probeLiveness is the dangerous one. When it fails, Kubernetes restarts the container, and a restart means a full boot: libraries, model, GPU memory, and every request in progress lost. So liveness should be hard to trigger and should fire only for a pod that is truly stuck, for example a deadlocked process.Keep it light. Use a separate endpoint (/live) that does no work and checks nothing external. If liveness checks the model or the database, a slow dependency restarts every pod.Make it slower than readiness. Readiness takes a pod out of traffic within about 13 seconds. Liveness should act only after much longer, for example periodSeconds: 10, timeoutSeconds: 5, failureThreshold: 6, which is about a minute of no answers. A brief slow patch then only removes the pod from traffic and does not restart it.Never use liveness without a startup probe. Liveness starts counting the moment the container starts. If the app needs longer to boot than the liveness window, Kubernetes kills it, it starts again, and it never becomes ready.Image 7: A liveness probe alone restarts a slow-booting app forever; a startup probe fixes itThis is the configuration that causes the loop. The app needs 45 seconds to boot, but the first liveness check happens at 10 seconds and the third failure at 30 seconds, so the container is killed halfway through its boot, every time:# Only a liveness probe, and the app needs 45 s to boot.livenessProbe: httpGet: {path: /live, port: 8080} initialDelaySeconds: 10 periodSeconds: 10 failureThreshold: 3# Probes at 10, 20 and 30 s all fail, so the container is killed at ~30 s,# before the 45 s boot finishes. It restarts and fails again: killed at ~30 s, forever.Do not forget shutdownProbes also matter when a pod is removed. When Kubernetes stops a pod, it starts taking it out of the Service at the same moment it tells the app to shut down, and not every part of the cluster learns about it at the same instant. A short preStop sleep (10 seconds here) keeps the pod serving while that news spreads. terminationGracePeriodSeconds must be longer than that sleep plus the time the app needs to finish its requests, or Kubernetes kills the container early.The complete configurationAll the pieces together, for the OCR service:apiVersion: apps/v1kind: Deploymentmetadata: name: ocr-servicespec: replicas: 2 # Start one new pod, and only remove an old pod once the new one is Ready. strategy: type: RollingUpdate rollingUpdate: maxUnavailable: 0 maxSurge: 1 selector: matchLabels: app: ocr-service template: metadata: labels: app: ocr-service spec: # On shutdown, Kubernetes removes the pod from the Service while it also # sends SIGTERM. preStop sleeps so in-flight requests finish and the # endpoint removal spreads before the app stops; the 60 s grace covers it. terminationGracePeriodSeconds: 60 containers: - name: ocr-service image: my-registry/ocr-service:1.0.0 ports: - containerPort: 8080 resources: limits: nvidia.com/gpu: 1 lifecycle: preStop: exec: command: ["sleep", "10"] # Startup: gives a slow boot up to 600 s (120 x 5 s); no other probe runs until it passes. startupProbe: httpGet: {path: /ready, port: 8080} periodSeconds: 5 timeoutSeconds: 3 failureThreshold: 120 # Readiness: takes a pod out of the Service when it cannot serve; it is not restarted. readinessProbe: httpGet: {path: /ready, port: 8080} periodSeconds: 5 timeoutSeconds: 3 failureThreshold: 3 # Liveness: restarts a pod whose process is hung; it is slow and patient on purpose. livenessProbe: httpGet: {path: /live, port: 8080} periodSeconds: 10 timeoutSeconds: 5 failureThreshold: 6A short checklist to take away:One endpoint per question. /live for "not stuck", /ready for "can serve".Use httpGet on a path that answers truthfully, not a TCP check, for anything that takes time to start.Add a startup probe with a budget of about three times your slowest measured boot.Readiness: quick in, quick outLiveness: light endpoint, slow to act, and always behind a startup probe.The numbers above are starting points, not rules. Measure your own boot time, decide how long a stuck pod may stay stuck, and let those two answers set the numbers.Startup, Readiness and Liveness Probes: What Each One Does and How to Tune The Numbers was originally published in Towards AI on Medium, where people are continuing the conversation by highlighting and responding to this story.