Skip to content
Français
Sync not enabled: your progress stays in this browser My learning
Select theme
Français

Guarantee application availability on Kubernetes

By updated

Improve this page

Logo Kubernetes

An application deployed on Kubernetes is not automatically highly available. Without a PDB, a kubectl drain can make several Pods of the same application unavailable during a voluntary disruption, with no explicit application-level safeguard. A failing node can take all your replicas with it, and badly tuned probes can restart healthy containers under load. This guide covers the four mechanisms to combine to guarantee continuity of service: replicas, PodDisruptionBudget, placement rules and production probes.

What you will learn

  • Tell voluntary and involuntary disruptions apart
  • Protect your applications with a PodDisruptionBudget (PDB)
  • Spread your Pods with anti-affinity and topology spread constraints
  • Size your probes for production (not for development)
  • Combine these mechanisms in a reference configuration

Prerequisites

Voluntary and involuntary disruptions

Kubernetes distinguishes two types of disruptions that affect your Pods:

TypeExamplesControllable?
InvoluntaryNode failure, kernel panic, network loss, OOM killNo, only replication protects
Voluntarykubectl drain, manual deletion through eviction, administration operationsYes, PDBs limit the impact when the disruption goes through the Eviction API

PDBs only protect against voluntary disruptions. For involuntary ones, the only remedy is to have several replicas distributed across several nodes (or even several zones).

A PDB has another limit: it only acts on the Eviction API. A kubectl delete pod, a scale to zero or a node failure bypass it without consulting anything. The budget frames the evictions that go through that API, not everything that can happen to your Pods.

First layer: enough replicas

Before any advanced configuration, make sure your Deployment (or StatefulSet) has at least 2 replicas in production. A single Pod is a SPOF (Single Point of Failure): no PDB and no probe can make up for the absence of replication.

apiVersion: apps/v1
kind: Deployment
metadata:
name: my-api
spec:
replicas: 3
selector:
matchLabels:
app: my-api
template:
metadata:
labels:
app: my-api
spec:
containers:
- name: api
image: my-api:1.4.0
ports:
- containerPort: 8080

Three replicas let you tolerate the loss of one node while keeping two active Pods. For stateful applications with a quorum (etcd, ZooKeeper, Consul), aim for an odd number of replicas: 3 or 5.

Second layer: PodDisruptionBudget

A PodDisruptionBudget tells Kubernetes how many Pods of an application must remain available, or how many can be missing, during a voluntary interruption. The Eviction API refuses to evict a Pod if that would violate the budget.

Syntax and options

A PDB is configured with one of these two fields, not both:

FieldMeaningExample
minAvailableNumber or percentage of Pods that must remain available2 or "50%"
maxUnavailableNumber or percentage of Pods that can be unavailable1 or "25%"

maxUnavailable is convenient for stateless applications: if you go from 3 to 5 replicas, maxUnavailable: 1 stays valid without any change. minAvailable reads better for quorum systems (etcd, ZooKeeper), where you reason in terms of the minimum number of active members. The right choice depends on the expected behaviour of the application.

Example for a Deployment of 3 replicas

apiVersion: policy/v1
kind: PodDisruptionBudget
metadata:
name: my-api-pdb
spec:
maxUnavailable: 1
selector:
matchLabels:
app: my-api

This PDB allows 1 unavailable Pod at a time. During a kubectl drain, Kubernetes evicts one Pod, waits until it is replaced and healthy, then evicts the next one.

Check the state of a PDB

Terminal window
kubectl get pdb
NAME MIN AVAILABLE MAX UNAVAILABLE ALLOWED DISRUPTIONS AGE
my-api-pdb N/A 1 1 5m

The ALLOWED DISRUPTIONS column shows how many Pods can still be evicted without violating the budget. If it shows 0, the drain will be blocked until a Pod becomes healthy again.

Patterns by application type

ApplicationPDB configurationRationale
Stateless frontend (3+ replicas)maxUnavailable: 1Tolerates restarts, one Pod is enough
Critical API (3 replicas)maxUnavailable: 1Always at least 2 active Pods
Stateful with quorum (3 replicas)minAvailable: 2Maintains the quorum
Job worker (5 replicas)maxUnavailable: "40%"Absorbs a fast drain
Singleton (replicas: 1)No PDBA PDB would block the drain indefinitely

Unhealthy Pod Eviction Policy

The spec.unhealthyPodEvictionPolicy field controls how PDBs behave with failing Pods:

  • IfHealthyBudget (default): Pods in CrashLoopBackOff are only evicted if the budget is respected. This can block a drain if the application is already failing.
  • AlwaysAllow: unhealthy Pods are always eligible for eviction, even if the budget is exhausted.

The Kubernetes documentation recommends considering AlwaysAllow so that already failing Pods do not prevent a drain operation.

A useful detail when you reread an existing PDB: the default value is not written into the object. A budget that declares nothing shows an empty field, not IfHealthyBudget. So do not conclude from a silent kubectl get pdb -o yaml that the policy does not exist: it applies anyway. An invented value, on the other hand, is rejected without ambiguity:

spec.unhealthyPodEvictionPolicy: Unsupported value: "NImporteQuoi":
supported values: "AlwaysAllow", "IfHealthyBudget"
apiVersion: policy/v1
kind: PodDisruptionBudget
metadata:
name: my-api-pdb
spec:
maxUnavailable: 1
unhealthyPodEvictionPolicy: AlwaysAllow
selector:
matchLabels:
app: my-api

Third layer: spreading the Pods

Three replicas do not protect against a node failure if they all run on the same node. Two complementary mechanisms force the distribution.

Pod anti-affinity

Anti-affinity forbids (or discourages) placing two Pods with the same label on the same node or in the same zone.

affinity:
podAntiAffinity:
requiredDuringSchedulingIgnoredDuringExecution:
- labelSelector:
matchLabels:
app: my-api
topologyKey: kubernetes.io/hostname

The scheduler refuses to place two my-api Pods on the same node. If you only have 2 nodes and 3 replicas, the third one stays Pending, and the message names the rule at fault precisely:

0/2 nodes are available: 1 node(s) didn't match pod anti-affinity rules,
1 node(s) had untolerated taint(s).

The choice between the two comes down to a single criterion: the ratio between the number of nodes and the number of replicas. Take required when the cluster always has at least as many nodes or zones as replicas, typically a cloud environment with autoscaling: the guarantee is then real and costs nothing. Take preferred as soon as that number varies or is lower: you get the spread when it is possible, without ever leaving a Pod stuck in Pending.

Pod anti-affinity also has a cost: the scheduler compares each candidate with all the Pods already placed, and this load grows with the size of the cluster. For a simple spread, topologySpreadConstraints are more readable and cheaper.

Topology spread constraints

Topology spread constraints give finer control than anti-affinity. They spread the Pods evenly across a topology domain (node, zone, region).

topologySpreadConstraints:
- maxSkew: 1
topologyKey: topology.kubernetes.io/zone
whenUnsatisfiable: DoNotSchedule
labelSelector:
matchLabels:
app: my-api
ParameterMeaning
maxSkewMaximum difference in Pod count between two topology domains
topologyKeyLabel that defines the domain (kubernetes.io/hostname, topology.kubernetes.io/zone)
whenUnsatisfiableDoNotSchedule (strict) or ScheduleAnyway (soft)

With maxSkew: 1, the scheduler maintains a balanced distribution across zones, with a maximum difference of one Pod between topology domains. If a zone goes down, the Pods in the other zones keep serving traffic.

The two mechanisms answer the same question by different means: anti-affinity reasons in terms of prohibition ("not two here"), whereas topologySpreadConstraints reason in terms of balance, with a tolerated difference between domains. The second expresses a spread across several zones more naturally, and reads better six months later.

Fourth layer: production probes

Probes (liveness, readiness, startup) let Kubernetes know whether a Pod is healthy and ready to receive traffic. Badly configured, they become a source of disruption: restart loops under load, or Pods removed from the Service too quickly.

The three types of probes

The three answer three distinct questions: "is the container alive", "can it receive traffic", "has it finished starting". Confusing them causes needless restarts. Only readiness restarts nothing: it removes the Pod from traffic without killing the container.

ProbeRoleConsequence of a failure
startupProbeChecks that the Pod has finished startingThe container is killed, then restarted according to the restartPolicy
livenessProbeChecks that the Pod is not stuck (deadlock)The container is restarted
readinessProbeChecks that the Pod can receive trafficThe Pod is removed from the Service (no more traffic)

Sizing for production

The default probe values, periodSeconds: 10, timeoutSeconds: 1 and failureThreshold: 3, are too generic for production. Under load, a CPU spike can make an HTTP probe fail without the Pod actually being down. Adapt these values to the real behaviour of your application.

startupProbe:
httpGet:
path: /healthz
port: 8080
failureThreshold: 30
periodSeconds: 2
livenessProbe:
httpGet:
path: /healthz
port: 8080
initialDelaySeconds: 0
periodSeconds: 10
failureThreshold: 3
timeoutSeconds: 5
readinessProbe:
httpGet:
path: /ready
port: 8080
periodSeconds: 5
failureThreshold: 3
timeoutSeconds: 3

Sizing rules

  1. Start with the startupProbe: failureThreshold × periodSeconds must cover the worst startup time of your application (cold start + cache loading + DB connections). Example: 30 × 2 = 60 seconds.

  2. The livenessProbe must not test the load: it detects deadlocks, not slowness. Use a light /healthz endpoint (no DB query, no external dependency). A periodSeconds: 10 with failureThreshold: 3 leaves 30 seconds before a restart.

  3. The readinessProbe can test dependencies: if your Pod depends on a database or a cache, the readinessProbe can check the connection. A failure removes the Pod from the Service without killing it. Beware: if you make the readiness depend on an unstable third-party service, you risk removing all the Pods from the Service while the application itself works. Target stable, indispensable dependencies.

  4. Separate the endpoints: /healthz for liveness (always fast), /ready for readiness (checks the dependencies).

