StatefulSets
Replicas that are not interchangeable. A StatefulSet gives each pod a fixed ordinal, a DNS name through a headless Service and its own claim, and changes them in a predictable order.
Shows the lesson one block at a time. Arrow keys step, number keys jump to a scene, and Escape returns to the page where you were.
A Deployment treats its pods as interchangeable: any replica can serve any request, a replacement gets a random name, and they all share whatever volume the template mounts. Databases, message brokers and consensus systems do not work that way. Each member has its own data, its peers address it by name, and some members must start before others. A StatefulSetA workload controller that gives each pod a stable ordinal, a stable DNS name and its own PersistentVolumeClaim, and creates, updates and deletes pods in ordinal order. provides those guarantees. It does not provide replication, failover or backups; those belong to the application.
Here is a StatefulSet with the Service it needs, used through the rest of this lesson:
Manifestkv.yaml
- service/kv
- statefulset.apps/kv
The preview runs once this page's cluster starts.$ kubectl diff -f kv.yamlThe container mounts data, but the pod template declares no volume of that name. The controller adds one per pod, pointing at that pod’s own claim.
Reconcile, in 7 scenes
Identity
Each pod gets an ordinalThe integer index a StatefulSet assigns to each pod, unique within the set and kept by every replacement of that pod. and a name built from it: kv-0, kv-1, kv-2. A replacement for kv-1 is kv-1 again, with the same ordinal, DNS name and claim; only its UID and IP change. The controller labels every pod with statefulset.kubernetes.io/pod-name, which lets you put a Service in front of a single member, and with apps.kubernetes.io/pod-index, GA in Kubernetes 1.32, which carries the ordinal for selectors, logs and metrics.
kubectl apply -f kv.yaml
service/kv created statefulset.apps/kv created
kubectl get pods -l app=kv
NAME READY STATUS RESTARTS AGE kv-0 0/1 ContainerCreating 0 1s
kubectl get pods -l app=kv
NAME READY STATUS RESTARTS AGE kv-0 1/1 Running 0 6s kv-1 0/1 Pending 0 0s
kubectl get pods -l app=kv
NAME READY STATUS RESTARTS AGE kv-0 1/1 Running 0 12s kv-1 1/1 Running 0 6s kv-2 0/1 Pending 0 0s
kubectl get pods -l app=kv -L apps.kubernetes.io/pod-index
NAME READY STATUS RESTARTS AGE POD-INDEX kv-0 1/1 Running 0 32s 0 kv-1 1/1 Running 0 26s 1 kv-2 1/1 Running 0 20s 2
kubectl get statefulset kv
NAME READY AGE kv 3/3 32s
Applications use the ordinal as a member ID. In the upstream tutorial that runs replicated MySQL on a StatefulSet, an init container reads the ordinal from the end of the hostname, writes 100 + ordinal as the server ID, and configures ordinal 0 as the primary and every other member as a replica. A second init container clones data from the member one ordinal lower, so a fresh mysql-3 copies from mysql-2 instead of loading the primary. None of that is Kubernetes behaviour; the StatefulSet only guarantees that the number in the hostname is stable, unique and kept across restarts, which is what makes such scripts safe.
Ordinals start at 0 by default. spec.ordinals.start, GA in Kubernetes 1.31, makes them run from start to start + replicas - 1 instead. It exists for moving a StatefulSet between namespaces or clusters one member at a time: as the source scales down from its highest ordinal, a destination StatefulSet of the same name lowers its start and scales up to take over that ordinal, so the two sets together never run two pods with the same identity.
Network identity
spec.serviceName names the headless ServiceA Service with clusterIP: None. DNS answers with the addresses of the selected pods instead of one virtual IP, and gives StatefulSet pods individual records. that governs the set’s network domain. With it, every pod gets a DNS name of the form <pod>.<service>.<namespace>.svc.cluster.local, and the pod’s hostname is its own name. The Service name alone resolves to all ready members at once.
kubectl apply -f kv.yaml
service/kv created statefulset.apps/kv created
kubectl rollout status statefulset/kv
Waiting for 3 pods to be ready... Waiting for 2 pods to be ready... Waiting for 1 pods to be ready... partitioned roll out complete: 3 new pods have been updated...
kubectl run client --image=busybox:1.37 -- sleep 3600
pod/client created
kubectl wait --for=condition=Ready pod/client
pod/client condition met
kubectl get svc kv
NAME TYPE CLUSTER-IP EXTERNAL-IP PORT(S) AGE kv ClusterIP None <none> 6379/TCP 21s
kubectl exec client -- nslookup kv-0.kv.default.svc.cluster.local
Server: 10.96.0.10 Address: 10.96.0.10:53 Name: kv-0.kv.default.svc.cluster.local Address: 10.244.3.2
kubectl exec kv-0 -- hostname
kv-0
kubectl exec kv-0 -- redis-cli -h kv-2.kv ping
PONG
You create the headless Service; the StatefulSet never does. The API imposes no order between the two: a StatefulSet created first runs its pods normally, and their per-pod records start resolving once the Service exists. Until then, nothing answers for kv-0.kv.
A headless Service is for peers. Clients usually want something else: writes go to whichever member is primary, and reads can go to any replica. The usual shape is two Services over the same pods. The headless one gives each member its name, and a normal ClusterIP Service, such as the tutorial’s mysql-read, load-balances reads across every ready member. Readiness then matters twice: a member that fails its readiness probe drops out of the read Service’s endpoints and out of the headless Service’s combined record, while its own <pod>.<service> name keeps resolving only if the Service sets publishNotReadyAddresses: true.
DNS caches failures. A client that looks up kv-3 before that pod exists can keep getting the negative answer for the resolver’s cache time after the pod appears. Peer discovery that polls DNS during scale-up should tolerate that, or ask the API server for the endpoints instead.
Storage identity
Each entry in spec.volumeClaimTemplates produces one PersistentVolumeClaim per ordinal, named <template>-<statefulset>-<ordinal>. The controller creates the claim before the pod, and every incarnation of that ordinal mounts the same claim. Deleting a pod, draining its node or rolling out a template change never touches the claim.
kubectl apply -f kv.yaml
service/kv created statefulset.apps/kv created
kubectl rollout status statefulset/kv
Waiting for 3 pods to be ready... Waiting for 2 pods to be ready... Waiting for 1 pods to be ready... partitioned roll out complete: 3 new pods have been updated...
kubectl get pvc
NAME STATUS VOLUME CAPACITY ACCESS MODES STORAGECLASS VOLUMEATTRIBUTESCLASS AGE data-kv-0 Bound pvc-683592b6-265e-4b5e-9bbd-98e594120b86 1Gi RWO standard <unset> 23s data-kv-1 Bound pvc-f6bd0bc2-79fc-4679-b1b5-2e218317a90d 1Gi RWO standard <unset> 17s data-kv-2 Bound pvc-93233b12-b3de-4133-95d6-d4a9ff8fd185 1Gi RWO standard <unset> 11s
kubectl delete pod kv-1
pod "kv-1" deleted from default namespace
kubectl get pods -l app=kv -o wide
NAME READY STATUS RESTARTS AGE IP NODE NOMINATED NODE READINESS GATES kv-0 1/1 Running 0 33s 10.244.3.2 kx-worker3 <none> <none> kv-1 1/1 Running 0 8s 10.244.2.3 kx-worker2 <none> <none> kv-2 1/1 Running 0 21s 10.244.1.3 kx-worker <none> <none>
kubectl get pvc data-kv-1
NAME STATUS VOLUME CAPACITY ACCESS MODES STORAGECLASS VOLUMEATTRIBUTESCLASS AGE data-kv-1 Bound pvc-f6bd0bc2-79fc-4679-b1b5-2e218317a90d 1Gi RWO standard <unset> 27s
The replacement kv-1 has a different IP but the same volume. It also landed on the same node: kx’s default class provisions node-local directories, so the volume’s node affinity pins the pod there. On a cloud disk the same rule applies per zone, which is why StatefulSets pair naturally with WaitForFirstConsumer classes.
The claims are ordinary PVCs. A template without storageClassName uses the cluster’s default class, so in a cluster without one, data-kv-0 stays Pending, kv-0 cannot be scheduled, and the ordered start below means kv-1 is never even created. The upstream example uses ReadWriteOnce for simplicity; for production, the Kubernetes project recommends ReadWriteOncePod, which guarantees that no second pod ever mounts a member’s data. ReadWriteOncePod works only with CSI volumes, and kind’s local-path provisioner is not a CSI driver, so the examples here keep ReadWriteOnce.
Ordering
spec.podManagementPolicy decides how strictly the controller orders pod creation and deletion, and it cannot be changed after creation.
OrderedReady, the default, creates pods from0upwards and waits for each to be Running and Ready before starting the next. Scale-down removes pods from the highest ordinal down, waiting for each to terminate completely. If an earlier pod fails meanwhile, the controller stops until it recovers. The transcript under Identity shows this:kv-1appears only afterkv-0is running.Parallelcreates or terminates all the pods a scaling operation needs at once, without waiting. Identity and per-pod storage are unchanged; only the wait goes away.
Because OrderedReady waits on readiness, a readiness probe decides how fast a StatefulSet can grow. spec.minReadySeconds adds a further wait after a pod turns Ready. Never set terminationGracePeriodSeconds: 0: a pod that is not given time to shut down can leave two members believing they own the same identity.
Ordering also protects data on scale-down. The highest ordinal always goes first, so the member removed is the one that joined last, and with OrderedReady the next removal waits until the previous member has fully terminated. A clustered application gets the chance to hand off its share of data, one member at a time, as long as its shutdown hook does that work within the grace period.
Deleting a StatefulSet gives no ordering guarantee for its pods. To stop members in order, scale to 0 first and delete the StatefulSet afterwards.
Updates
spec.updateStrategy.type chooses how template changes reach the pods:
RollingUpdate, the default, replaces pods one at a time from the highest ordinal to the lowest, waiting for each replacement to be Running and Ready, plusminReadySeconds, before moving on.OnDeletechanges nothing by itself. Each pod picks up the template only when you delete it, which suits software whose members must be upgraded by hand in a specific order.Recreate, alpha in Kubernetes 1.37 behind theStatefulSetRecreateStrategyfeature gate, deletes every pod before creating any replacement, for software that cannot run two versions at once.
Every template change is stored as a ControllerRevisionAn object that holds one historical version of a StatefulSet’s or DaemonSet’s pod template. Pods carry its hash in the controller-revision-hash label., and revisionHistoryLimit, 10 by default, bounds how many are kept. kubectl rollout history statefulset/kv lists them, and kubectl rollout undo statefulset/kv writes the previous template back, which then rolls out like any other change: highest ordinal first, and only down to the partition.
rollingUpdate.partition stages a rollout. Pods with an ordinal greater than or equal to the partition get the updated template; lower ordinals keep the previous revision, and even if they are deleted they are recreated at that revision. Setting the partition to replicas - 1 makes the highest member a canary.
kubectl apply -f kv.yaml
service/kv created statefulset.apps/kv created
kubectl rollout status statefulset/kv
Waiting for 3 pods to be ready... Waiting for 2 pods to be ready... Waiting for 1 pods to be ready... partitioned roll out complete: 3 new pods have been updated...
kubectl patch statefulset kv -p '{"spec":{"updateStrategy":{"rollingUpdate":{"partition":2}}}}'
statefulset.apps/kv patched
kubectl set image statefulset/kv redis=redis:8.10
statefulset.apps/kv image updated
kubectl get pods -l app=kv -L controller-revision-hash
NAME READY STATUS RESTARTS AGE CONTROLLER-REVISION-HASH kv-0 1/1 Running 0 23s kv-7bcdb48985 kv-1 1/1 Running 0 17s kv-7bcdb48985 kv-2 0/1 ContainerCreating 0 3s kv-788cfd4d86
kubectl rollout status statefulset/kv
Waiting for 1 pods to be ready... partitioned roll out complete: 1 new pods have been updated...
kubectl delete pod kv-0
pod "kv-0" deleted from default namespace
kubectl get pods -l app=kv -o custom-columns=NAME:.metadata.name,IMAGE:.spec.containers[0].image
NAME IMAGE kv-0 redis:8.8 kv-1 redis:8.8 kv-2 redis:8.10
kubectl patch statefulset kv -p '{"spec":{"updateStrategy":{"rollingUpdate":{"partition":0}}}}'
statefulset.apps/kv patched
kubectl get pods -l app=kv -o custom-columns=NAME:.metadata.name,IMAGE:.spec.containers[0].image
NAME IMAGE kv-0 redis:8.10 kv-1 redis:8.10 kv-2 redis:8.10
The deleted kv-0 came back on redis:8.8, because it sits below the partition. Lowering the partition to 0 released the rest.
rollingUpdate.maxUnavailable caps how many pods may be unavailable during an update. It takes a number or a percentage, defaults to 1 and cannot be 0, and any unavailable pod in the set counts against it. Its feature gate, MaxUnavailableStatefulSet, is alpha in Kubernetes 1.24 to 1.34 and beta from 1.35: enabled by default in 1.35.0 to 1.35.3, disabled by default in 1.35.4 to 1.36, and enabled by default again in 1.37. With Parallel pod management and maxUnavailable above 1, the controller terminates and creates up to that many pods simultaneously, so they can become ready out of order.
PVC retention (GA 1.32)
By default, neither scaling down nor deleting a StatefulSet deletes its claims, so the data survives and comes back when the ordinals do. spec.persistentVolumeClaimRetentionPolicy, GA in Kubernetes 1.32, makes that a choice with two fields:
whenDeletedapplies when the StatefulSet itself is deleted.whenScaledapplies when scale-down removes ordinals.
Each takes Retain, the default, or Delete. The controller implements Delete with owner references: on deletion, claims are owned by the StatefulSet and garbage-collected after its pods go; on scale-down, a removed ordinal’s claim is owned by its pod and goes with it. Scaling back up then creates fresh, empty claims.
spec:
persistentVolumeClaimRetentionPolicy:
whenDeleted: Retain
whenScaled: Delete
kubectl apply -f kv.yaml
service/kv created statefulset.apps/kv created
kubectl rollout status statefulset/kv
Waiting for 3 pods to be ready... Waiting for 2 pods to be ready... Waiting for 1 pods to be ready... partitioned roll out complete: 3 new pods have been updated...
kubectl scale statefulset kv --replicas=1
statefulset.apps/kv scaled
kubectl get pvc
NAME STATUS VOLUME CAPACITY ACCESS MODES STORAGECLASS VOLUMEATTRIBUTESCLASS AGE data-kv-0 Bound pvc-683592b6-265e-4b5e-9bbd-98e594120b86 1Gi RWO standard <unset> 28s data-kv-1 Bound pvc-f6bd0bc2-79fc-4679-b1b5-2e218317a90d 1Gi RWO standard <unset> 22s data-kv-2 Bound pvc-93233b12-b3de-4133-95d6-d4a9ff8fd185 1Gi RWO standard <unset> 16s
kubectl patch statefulset kv -p '{"spec":{"persistentVolumeClaimRetentionPolicy":{"whenScaled":"Delete"}}}'
statefulset.apps/kv patched
kubectl scale statefulset kv --replicas=3
statefulset.apps/kv scaled
kubectl scale statefulset kv --replicas=1
statefulset.apps/kv scaled
kubectl get pvc
NAME STATUS VOLUME CAPACITY ACCESS MODES STORAGECLASS VOLUMEATTRIBUTESCLASS AGE data-kv-0 Bound pvc-683592b6-265e-4b5e-9bbd-98e594120b86 1Gi RWO standard <unset> 98s
The policy only covers deliberate removal. When a pod fails, for example because its node dies, and the control plane creates a replacement, the claim is kept whatever the policy says. Whether the volume itself survives a deleted claim is a separate decision: that is the PersistentVolume’s reclaim policy.
Running stateful apps
A StatefulSet guarantees identity, ordering and storage, and nothing about the data. Everything a database needs beyond that belongs to the application or to an operator that knows it:
- Replication and membership. The application decides which member is primary, how replicas copy data and how a member that comes back with an old volume catches up. In quorum systems such as etcd, a pod the StatefulSet adds is not a voting member until the cluster admits it, and a member removed by scale-down still counts towards the quorum until it is taken out of the configuration.
- Failover. Promoting a replica and moving a role label or a stable primary Service is the operator’s job.
- Backups. Volume snapshots are crash-consistent at best; databases need application-level backups or a quiesced snapshot.
- Disruptions. A PodDisruptionBudget keeps a quorum running while nodes are drained.
That is why many teams run stateful systems through an operator, a controller that encodes one application’s procedures, rather than through a bare StatefulSet.
kubectl --context kind-kx apply -f kv.yamlkubectl --context kind-kx get pods -l app=kv -wkubectl --context kind-kx rollout status statefulset/kvkubectl --context kind-kx get pvckubectl --context kind-kx run client --image=busybox:1.37 -- sleep 3600kubectl --context kind-kx wait --for=condition=Ready pod/clientkubectl --context kind-kx exec client -- nslookup kv-1.kv.default.svc.cluster.localkubectl --context kind-kx delete pod kv-1kubectl --context kind-kx get pods -l app=kv -o widekubectl --context kind-kx patch statefulset kv -p '{"spec":{"persistentVolumeClaimRetentionPolicy":{"whenScaled":"Delete"}}}'kubectl --context kind-kx scale statefulset kv --replicas=1kubectl --context kind-kx get pvc
For your own kind cluster kx: copy a command and paste it into your terminal. Run in the simulator runs the same command in this page's simulated cluster instead; nothing on this page touches your machine. Save the Service and StatefulSet from this lesson as kv.yaml first, and stop the watch once kv-2 is Running. Clean up with kubectl --context kind-kx delete -f kv.yaml, then delete the client pod and the remaining claim data-kv-0.
Actual state
Check your understanding
Your first answer to each check is the one that counts. After a miss you can answer again; passing every check reconciles the lesson.
Lesson not yet reconciled
Desired: 5 objectives, 0 metReconciled: 5 of 5 objectives met
- Explain stable pod names, ordinals and per-pod DNS names through a headless Service. (not yet met)
- Give each replica its own volume with volumeClaimTemplates and follow a claim across a pod replacement. (not yet met)
- Choose OrderedReady or Parallel pod management and predict how scaling proceeds. (not yet met)
- Stage an update with partition, and describe what maxUnavailable changes. (not yet met)
- Set persistentVolumeClaimRetentionPolicy so that scale-down and deletion keep or remove claims. (not yet met)
Pass every check above to reconcile this lesson.
Every check has passed, so the desired state is met. First-try accuracy: 0 of 5. This lesson's review cards are in your queue.
Practice
Put this lesson to work on the simulated cluster. Everything runs in your browser, with nothing to install.
Changed since the notes
This lesson draws on an earlier set of study notes. Where the documentation contradicts a claim in them, qualifies it or has moved past it, the claim is listed here with the corrected statement and the source it was checked against.
Show 6 corrections
The notes said'Deleting a StatefulSet doesn't delete its PVCs by default… You must manually delete PVCs'
CorrectedStill the default (Retain), but spec.persistentVolumeClaimRetentionPolicy is GA since 1.32: whenDeleted and whenScaled each accept Retain (default) or Delete, so PVCs can be removed automatically on StatefulSet deletion or scale-down.
Sourcekubernetes.io/docs/concepts/workloads/controllers/statefulset#persistentvolumeclaim-retention
The notes saidUpdates proceed strictly one pod at a time
Correctedspec.updateStrategy.rollingUpdate.maxUnavailable (MaxUnavailableStatefulSet) is beta: alpha 1.24 to 1.34, beta enabled by default in 1.35.0 to 1.35.3, disabled by default in 1.35.4 to 1.36, enabled by default again from 1.37. Default value is 1; it accepts a number or percentage. With Parallel pod management and maxUnavailable > 1 the controller replaces up to that many pods at once.
The notes saidOrdinals always start at 0 ('The first pod is always index 0')
CorrectedOrdinals start at 0 by default, but spec.ordinals.start (StatefulSetStartOrdinal, GA 1.31) assigns ordinals from start to start+replicas-1, used for example to migrate a StatefulSet between clusters or namespaces.
Sourcekubernetes.io/docs/concepts/workloads/controllers/statefulset#start-ordinal
The notes saidThe headless Service 'must exist before the StatefulSet'
CorrectedThe StatefulSet needs a headless Service for per-pod network identity and you are responsible for creating it, but the API imposes no ordering. The StatefulSet can be created first; per-pod DNS records (pod-N.svc.ns.svc.cluster.local) resolve once the headless Service exists.
Sourcekubernetes.io/docs/concepts/workloads/controllers/statefulset#limitations
The notes saidUses 'primary.database.default.svc.cluster.local' to imply role-based DNS ('always reaching the primary')
CorrectedStatefulSet DNS is ordinal-based only: <statefulset>-<ordinal>.<headless-service>.<namespace>.svc.cluster.local. Kubernetes has no notion of a primary; a stable primary name needs a separate Service selecting a role label that an operator or the database's own failover tooling keeps up to date.
Sourcekubernetes.io/docs/concepts/workloads/controllers/statefulset#stable-network-id
The notes saidThe Parallel policy means 'pods are created and deleted in parallel like Deployments'
CorrectedpodManagementPolicy: Parallel makes scale-up and scale-down create or terminate pods without waiting for each other. Rolling updates still replace one pod at a time unless rollingUpdate.maxUnavailable > 1 (beta, see above), in which case up to maxUnavailable pods are replaced at once. Identity, stable storage and per-pod PVCs still differ from Deployments.
Sourcekubernetes.io/docs/concepts/workloads/controllers/statefulset#parallel-pod-management
Every correction across the guide, by note and topic.
Sources
Checked against kubernetes.io and AWS documentation for Kubernetes 1.37 on .
- kubernetes.io/docs/concepts/workloads/controllers/statefulset
- kubernetes.io/docs/tutorials/stateful-application/basic-stateful-set
- kubernetes.io/docs/tasks/run-application/run-replicated-stateful-application
- kubernetes.io/docs/concepts/services-networking/dns-pod-service
- kubernetes.io/docs/concepts/storage/persistent-volumes
StatefulSets
↓ ↑ step, 1 to 7 scene, Esc leave