StatefulSets

Intermediate · 16 min

Pods with stable names, DNS and disks: ordered start and stop, volumeClaimTemplates, PVC retention, partitioned updates, and what a StatefulSet will not do.

Before thisDeployments and ReplicaSetsRolling updates and rollbacks

TechWorld with Nana · 16 min

StatefulSets

The player loads from youtube-nocookie.com when you press play. Nothing reaches YouTube before that.

Taught by TechWorld with NanaReport a problem with this video
Not started
Set this lesson's status

What you'll learn

  • A StatefulSet gives each Pod a fixed identity: an ordinal name (pg-0, pg-1), a stable DNS name through a headless Service, and its own PersistentVolumeClaim from volumeClaimTemplates.
  • A replaced Pod comes back with the same name and the same claim, so it finds its own data. Identity follows the ordinal, not the Pod.
  • By default Pods start one at a time in order, each waiting for the previous one to be Ready, and stop in reverse order. podManagementPolicy: Parallel drops that.
  • Scaling down or deleting the StatefulSet keeps the PVCs unless persistentVolumeClaimRetentionPolicy says Delete. Data outliving Pods is the point.
  • Rolling updates go from the highest ordinal down. A partition updates only ordinals at or above it, which makes a built-in canary.
  • A StatefulSet does not replicate, back up or fail over your database. That logic lives in the database or an operator.

Cattle that need names

A Deployment treats Pods as interchangeable. Any one can be killed and replaced by a stranger with a random suffix and an empty disk. That is perfect for a web API and wrong for a database cluster. A Postgres or Kafka or etcd member has to keep its identity across restarts: peers refer to it by name, it owns a particular slice of data on a particular disk, and the order members start in can matter, since the first one may need to bootstrap the cluster.

A StatefulSet is the workload controller for that. It still creates Pods from a template and replaces them when they die, but it gives each one a stable identity that survives replacement.

Three kinds of stable identity

apiVersion: v1
kind: Service
metadata:
  name: pg
spec:
  clusterIP: None          # headless: DNS returns Pod addresses, one name per Pod
  selector: {app: pg}
  ports: [{port: 5432}]
---
apiVersion: apps/v1
kind: StatefulSet
metadata:
  name: pg
spec:
  serviceName: pg
  replicas: 3
  selector:
    matchLabels: {app: pg}
  persistentVolumeClaimRetentionPolicy:
    whenScaled: Retain
    whenDeleted: Retain
  template:
    metadata:
      labels: {app: pg}
    spec:
      containers:
      - name: postgres
        image: postgres:18.1
        ports: [{containerPort: 5432}]
        volumeMounts:
        - {name: data, mountPath: /var/lib/postgresql}
  volumeClaimTemplates:
  - metadata:
      name: data
    spec:
      accessModes: [ReadWriteOnce]
      resources: {requests: {storage: 10Gi}}
  1. A stable name. Pods are named <statefulset>-<ordinal>: pg-0, pg-1, pg-2. In the lab, pg-1 had spec.hostname: pg-1 and spec.subdomain: pg.
  2. Stable DNS. With the headless Service named in serviceName, cluster DNS publishes a record per Pod, pg-0.pg.default.svc.cluster.local, so clients and peers can reach one specific member. Cluster DNS covers the records.
  3. Stable storage. For each entry in volumeClaimTemplates, the controller creates a PersistentVolumeClaim named <template>-<pod>: data-pg-0, data-pg-1, data-pg-2. Each Pod mounts its own. PersistentVolumes and claims explains binding.

Think of numbered lockers in a gym. Members come and go, but whoever is assigned locker 1 always gets locker 1 and its contents.

Identity belongs to the ordinal. When pg-1 was deleted in the lab, a new pg-1 appeared within three seconds with a different UID but the same claim:

hostname=pg-1 subdomain=pg claim=data-pg-1 uid=0909e3bd-...
recreated: name=pg-1 claim=data-pg-1 uid=2423ba25-...

Ordered start, reverse stop

With the default podManagementPolicy: OrderedReady, Pods are created one at a time, and each must be Running and Ready before the next is created. The lab nodes run no containers and had no storage provisioner, so PersistentVolumes were created by hand for the claims to bind to, and a script marked each Pod Ready, playing the kubelet. The controller then did this:

t=2s  pg-0:Pending
t=6s  pg-0:Running/ready=True pg-1:Pending
t=8s  pg-0:Running/ready=True pg-1:Running/ready=True pg-2:Pending
t=10s pg-0:Running/ready=True pg-1:Running/ready=True pg-2:Running/ready=True

pg-1 did not exist until pg-0 was Ready. Scaling down goes the other way: scaling to one replica removed pg-2, then pg-1, keeping pg-0. That ordering lets a database bring up its first member as the bootstrap node and add followers after it. If your software doesn’t care, podManagementPolicy: Parallel starts and stops them all at once, which is much faster for large sets.

