Skip to content
Tutorials Center
My learning

Topics

Lesson 19 of 78 ยท Workloads

StatefulSets

Learn how StatefulSets give pods stable names, ordered startup, a headless Service and per-pod volumes, and how their update strategies differ from Deployments.

Deployments treat pods as interchangeable cattle: any pod can be replaced by any other, names are random, and storage (if any) is shared or thrown away. That is perfect for web servers and wrong for databases, message brokers and clustered systems such as PostgreSQL with replicas, Kafka, Elasticsearch or ZooKeeper. Those need each member to keep its own name, its own network address and its own disk across restarts, and often need to start and stop in a particular order.

A StatefulSet is the workload object for that. It creates pods named name-0, name-1, name-2 and so on, brings them up one at a time, gives each one a private PersistentVolumeClaim, and reattaches the same volume when a pod is rescheduled. This lesson covers the four guarantees, the manifest, the update strategies, and a Python stand-in that models ordered creation with stable names. Storage objects themselves are covered later in PersistentVolumes and claims.

What a StatefulSet guarantees

Stable name web-0, web-1, web-2.
Stable DNS Each pod has its own address.
Stable storage Its own volume, reattached on restart.
Ordered Start up and shut down in order.
1 / 2

The manifest

A StatefulSet needs a headless Service (a Service with clusterIP: None) to give its pods DNS names, and usually a volumeClaimTemplates section to create their volumes. Everything below is read-only; there is no cluster on the site.

YAML
apiVersion: v1
kind: Service
metadata:
  name: db-headless
spec:
  clusterIP: None            # headless: no virtual IP, DNS returns pod IPs
  selector:
    app: db
  ports:
    - name: sql
      port: 5432
---
apiVersion: apps/v1
kind: StatefulSet
metadata:
  name: db
spec:
  serviceName: db-headless   # must name the headless Service
  replicas: 3
  selector:
    matchLabels:
      app: db
  podManagementPolicy: OrderedReady
  updateStrategy:
    type: RollingUpdate
    rollingUpdate:
      partition: 0
  persistentVolumeClaimRetentionPolicy:
    whenDeleted: Retain
    whenScaled: Retain
  template:
    metadata:
      labels:
        app: db
    spec:
      containers:
        - name: postgres
          image: postgres:17
          ports:
            - containerPort: 5432
          volumeMounts:
            - name: data
              mountPath: /var/lib/postgresql/data
  volumeClaimTemplates:
    - metadata:
        name: data
      spec:
        accessModes: ["ReadWriteOnce"]
        resources:
          requests:
            storage: 10Gi

(A real PostgreSQL pod also needs a password Secret and sensible settings; this manifest only shows the StatefulSet-specific parts.)

Stable identity

Names. Pods are db-0, db-1, db-2. The number is the ordinal. When db-1 is deleted or its node dies, the replacement is called db-1 again, not db-7x2k.

DNS. The headless Service gives each pod an address of the form <pod>.<service>.<namespace>.svc.cluster.local, for example db-0.db-headless.default.svc.cluster.local. The DNS name keeps pointing at the right pod even though its IP address changes. That is how a replica finds its primary ("always connect to db-0"), and how members of a cluster find each other. The Service name alone returns the IPs of all ready pods. See services and DNS and service discovery.

Storage. For every pod, the controller creates a PersistentVolumeClaim from each template, named <template>-<pod>: data-db-0, data-db-1, and so on. If a pod is rescheduled, the new db-1 mounts the existing data-db-1. Scaling down does not delete claims by default, so scaling back up reattaches the old data. The persistentVolumeClaimRetentionPolicy can change this to Delete for whenScaled and/or whenDeleted; the default for both is Retain, because data loss is worse than leftover disks.

Order. With the default podManagementPolicy: OrderedReady:

  • Scale-up creates db-0 first, waits until it is Running and Ready, then db-1, and so on.
  • Scale-down and deletion go in reverse: highest ordinal first, one at a time.
  • If a pod fails to become Ready, the StatefulSet stops there and creates nothing further.

Set podManagementPolicy: Parallel when the members do not depend on one another's order; it launches and terminates pods all at once. It does not affect rolling updates, which stay ordered.

