Kubernetes StatefulSet
A StatefulSet manages stateful applications in Kubernetes with stable network identities, ordered deployment, and persistent storage per replica.
A StatefulSet is the Kubernetes workload controller for stateful applications that require stable, unique network identities, stable persistent storage per replica, and ordered, graceful deployment and scaling. Typical use cases include databases (PostgreSQL, MySQL, Cassandra), distributed message brokers (Kafka, RabbitMQ), and distributed key-value stores (Redis Cluster, etcd). A Deployment is insufficient for these workloads because it treats all replicas as interchangeable, which breaks applications that require each replica to have its own identity.
Deployment vs StatefulSet
| Feature | Deployment |
StatefulSet |
|---|---|---|
| Pod identity | Random hash suffix (e.g., app-7f9c5b-xqp2z) |
Stable ordinal index (e.g., pg-0, pg-1, pg-2) |
| Pod DNS name | Random; changes on restart | Stable: <pod>.<headless-svc>.<ns>.svc.cluster.local |
| Storage per replica | Shared or none | Dedicated PVC per replica via volumeClaimTemplates |
| Startup order | All Pods start in parallel | Sequential: pod-0 must be Ready before pod-1 starts |
| Deletion order | All Pods deleted in parallel | Reverse ordinal order: pod-N deleted first |
| Use case | Stateless apps (web servers, APIs) | Stateful apps (databases, message brokers) |
| Rolling updates | Parallel by default | Sequential, from highest ordinal to lowest |
StatefulSet Manifest
apiVersion: apps/v1
kind: StatefulSet
metadata:
name: postgres
namespace: default
spec:
serviceName: postgres-headless # must match the headless Service name
replicas: 3
selector:
matchLabels:
app: postgres
template:
metadata:
labels:
app: postgres
spec:
containers:
- name: postgres
image: postgres:16
ports:
- containerPort: 5432
env:
- name: POSTGRES_PASSWORD
valueFrom:
secretKeyRef:
name: postgres-secret
key: POSTGRES_PASSWORD
- name: PGDATA
value: /var/lib/postgresql/data/pgdata
resources:
requests:
cpu: "500m"
memory: "512Mi"
limits:
cpu: "1"
memory: "1Gi"
volumeMounts:
- name: postgres-data
mountPath: /var/lib/postgresql/data
readinessProbe:
exec:
command: ["pg_isready", "-U", "postgres"]
initialDelaySeconds: 15
periodSeconds: 10
volumeClaimTemplates:
- metadata:
name: postgres-data
spec:
accessModes: ["ReadWriteOnce"]
storageClassName: gp3
resources:
requests:
storage: 10Gi
Headless Service (Required)
A StatefulSet requires a headless Service (clusterIP: None). This Service does not have a cluster IP and instead creates a DNS A record per Pod, enabling direct Pod-to-Pod addressing:
apiVersion: v1
kind: Service
metadata:
name: postgres-headless
namespace: default
spec:
clusterIP: None # headless — no virtual IP, DNS returns Pod IPs directly
selector:
app: postgres
ports:
- port: 5432
targetPort: 5432
With this Service, each Pod gets a stable DNS name:
postgres-0.postgres-headless.default.svc.cluster.localpostgres-1.postgres-headless.default.svc.cluster.localpostgres-2.postgres-headless.default.svc.cluster.local
kubectl Commands
kubectl apply -f postgres-headless-svc.yaml
kubectl apply -f postgres-statefulset.yaml
kubectl get statefulsets
# NAME READY AGE
# postgres 3/3 2m
kubectl get pods -l app=postgres
# NAME READY STATUS RESTARTS AGE
# postgres-0 1/1 Running 0 2m
# postgres-1 1/1 Running 0 90s
# postgres-2 1/1 Running 0 60s
kubectl get pvc -l app=postgres
# NAME STATUS VOLUME CAPACITY STORAGECLASS
# postgres-data-postgres-0 Bound pvc-aaa111 10Gi gp3
# postgres-data-postgres-1 Bound pvc-bbb222 10Gi gp3
# postgres-data-postgres-2 Bound pvc-ccc333 10Gi gp3
# Scale down
kubectl scale statefulset postgres --replicas=1
# Pods are terminated in order: postgres-2 first, then postgres-1
# Rolling update (update the image)
kubectl set image statefulset/postgres postgres=postgres:16.2
# Updates postgres-2, then postgres-1, then postgres-0 (reverse ordinal)
# Check rollout
kubectl rollout status statefulset/postgres
Update Strategies
| Strategy | Behavior |
|---|---|
RollingUpdate (default) |
Updates Pods from the highest ordinal to the lowest; waits for each to be Ready before proceeding |
OnDelete |
Does not automatically update Pods; updates only when a Pod is manually deleted |
spec.updateStrategy.rollingUpdate.partition allows canary-style updates: only Pods with ordinals >= partition are updated.
Common Mistakes
- Deleting a StatefulSet without deleting PVCs. PVCs created by
volumeClaimTemplatesare not garbage-collected when the StatefulSet is deleted. They remain bound and consume storage until explicitly deleted. List them withkubectl get pvc -l app=<name>and delete them separately. - Forgetting the headless Service. A
StatefulSetmust reference a headless Service viaspec.serviceName. Without it, stable DNS names for individual Pods are not created. - Using a regular (ClusterIP) Service as the governing Service. The
spec.serviceNamemust point to a headless Service (clusterIP: None). A regular Service does not create per-Pod DNS records. - Assuming a StatefulSet behaves like a Deployment for updates. By default, updates are sequential (highest ordinal first).
maxUnavailableexists inspec.updateStrategy.rollingUpdatesince Kubernetes 1.24 to speed up updates, but ordered semantics still apply. - Not using
podManagementPolicy: Parallelwhen ordering is not needed. By default StatefulSet creates Pods one at a time. If your application does not need ordered startup (e.g., a stateless-like workload with stable storage but no leader election), setpodManagementPolicy: Parallelto speed up scaling.
Best Practices
- Always create the headless Service before the StatefulSet to ensure DNS records are ready when Pods start.
- Use
volumeClaimTemplatesso each replica gets its own dedicated PVC — never share a single PVC across StatefulSet replicas unless the storage supportsReadWriteMany. - Set the
persistentVolumeReclaimPolicytoRetainon the backingStorageClassfor production data. - Clean up PVCs explicitly after deleting a StatefulSet; do not rely on Kubernetes to delete them.
- Use init containers or lifecycle hooks to handle leader election and replica setup (e.g., Patroni for PostgreSQL HA).
Interview Questions
1. What is a StatefulSet and when should you use it instead of a Deployment?
A StatefulSet is the Kubernetes controller for stateful applications that require stable Pod identities, stable persistent storage per replica, and ordered startup/shutdown. Use it for databases (PostgreSQL, MySQL, Cassandra), message brokers (Kafka), and distributed systems that rely on stable network names or replica-specific data. Use Deployment for stateless applications where all replicas are identical and interchangeable.
2. What is a headless Service and why does a StatefulSet require one?
A headless Service has clusterIP: None. Instead of providing a single virtual IP, it causes CoreDNS to create an A record for each Pod, making each Pod individually addressable by a stable DNS name (e.g., postgres-0.postgres-headless.default.svc.cluster.local). A StatefulSet requires a headless Service so that each replica can be reached directly by name — this is essential for database replication, where replicas need to know each other's stable identities.
3. What are volumeClaimTemplates in a StatefulSet?
volumeClaimTemplates is a list of PVC templates in the StatefulSet spec. Kubernetes creates one PVC per replica using this template when each Pod is created. The PVC name follows the pattern <template-name>-<pod-name> (e.g., postgres-data-postgres-0). Unlike regular Pod volumes, these PVCs are not deleted when the StatefulSet is deleted or scaled down — they persist until explicitly removed.
4. How does a StatefulSet perform a rolling update?
By default, a StatefulSet updates Pods in reverse ordinal order: the highest-numbered Pod is updated first. It waits for the updated Pod to be Ready before proceeding to the next lower ordinal. This ensures that the primary (ordinal 0) is updated last. The partition field allows partial rollouts: only Pods with ordinals >= partition are updated, enabling canary testing.
5. What happens to PVCs when you delete a StatefulSet?
PVCs created by volumeClaimTemplates are not deleted. They remain in the cluster bound to the storage. If you recreate the StatefulSet with the same name, the new Pods will rebind to the existing PVCs and recover their data. This behavior protects against accidental data loss but requires manual PVC cleanup when you genuinely want to remove the data.
6. What is the difference between podManagementPolicy: OrderedReady and Parallel?
OrderedReady (the default) creates Pods sequentially: the next Pod is not created until the previous one is Ready. This guarantees startup order, which is important for leader election or replication setup. Parallel creates and deletes all Pods simultaneously, like a Deployment. Use Parallel only when your application does not depend on ordered startup or shutdown.
7. How would you access a specific replica of a StatefulSet?
Use the stable DNS name provided by the headless Service: <pod-name>.<headless-service-name>.<namespace>.svc.cluster.local. For example, to connect directly to the primary replica at ordinal 0: postgres-0.postgres-headless.default.svc.cluster.local:5432. This stable naming is the key reason why StatefulSets are used for databases that distinguish between primary and replica roles.
Summary
- A
StatefulSetprovides stable Pod names, stable per-replica PVCs, and ordered startup/shutdown for stateful applications. - It requires a headless Service to create stable per-Pod DNS records.
volumeClaimTemplatesautomatically creates a dedicated PVC for each replica; these PVCs survive StatefulSet deletion.- Rolling updates proceed in reverse ordinal order; the
partitionfield enables canary updates. - Always delete PVCs manually after removing a StatefulSet to avoid orphaned storage costs.
Continue Learning
Previous: Volume and PVC | Next: DaemonSet
Was this guide helpful?
CodeWithVenu is free to read, with no paywall. If this guide saved you time or helped you prepare, a small voluntary contribution helps me write more practical tutorials, architecture guides, and interview-prep content.