Overview and What You Will Learn
A StatefulSet runs pods that need a stable identity: each pod gets a fixed name, its own DNS record, its own persistent volume, and ordered startup and shutdown. A Deployment treats pods as interchangeable, which suits stateless APIs but breaks databases where identity, order and storage matter. In this lab you will run a single PostgreSQL instance, then a three-pod Redis primary with replicas, and practice ordered startup, a canary rolling update, scaling and troubleshooting. It assumes the StorageClass gp3-encrypted from the Persistent Volumes topic, so use your own class name if you do not have it.
- Choosing between a Deployment and a StatefulSet
- Creating the headless Service that gives each pod a stable DNS name
- Running PostgreSQL with a volume per pod
- Building primary and replica roles from the pod's ordinal
- Rolling out updates in stages with
partition - Scaling safely and handling the PVCs that remain
- Troubleshooting stuck pods and volumes
Why This Matters in Production
Databases fail in unpleasant ways when their identity or storage is not stable. Imagine a platform team at a company like Zerodha running Redis for session data. If replicas start before the primary exists, or the application finds nodes by pod IP, every restart becomes an incident. With a StatefulSet, each pod keeps a name such as redis-0 and a DNS record that never changes, replicas start only after the primary is Ready, and each pod reattaches to its own volume after a restart.
Core Principles
A StatefulSet gives every pod an ordinal number and ties three things to it: the pod name, the DNS name and the volume.
| Feature | Deployment | StatefulSet |
|---|---|---|
| Pod names | Random suffix, such as api-7d9f8b-xkp2q |
Stable ordinal, such as redis-0 |
| Identity | Interchangeable | Unique and stable |
| Storage | Shared or none | One PVC per pod from volumeClaimTemplates |
| Startup order | All pods start together | redis-0 must be Ready before redis-1 starts |
| Termination | All pods stop together | Reverse order, highest ordinal first |
| DNS | One Service IP | Per-pod DNS through a headless Service |
Choose a StatefulSet for databases such as PostgreSQL and MySQL, message brokers such as Kafka and RabbitMQ, search engines such as Elasticsearch, and anything that needs stable pod DNS or a volume per replica. Choose a Deployment for REST APIs, web servers, stateless workers and anything with no local state.
Two limits matter before you start. A StatefulSet gives you identity and storage, but it does not configure replication, elect a primary or fail over, so a database still needs its own replication setup. And scaling PostgreSQL from one pod to three creates three separate, empty databases, not a replica set. For production PostgreSQL high availability, use an operator such as CloudNativePG, the Zalando Postgres Operator or Crunchy Postgres, which manage replication, failover and backups on top of StatefulSet-style pods.
Detailed Step-by-Step Practical Lab
Step 1 - Create the Namespace, Secret and Headless Service
A headless Service has clusterIP: None. Instead of one load-balanced IP, it creates a DNS record for every pod, such as postgres-0.postgres.statefulset-lab.svc.cluster.local. Its name must match the StatefulSet's serviceName, and a mismatch is the most common StatefulSet setup mistake:
kubectl create namespace statefulset-lab read -s -p "Postgres password: " PGPASSkubectl create secret generic postgres-credentials -n statefulset-lab \ --from-literal=username=rahul \ --from-literal=password="$PGPASS"apiVersion: v1kind: Servicemetadata: name: postgres namespace: statefulset-lab labels: app: postgresspec: clusterIP: None selector: app: postgres ports: - name: postgres port: 5432 targetPort: 5432kubectl apply -f postgres-headless-service.yamlStep 2 - Run a Single PostgreSQL Instance
The pod-level fsGroup makes the mounted volume writable by the postgres group, so no root init container is needed. Setting PGDATA to a subdirectory avoids the lost+found directory at the root of a new volume:
# postgres-statefulset.yamlapiVersion: apps/v1kind: StatefulSetmetadata: name: postgres namespace: statefulset-labspec: serviceName: postgres replicas: 1 selector: matchLabels: app: postgres template: metadata: labels: app: postgres spec: terminationGracePeriodSeconds: 60 securityContext: fsGroup: 999 fsGroupChangePolicy: OnRootMismatch containers: - name: postgres image: postgres:16 ports: - name: postgres containerPort: 5432 env: - name: POSTGRES_DB value: trading - name: POSTGRES_USER valueFrom: secretKeyRef: name: postgres-credentials key: username - name: POSTGRES_PASSWORD valueFrom: secretKeyRef: name: postgres-credentials key: password - name: PGDATA value: /var/lib/postgresql/data/pgdata - name: POSTGRES_INITDB_ARGS value: "--encoding=UTF8 --auth-host=scram-sha-256" resources: requests: cpu: 500m memory: 1Gi limits: memory: 2Gi livenessProbe: exec: command: - pg_isready - -U - $(POSTGRES_USER) - -d - $(POSTGRES_DB) initialDelaySeconds: 30 periodSeconds: 10 failureThreshold: 6 readinessProbe: exec: command: - pg_isready - -U - $(POSTGRES_USER) - -d - $(POSTGRES_DB) initialDelaySeconds: 5 periodSeconds: 5 failureThreshold: 3 volumeMounts: - name: postgres-data mountPath: /var/lib/postgresql/data volumeClaimTemplates: - metadata: name: postgres-data spec: accessModes: - ReadWriteOnce storageClassName: gp3-encrypted resources: requests: storage: 20Gikubectl apply -f postgres-statefulset.yamlkubectl get pods -n statefulset-lab -w # The PVC name is the template name plus the pod namekubectl get pvc -n statefulset-lab# postgres-data-postgres-0 Bound ... 20Gi # Confirm the stable DNS name resolves from another podkubectl run dns-test --rm -it --restart=Never --image=busybox:1.36 \ -n statefulset-lab -- nslookup postgres-0.postgresConnect applications to postgres-0.postgres, never to a pod IP, because the IP changes on every restart and the name does not.
Step 3 - Build a Redis Primary with Replicas
Three Redis pods from one StatefulSet are three independent servers until you configure replication. This start script reads the ordinal from the hostname: pod 0 becomes the primary and every other pod replicates from redis-0. It works because ordered startup guarantees redis-0 is Ready, and its DNS record exists, before redis-1 starts:
# redis-config.yamlapiVersion: v1kind: ConfigMapmetadata: name: redis-config namespace: statefulset-labdata: redis.conf: | dir /data appendonly yes appendfsync everysec maxmemory 1gb maxmemory-policy noeviction save 900 1 save 300 10 save 60 10000 start.sh: | #!/bin/sh ORDINAL=${HOSTNAME##*-} if [ "$ORDINAL" = "0" ]; then exec redis-server /etc/redis/redis.conf else exec redis-server /etc/redis/redis.conf --replicaof redis-0.redis 6379 fi# redis-headless-service.yamlapiVersion: v1kind: Servicemetadata: name: redis namespace: statefulset-lab labels: app: redisspec: clusterIP: None selector: app: redis ports: - name: redis port: 6379# redis-statefulset.yamlapiVersion: apps/v1kind: StatefulSetmetadata: name: redis namespace: statefulset-labspec: serviceName: redis replicas: 3 selector: matchLabels: app: redis template: metadata: labels: app: redis spec: terminationGracePeriodSeconds: 30 securityContext: fsGroup: 999 containers: - name: redis image: redis:7.2 command: - sh - /etc/redis/start.sh ports: - name: redis containerPort: 6379 resources: requests: cpu: 250m memory: 1Gi limits: memory: 1536Mi livenessProbe: exec: command: - redis-cli - ping initialDelaySeconds: 15 periodSeconds: 10 readinessProbe: exec: command: - redis-cli - ping initialDelaySeconds: 5 periodSeconds: 5 volumeMounts: - name: redis-data mountPath: /data - name: redis-config mountPath: /etc/redis volumes: - name: redis-config configMap: name: redis-config volumeClaimTemplates: - metadata: name: redis-data spec: accessModes: - ReadWriteOnce storageClassName: gp3-encrypted resources: requests: storage: 10Gikubectl apply -f redis-config.yaml -f redis-headless-service.yaml -f redis-statefulset.yamlkubectl get pods -n statefulset-lab -w# redis-0 becomes Ready first, then redis-1, then redis-2The maxmemory of 1 GiB leaves headroom under the 1.5 GiB container limit, so Redis evicts or rejects writes before the kernel kills the container. This setup uses noeviction, which suits a data store. For a pure cache, use allkeys-lru.
Step 4 - Verify Order, Roles and Stable Names
kubectl exec -n statefulset-lab redis-0 -- redis-cli info replication# role:master# connected_slaves:2 kubectl exec -n statefulset-lab redis-1 -- redis-cli info replication# role:slave# master_host:redis-0.redis # Write on the primary, read from a replicakubectl exec -n statefulset-lab redis-0 -- redis-cli set order:ORD-48214 confirmedkubectl exec -n statefulset-lab redis-2 -- redis-cli get order:ORD-48214# confirmedApplications reach each node at redis-0.redis.statefulset-lab.svc.cluster.local:6379, and the names survive pod restarts. This setup has no automatic failover. If redis-0 dies, nothing promotes a replica, so use Redis Sentinel or a Redis operator for that.
Step 5 - Roll Out an Update in Stages
By default a StatefulSet updates pods in reverse ordinal order, so redis-2 goes first and the primary redis-0 goes last. The partition setting limits the update to pods whose ordinal is equal to or higher than the number, which lets you canary one pod and check it before continuing:
# partition-2.yamlspec: updateStrategy: type: RollingUpdate rollingUpdate: partition: 2kubectl patch statefulset redis -n statefulset-lab --patch-file partition-2.yamlkubectl set image statefulset/redis redis=redis:7.4 -n statefulset-lab kubectl get pods -n statefulset-lab -l app=redis \ -o custom-columns=NAME:.metadata.name,IMAGE:.spec.containers[0].image# Only redis-2 runs redis:7.4 # Check replication on redis-2, then lower the partition to continuekubectl exec -n statefulset-lab redis-2 -- redis-cli info replicationLower partition to 1 and then to 0 by changing partition-2.yaml and patching again. To roll back, run kubectl rollout undo statefulset/redis. If a bad update leaves a pod crashing, a StatefulSet does not repair it automatically, so you may need to delete that pod after fixing the template.
Step 6 - Scale and Handle Leftover PVCs
New pods start in order, and the start script makes each one a replica automatically:
kubectl scale statefulset redis -n statefulset-lab --replicas=5kubectl get pods -n statefulset-lab -w # Scale down: highest ordinals stop firstkubectl scale statefulset redis -n statefulset-lab --replicas=3 # The PVCs of the removed pods are keptkubectl get pvc -n statefulset-lab -l app=redisRememberBy default, Kubernetes keeps a StatefulSet's PVCs after a scale-down or a delete, so data is never lost by accident. The
persistentVolumeClaimRetentionPolicyfield, withwhenScaledandwhenDeletedset toRetainorDelete, changes that, so review it before scaling down or deleting a database.
Step 7 - Troubleshoot Common Failures
| Symptom | Likely cause | What to do |
|---|---|---|
Pod stuck in Terminating |
Node is unreachable, or a finalizer or volume detach is blocking it | Check the node and finalizers, and force delete only once the node is confirmed gone |
| Replacement pod never starts after a node failure | The StatefulSet keeps at most one pod per identity and waits until the old one is confirmed deleted | Remove the dead node or force delete the pod, accepting the data risks below |
Multi-Attach error on the new pod |
The block volume is still attached to the failed node | Wait for detach, or fix the node state, then retry |
PVC shows Pending |
The class uses WaitForFirstConsumer, or the zone has no capacity |
Check pod scheduling first, then kubectl describe pvc |
redis-1 never appears |
redis-0 is not Ready, so ordered startup is waiting |
Run kubectl describe pod redis-0 and read its logs |
kubectl describe pod redis-0 -n statefulset-labkubectl logs redis-0 -n statefulset-labkubectl get pod redis-0 -n statefulset-lab -o jsonpath='{.metadata.finalizers}'kubectl get events -n statefulset-lab --sort-by=.lastTimestampForce deleting a pod removes it from the API immediately, without proof that the process has stopped. If the node is only unreachable and not dead, two pods with the same identity could write to the same data, so force delete only when you are certain the node is gone:
kubectl delete pod redis-0 -n statefulset-lab --force --grace-period=0Step 8 - Clean Up
Scale to zero first so pods stop in order, because deleting a StatefulSet does not guarantee ordered termination. Then delete the leftover PVCs on purpose:
kubectl scale statefulset redis postgres -n statefulset-lab --replicas=0kubectl delete statefulset redis postgres -n statefulset-labkubectl delete pvc --all -n statefulset-labkubectl delete namespace statefulset-labProduction Best Practices & Common Pitfalls
Common MistakeScaling a database StatefulSet and assuming it created replicas. Without replication configured, extra PostgreSQL or MySQL pods are separate, empty databases. Configure replication yourself or use an operator that does it.
TipUse
partitionfor major upgrades. Update one pod, verify replication lag and health, then lower the partition to continue, and update the primary last.
RememberSet
terminationGracePeriodSecondsto at least 60 for databases. The default 30 seconds can be too short for a clean checkpoint, and a hard kill risks recovery time or data loss.
- Use an operator for production PostgreSQL and MySQL. Operators automate replication, failover, backups and upgrades, which a StatefulSet alone does not.
- Spread pods across nodes and zones. Add topology spread constraints or pod anti-affinity, and remember that each volume is tied to one zone, so a pod can only run where its disk is.
- Protect pods with a PodDisruptionBudget. A budget keeps drains and autoscaler scale-downs from taking too many replicas at once, and a single-replica database needs a plan for maintenance instead.
- Set memory requests equal to limits. A database with a limit far above its request can be killed under node pressure.
- Use
podManagementPolicy: Parallelonly for independent pods. It suits data nodes that do not depend on each other, and it removes the ordering guarantees that primary and replica setups rely on. - Back up beyond volume snapshots. Snapshots are crash-consistent, so add logical backups or WAL archiving, schedule them, and test a restore.
- Watch replication lag. A replica that falls far behind loses recent writes if the primary fails, so alert on lag.
Quick Reference & Troubleshooting Commands
| Command | Description |
|---|---|
kubectl get statefulset -n NS |
List StatefulSets and replica counts |
kubectl describe statefulset NAME -n NS |
Show configuration and events |
kubectl get pods -n NS -w |
Watch ordered startup and termination |
kubectl scale statefulset NAME --replicas=N -n NS |
Scale up or down |
kubectl rollout status statefulset/NAME -n NS |
Watch a rolling update |
kubectl rollout undo statefulset/NAME -n NS |
Roll back to the previous revision |
kubectl get pvc -n NS -l app=NAME |
List the PVCs a StatefulSet created |
kubectl exec -it NAME-0 -n NS -- sh |
Open a shell in the first pod |
kubectl delete pod NAME-0 -n NS --force --grace-period=0 |
Force delete a stuck pod on a confirmed-dead node |