Data outlives Pods

After scaling down to one replica, all three claims were still there and bound:

data-pg-0 Bound lab-pv-3
data-pg-1 Bound lab-pv-1
data-pg-2 Bound lab-pv-2

Scaling back to three reattached pg-2 to data-pg-2. That is the safe default: the controller never deletes data you didn’t ask it to. persistentVolumeClaimRetentionPolicy (GA since 1.32) lets you choose Delete separately for whenScaled and whenDeleted, for example to clean up claims for throwaway test clusters. Remember that deleting a claim may delete the disk, depending on the PersistentVolume’s reclaim policy.

Updating a StatefulSet

The default RollingUpdate strategy replaces Pods one at a time, from the highest ordinal down, waiting for each to be Ready. There is no surge: pg-2 must stop before the new pg-2 starts, because they would share a name and a disk.

A partition limits the rollout to ordinals at or above it. With partition: 2 and the image changed to postgres:18.2:

pg-0 postgres:18.1 pg-56997f4f75
pg-1 postgres:18.1 pg-56997f4f75
pg-2 postgres:18.2 pg-c8b64844b
current=pg-56997f4f75 update=pg-c8b64844b updated=1

Only pg-2 moved to the new revision. Revisions are stored as ControllerRevision objects, and each Pod carries a controller-revision-hash label. Lower the partition to continue. In v1.37 maxUnavailable for StatefulSets is beta and on by default, letting more than one Pod update at a time; OnDelete leaves updates entirely to you, replacing a Pod only when you delete it.

One trap: with OrderedReady, if a bad template leaves a Pod never Ready, the rollout stops and does not repair itself even after you revert the template. The docs call this out; you may need to delete the stuck Pod after reverting.

What a StatefulSet does not do

It does not make a database highly available. It doesn’t configure replication between pg-0 and pg-1, elect a new primary when pg-0 dies, take backups, or move data when you scale. A StatefulSet gives you stable building blocks; the database’s own clustering, or an operator such as CloudNativePG, does the rest. Most teams running production databases on Kubernetes use an operator, and many decide a managed database is less work.

About the video

The embed is TechWorld with Nana’s “Kubernetes StatefulSet simply explained” (June 2020, 16 minutes). Its chapters cover stateless against stateful applications, deploying each, Deployment against StatefulSet, Pod identity, scaling a database with a primary and replicas, Pod state, the Pod identifier, the two Pod endpoints, and a final note that replicating stateful apps is still up to you, which is this lesson’s closing point. It uses master/slave wording for database roles and predates the PVC retention policy and StatefulSet maxUnavailable, both covered here. English was judged from the English title and caption track; there is no audio-track metadata. Piyush’s 2025 video in deeper is the hands-on version, with a headless Service, a StorageClass and a MongoDB StatefulSet.

What was run: the StatefulSet, its claims, the ordered start, the recreated pg-1, the reverse scale-down, the retained claims and the partitioned update ran against a local v1.37.3 control plane on 2026-11-28. Its nodes run no containers and it has no storage provisioner, so PersistentVolumes were created by hand and Pod readiness was written into Pod status by a script standing in for the kubelet. DNS records need cluster DNS and are described from the docs.

Where this fits

Some workloads need exactly one Pod on every node rather than a numbered set: DaemonSets.

Check yourself

  1. 01pg-1 is deleted. What comes back, and which disk does it get?

    A new Pod named pg-1, with a new UID and probably a new IP, mounting the same PVC, data-pg-1. The StatefulSet controller recreates the missing ordinal from the template, and the claim name is derived from the template name and the Pod name.

  2. 02Why does a StatefulSet need a headless Service?

    To give each Pod its own DNS record, such as pg-0.pg.default.svc.cluster.local. A normal Service load-balances across Pods behind one virtual IP, but a database client often needs to reach one specific member, like the primary.

  3. 03You scale a StatefulSet from 3 to 1 and back to 3. What happens to the data on pg-1 and pg-2?

    With the default Retain policy, data-pg-1 and data-pg-2 stay while the Pods are gone, and the recreated Pods reattach to them with the old data. With whenScaled: Delete the claims would be removed on scale-down.

  4. 04How would you try a new Postgres image on one replica before the rest?

    Set spec.updateStrategy.rollingUpdate.partition to the highest ordinal, say 2 for three replicas, then change the image. Only pg-2 is updated. Lower the partition step by step to continue, or revert the template to back out.

Go deeper

Notes

Private to you

Esc
↑↓ navigate↵ open? shortcuts

Keyboard shortcuts

Press Esc to close

Anywhere

⌘K
Search and commands
/
Search
?
This sheet
Esc
Close

Reading a lesson

J
Next lesson
K
Previous lesson
B
Bookmark