Complete reference configuration

Here is a Deployment that combines the four layers: replicas, PDB, anti-affinity and probes tuned for production.

apiVersion: apps/v1
kind: Deployment
metadata:
name: my-api
spec:
replicas: 3
selector:
matchLabels:
app: my-api
strategy:
type: RollingUpdate
rollingUpdate:
maxUnavailable: 1
maxSurge: 1
template:
metadata:
labels:
app: my-api
spec:
affinity:
podAntiAffinity:
preferredDuringSchedulingIgnoredDuringExecution:
- weight: 100
podAffinityTerm:
labelSelector:
matchLabels:
app: my-api
topologyKey: kubernetes.io/hostname
topologySpreadConstraints:
- maxSkew: 1
topologyKey: topology.kubernetes.io/zone
whenUnsatisfiable: ScheduleAnyway
labelSelector:
matchLabels:
app: my-api
containers:
- name: api
image: my-api:1.4.0
ports:
- containerPort: 8080
resources:
requests:
cpu: 250m
memory: 256Mi
limits:
memory: 512Mi
startupProbe:
httpGet:
path: /healthz
port: 8080
failureThreshold: 30
periodSeconds: 2
livenessProbe:
httpGet:
path: /healthz
port: 8080
periodSeconds: 10
failureThreshold: 3
timeoutSeconds: 5
readinessProbe:
httpGet:
path: /ready
port: 8080
periodSeconds: 5
failureThreshold: 3
timeoutSeconds: 3

Check after deployment

An availability configuration is not checked by rereading the manifest, but by looking at where the Pods were actually placed and what the budget allows. The three commands below answer that in a few seconds.

Terminal window
# Check the distribution of the Pods across the nodes
kubectl get pods -l app=my-api -o wide
# Check the PDB
kubectl get pdb my-api-pdb
# Check the state of the probes
kubectl describe pod -l app=my-api | grep -A5 "Conditions:"

Interaction with rolling updates

The RollingUpdate strategy of the Deployment interacts with the PDB. During a rolling update, Kubernetes creates new Pods and deletes the old ones. The Pod deletions during a rolling update do not go through the Eviction API, so the PDB does not directly control the pace of the rollout. It is the maxUnavailable field of the deployment strategy that decides. However, the Pods that are unavailable during the rollout count against the budget of the PDB, which can block a drain that coincides with an update.

For maximum consistency:

  • The maxUnavailable of the strategy must be thought through together with your PDB and your target availability level
  • Use maxSurge: 1 to create the replacement Pod before deleting the old one

Troubleshooting

The symptoms below share a common cause: a protection does what it was asked, but not what you thought you were asking. A spread constraint that is too strict, a budget that is too tight, a probe that is badly sized: these settings turn against the availability they were meant to guarantee.

SymptomLikely causeSolution
Drain blocked indefinitelyPDB too restrictive, or Pod in CrashLoopBackOffCheck kubectl get pdb (ALLOWED DISRUPTIONS = 0). Switch to unhealthyPodEvictionPolicy: AlwaysAllow
Pod Pending after drainNot enough nodes / resources to respect the anti-affinityCheck kubectl describe pod (scheduling events). Switch to preferred if needed
Restart loops under loadlivenessProbe too aggressiveIncrease failureThreshold or timeoutSeconds. Separate /healthz and /ready
Pod removed from the Service but workingreadinessProbe too sensitiveIncrease the readinessProbe failureThreshold. Check that the endpoint does not depend on an unstable external service
PDB shows ALLOWED DISRUPTIONS = 0 permanentlyFewer healthy replicas than minAvailableCheck that the Deployment has enough Ready replicas. Check the probes
Blocking topology spread constraintStrict maxSkew with too few zonesSwitch to whenUnsatisfiable: ScheduleAnyway or increase maxSkew

Key takeaways

  • Kubernetes guarantees no availability by default: it is up to you to configure replicas, PDBs, placement and probes.
  • A PDB protects against voluntary disruptions (drain, upgrade). It does not protect against node failures.
  • maxUnavailable is convenient for stateless applications, minAvailable reads better for quorum systems: the right choice depends on the application.
  • Anti-affinity prevents co-locating Pods on a node. Topology spread constraints distribute evenly across zones.
  • Probes must be sized for production: liveness does not test the load, readiness can test dependencies.
  • A singleton (replicas: 1) is a SPOF. No PDB makes up for the absence of replication.
  • Combine unhealthyPodEvictionPolicy: AlwaysAllow with your PDBs so that a failing application does not block maintenance.

Knowledge check

Seven questions on what each layer really protects: a budget that a direct deletion ignores, an anti-affinity that leaves Pods waiting, and two probes not to be confused.

Knowledge check

Check what you have learned with this interactive quiz

7 questions
5 min
80% to pass

How it works

  • The timer starts when you click Start
  • Multiple choice, true/false and short answer questions
  • You can move between questions
  • Detailed results are shown at the end

Starts the quiz and the timer