Watching ordered creation

The stand-in below models how a StatefulSet scales: ascending names, one at a time, a new claim per pod, claims kept on scale-down and reused on scale-up. It is a simplified model, not Kubernetes code, and it leaves out readiness waiting, which here always succeeds instantly.

Python Ordered pods with stable names and volumes

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Notice that after scaling down to 1 and up again, db-1 and db-2 come back with their old volumes. Identity, not just the number of pods, is what the StatefulSet is managing.

Update strategies

spec.updateStrategy has two types:

  • RollingUpdate (default): pods are replaced one at a time in reverse ordinal order (db-2, then db-1, then db-0). The controller waits for each replacement to be Running and Ready before touching the next. If a new pod never becomes ready, the update halts, and, unlike a Deployment, you may need to fix or delete the stuck pod by hand.
  • OnDelete: the controller does not update anything. A pod gets the new template only after you delete it manually. Use it when you need full control over the order, for example to upgrade replicas first and the primary last.

The partition field of RollingUpdate turns an update into a staged rollout: only pods with an ordinal greater than or equal to the partition receive the new template; lower ordinals stay on the old one, even if they restart. Start with a high partition (a canary of just the last pod), check it, then lower it step by step to zero. There is also an optional maxUnavailable (a beta feature) that allows several pods to update at once.

Python Reverse-order update with a partition

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

The second run shows a canary: only web-3 and web-4 moved to v2, the rest wait. The third run shows the stall: web-2 never becomes ready, so web-1 and web-0 are left alone.

Practical advice

  • Do not run a database on Kubernetes just because you can. A StatefulSet gives you identity and storage, not replication, failover or backups. For databases, prefer a managed service or an operator that encodes the database's operational knowledge (see running databases and backups and operators).
  • Scaling is not rebalancing. Adding db-3 creates a pod and a volume. Whether data moves to it is up to the application.
  • Deleting a StatefulSet does not stop its pods in order. To scale to zero in order first, run kubectl scale statefulset db --replicas=0, then delete.
  • Volumes follow the zone. A claim on a zonal disk ties the pod to that zone; if the zone is full or down, the pod stays Pending. Use volumeBindingMode: WaitForFirstConsumer storage classes so volumes are created where the pod lands (see storage classes).
  • You cannot change volumeClaimTemplates after creation, so to resize volumes, expand the claims directly (if the StorageClass allows it) and recreate the StatefulSet with --cascade=orphan.
  • Always use a readiness probe, since "Ready" is what gates the next pod (probes).

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What is the name of the pod that replaces a deleted pod 'db-1' in a StatefulSet?

    StatefulSet pods keep their ordinal identity. The replacement is db-1 and it reattaches data-db-1.
  2. 2. What is the purpose of the headless Service (clusterIP: None) used with a StatefulSet?

    A headless Service has no virtual IP; DNS returns the pods' IPs and per-pod names like db-0.db-headless..., which stay stable across restarts.
  3. 3. In which order does a StatefulSet's default RollingUpdate replace pods?

    Updates go in reverse ordinal order, one at a time, and halt if a new pod does not become Ready.
  4. 4. With partition: 3 on a 5-pod StatefulSet, which pods get the new template?

    Only ordinals greater than or equal to the partition are updated, which makes partition useful for staged rollouts.
  5. 5. You scale a StatefulSet from 3 to 1 and back to 3. What happens to the data of db-1 and db-2?

    By default claims are retained on scale-down (persistentVolumeClaimRetentionPolicy whenScaled: Retain), so the old volumes return with their pods.

Summary

  • A StatefulSet gives pods stable names (name-0, name-1), stable DNS through a headless Service, and per-pod volumes from volumeClaimTemplates.
  • Pods start in ascending order waiting for Ready and stop in descending order; Parallel relaxes this for scaling.
  • Volume claims are kept on scale-down and deletion by default, controlled by persistentVolumeClaimRetentionPolicy.
  • RollingUpdate goes from the highest ordinal down; partition gives staged canaries; OnDelete leaves updates to you.
  • A StatefulSet provides identity and storage only; replication, failover and backups are the application's or an operator's job.

Next: DaemonSets.