StatefulSets
Deployments treat Pods as interchangeable cattle: random names, any order, shared or no storage. Databases, message brokers and other clustered systems need the opposite: each replica has an identity and its own data. A StatefulSet provides:
| Guarantee | Deployment | StatefulSet |
|---|---|---|
| Pod names | web-7c5d-x2k4p (random) |
db-0, db-1, db-2 (ordinal, stable) |
| DNS name per Pod | no | db-0.db.<ns>.svc.cluster.local (via a headless Service) |
| Storage | shared PVC or none | one PVC per Pod from volumeClaimTemplates, reattached after restarts |
| Start/stop order | all at once | ordered: 0, 1, 2 up; 2, 1, 0 down (by default) |
apiVersion: v1
kind: Service
metadata:
name: db
spec:
clusterIP: None # headless: required for per-Pod DNS
selector: {app: db}
ports: [{port: 5432}]
---
apiVersion: apps/v1
kind: StatefulSet
metadata:
name: db
spec:
serviceName: db
replicas: 3
selector:
matchLabels: {app: db}
podManagementPolicy: OrderedReady # or Parallel
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]
storageClassName: fast
resources:
requests:
storage: 20GiIdentity and storage
Each Pod gets a PVC named <template>-<statefulset>-<ordinal>. If db-1 is deleted or its node fails, the replacement is again called db-1 and mounts the same claim data-db-1:
statefulset = {"name": "db", "replicas": 3, "claim_template": "data", "service": "db", "ns": "shop"}
claims = {}
def ensure_pods(sts):
for i in range(sts["replicas"]):
pod = f"{sts['name']}-{i}"
claim = f"{sts['claim_template']}-{pod}"
new = claim not in claims
claims.setdefault(claim, {"data": []})
print(f"{pod}: claim {claim} ({'new' if new else 'reused'}), "
f"dns {pod}.{sts['service']}.{sts['ns']}.svc.cluster.local")
ensure_pods(statefulset)
claims["data-db-1"]["data"].append("wal-0001")
print("-- db-1 is deleted and recreated --")
ensure_pods(statefulset)
print("data-db-1 still contains:", claims["data-db-1"]["data"])db-0: claim data-db-0 (new), dns db-0.db.shop.svc.cluster.local
db-1: claim data-db-1 (new), dns db-1.db.shop.svc.cluster.local
db-2: claim data-db-2 (new), dns db-2.db.shop.svc.cluster.local
-- db-1 is deleted and recreated --
db-0: claim data-db-0 (reused), dns db-0.db.shop.svc.cluster.local
db-1: claim data-db-1 (reused), dns db-1.db.shop.svc.cluster.local
db-2: claim data-db-2 (reused), dns db-2.db.shop.svc.cluster.local
data-db-1 still contains: ['wal-0001']
Note: Scaling down or deleting a StatefulSet does not delete its PVCs by default, to protect data. Set
persistentVolumeClaimRetentionPolicy(whenDeleted/whenScaled: Delete) if you want them cleaned up.
Ordered start-up and scale-down
With the default OrderedReady policy, Pod n is only created when Pods 0..n-1 are Running and Ready, and scale-down removes the highest ordinal first. This lets db-0 bootstrap as the primary before the replicas join:
def scale(current, target):
steps = []
while current < target:
steps.append(f"create db-{current}, wait until Ready")
current += 1
while current > target:
current -= 1
steps.append(f"terminate db-{current}, wait until gone")
return steps
print("scale 0 -> 3:")
for s in scale(0, 3):
print(" " + s)
print("scale 3 -> 1:")
for s in scale(3, 1):
print(" " + s)scale 0 -> 3:
create db-0, wait until Ready
create db-1, wait until Ready
create db-2, wait until Ready
scale 3 -> 1:
terminate db-2, wait until gone
terminate db-1, wait until gone
podManagementPolicy: Parallel drops the ordering (faster) when the application handles its own membership.
Rolling updates and partitions
StatefulSets update Pods in reverse ordinal order, one at a time, waiting for each to be Ready. updateStrategy.rollingUpdate.partition: N only updates Pods with ordinal >= N, which gives you a canary: update db-2 first, check it, then lower the partition.
updateStrategy:
type: RollingUpdate
rollingUpdate:
partition: 2def rolling_update(replicas, partition, old="17.5", new="17.6"):
versions = {f"db-{i}": old for i in range(replicas)}
for i in reversed(range(replicas)):
if i >= partition:
versions[f"db-{i}"] = new
print(f"updated db-{i} -> {new}")
else:
print(f"kept db-{i} at {old} (below partition {partition})")
return versions
print(rolling_update(3, partition=2))
print(rolling_update(3, partition=0))updated db-2 -> 17.6
kept db-1 at 17.5 (below partition 2)
kept db-0 at 17.5 (below partition 2)
{'db-0': '17.5', 'db-1': '17.5', 'db-2': '17.6'}
updated db-2 -> 17.6
updated db-1 -> 17.6
updated db-0 -> 17.6
{'db-0': '17.6', 'db-1': '17.6', 'db-2': '17.6'}
When to use a StatefulSet (and when not)
- Use one for software that requires stable identity: PostgreSQL/MySQL replication, Kafka, ZooKeeper, Elasticsearch, etcd, Redis Cluster.
- A StatefulSet is only half the job: replication, failover and backups are the database's business. In production, prefer a database operator (CloudNativePG, Strimzi for Kafka, …) that manages the StatefulSet for you, or a managed cloud database.
- A single-instance app that just needs one disk is often fine as a Deployment with
replicas: 1,strategy: Recreateand a PVC.
kubectl get sts,pods,pvc -l app=db
kubectl scale sts db --replicas=5
kubectl exec -it db-0 -- psql -U postgres -c 'select 1'Test yourself
What will the replacement for a deleted StatefulSet Pod db-1 be called?
- A random name
- db-1
- db-3
- db-1-new
Which Service type gives StatefulSet Pods individual DNS names?
- NodePort
- LoadBalancer
- Headless (clusterIP: None)
- ExternalName
With partition: 2 and 3 replicas, which Pods get the new template?
- All
- db-0 only
- db-2 only
- db-0 and db-1