On this page
StatefulSet Patterns for Databases on Kubernetes
A StatefulSet is Kubernetes's answer to "I need my pods to have stable identities." Unlike a Deployment, where pods are interchangeable replicas named app-7d4f9b-xkz2p, a StatefulSet gives each pod a permanent ordinal name (kafka-0, kafka-1, kafka-2) that survives restarts, and binds each pod to its own PVC for the life of the StatefulSet. These three guarantees — stable name, stable DNS, stable storage — are what make databases work on Kubernetes.
The Three Guarantees
graph TD
subgraph STS["StatefulSet: mydb (replicas: 3)"]
P0["mydb-0<br/>pod name: stable"]
P1["mydb-1<br/>pod name: stable"]
P2["mydb-2<br/>pod name: stable"]
end
subgraph HS["Headless Service: mydb"]
D0["mydb-0.mydb.ns.svc.cluster.local"]
D1["mydb-1.mydb.ns.svc.cluster.local"]
D2["mydb-2.mydb.ns.svc.cluster.local"]
end
subgraph PVC["PersistentVolumeClaims"]
V0["data-mydb-0<br/>500Gi SSD"]
V1["data-mydb-1<br/>500Gi SSD"]
V2["data-mydb-2<br/>500Gi SSD"]
end
P0 -->|"stable DNS"| D0
P1 -->|"stable DNS"| D1
P2 -->|"stable DNS"| D2
P0 -->|"reattaches on restart"| V0
P1 -->|"reattaches on restart"| V1
P2 -->|"reattaches on restart"| V2
When mydb-1's pod dies — node failure, OOMKill, rolling update — Kubernetes creates a new pod named exactly mydb-1, schedules it to a node that can mount data-mydb-1, and the database restarts with its data intact. No other workload type provides all three guarantees together.
Headless Service
The clusterIP: None annotation makes Kubernetes create individual A records for each pod instead of a single round-robin VIP:
apiVersion: v1
kind: Service
metadata:
name: mydb
namespace: default
spec:
clusterIP: None # This is the headless flag
selector:
app: mydb
ports:
- name: db
port: 5432
targetPort: 5432
With this service, the DNS lookup for mydb.default.svc.cluster.local returns all pod IPs (A records), and mydb-2.mydb.default.svc.cluster.local resolves to that specific pod's IP. This is how databases do seed discovery:
| Database | Headless DNS usage |
|---|---|
| MongoDB | rs.initiate({ members: [{_id:0,host:"mongo-0.mongo:27017"},...] }) |
| Cassandra | seeds: "cassandra-0.cassandra,cassandra-1.cassandra" in cassandra.yaml |
| Kafka | zookeeper.connect=zk-0.zk:2181,zk-1.zk:2181,zk-2.zk:2181 |
| etcd | --initial-cluster=etcd-0=http://etcd-0.etcd:2380,... |
A regular ClusterIP service routes requests to any pod — useless for reaching a specific replica. Use a separate ClusterIP service for client read traffic, and the headless service for intra-cluster peer communication.
Your MongoDB init script needs to connect to mongo-0 specifically (to run rs.initiate()). You have both a headless service "mongo" and a ClusterIP service "mongo-svc". Which hostname do you use?
mongo-0.mongo.<namespace>.svc.cluster.local. The headless service creates per-pod DNS records. The ClusterIP service routes to a random ready pod — which might not be mongo-0 — and you'd fail to run rs.initiate() on a non-primary.PVC Lifecycle
volumeClaimTemplates in the StatefulSet spec creates one PVC per pod per template, named <template-name>-<pod-name>:
spec:
volumeClaimTemplates:
- metadata:
name: data
spec:
accessModes: ["ReadWriteOnce"]
storageClassName: premium-ssd
resources:
requests:
storage: 500Gi
This creates data-mydb-0, data-mydb-1, data-mydb-2. PVCs are not deleted when the pod is deleted. The pod can be evicted, crash-looped, or replaced — the PVC stays. When the new pod starts, Kubernetes binds the same PVC back. This is the behavior you want for databases.
Retention policy (Kubernetes 1.27+): control what happens to PVCs when the StatefulSet itself is deleted or scaled down:
spec:
persistentVolumeClaimRetentionPolicy:
whenDeleted: Retain # PVCs survive StatefulSet deletion (default)
whenScaled: Delete # PVCs for removed replicas are deleted on scale-down
Use whenScaled: Retain (the other default) when you want to manually inspect data before deletion. Use whenScaled: Delete when scaling-down a Kafka cluster — you've already rebalanced partitions off the broker, so the PVC is safe to remove.
Expanding a PVC: increase storage in volumeClaimTemplates does NOT resize existing PVCs (the template is immutable for existing pods). To expand:
# Resize each PVC individually (StorageClass must have allowVolumeExpansion: true)
kubectl patch pvc data-mydb-0 -p '{"spec":{"resources":{"requests":{"storage":"1Ti"}}}}'
kubectl patch pvc data-mydb-1 -p '{"spec":{"resources":{"requests":{"storage":"1Ti"}}}}'
kubectl patch pvc data-mydb-2 -p '{"spec":{"resources":{"requests":{"storage":"1Ti"}}}}'
# Restart each pod to trigger filesystem resize (if not auto-triggered)
kubectl rollout restart statefulset/mydb
Init Containers for Bootstrap
Init containers solve the "I need to know who I am before I can start" problem that databases face:
Pattern 1 — Cassandra seed wait: Poll DNS until seed nodes are resolvable before starting the main container:
initContainers:
- name: wait-for-seeds
image: busybox:1.36
command:
- sh
- -c
- |
until nslookup cassandra-0.cassandra.$(cat /var/run/secrets/kubernetes.io/serviceaccount/namespace).svc.cluster.local; do
echo "waiting for cassandra-0..."; sleep 2
done
Pattern 2 — etcd cluster join: Generate the --initial-cluster flag dynamically from DNS:
initContainers:
- name: gen-etcd-config
image: busybox:1.36
command:
- sh
- -c
- |
PEERS=""
for i in 0 1 2; do
PEERS="${PEERS}${PEERS:+,}etcd-${i}=http://etcd-${i}.etcd:2380"
done
echo "--initial-cluster=${PEERS}" > /config/peers.txt
volumeMounts:
- name: config
mountPath: /config
Pattern 3 — MongoDB keyfile: Generate a shared authentication secret from a K8s Secret:
initContainers:
- name: copy-keyfile
image: busybox:1.36
command: ["sh", "-c", "cp /secret/keyfile /data/keyfile && chmod 400 /data/keyfile && chown 999:999 /data/keyfile"]
volumeMounts:
- name: keyfile-secret
mountPath: /secret
readOnly: true
- name: data
mountPath: /data
PodDisruptionBudget
PDBs prevent node drains from disrupting quorum. For a 3-node database cluster:
apiVersion: policy/v1
kind: PodDisruptionBudget
metadata:
name: mydb-pdb
spec:
maxUnavailable: 1
selector:
matchLabels:
app: mydb
maxUnavailable: 1: At most 1 pod can be unavailable at a time. A kubectl drain on a node will block until the evicted pod is rescheduled and healthy before evicting the next.
maxUnavailable: 0: Blocks all voluntary disruptions. No drain can proceed. Use only if you're doing manual quorum management and want to explicitly release the PDB before each step.
minAvailable: 2 (equivalent to maxUnavailable: 1 for 3 replicas): Sometimes clearer — "I always need 2 members available." Preferred over maxUnavailable when replica count changes, because minAvailable: 2 stays correct while maxUnavailable: 1 would need re-evaluation.
PDBs only block voluntary disruptions (drains, maintenance). A node crashing takes the pod without asking Kubernetes permission.
Graceful Shutdown
The default SIGTERM-to-kill sequence is too fast for databases. Tune it:
spec:
template:
spec:
terminationGracePeriodSeconds: 120 # Give 2 minutes before SIGKILL
containers:
- name: kafka
lifecycle:
preStop:
exec:
command:
- sh
- -c
- |
# Hand off partition leadership before SIGTERM
/opt/kafka/bin/kafka-leader-election.sh \
--bootstrap-server localhost:9092 \
--election-type PREFERRED \
--all-topic-partitions
sleep 10 # Let the controller process the election
How it works: Kubernetes sends preStop, waits for it to complete, then sends SIGTERM. After terminationGracePeriodSeconds from the start of preStop, it sends SIGKILL regardless.
podManagementPolicy: Controls pod start/stop ordering during scale operations:
spec:
podManagementPolicy: OrderedReady # default: 0 before 1 before 2
# or
podManagementPolicy: Parallel # all pods start/stop simultaneously
Use OrderedReady for databases (default) — ordinal-0 must be Running before ordinal-1 starts. This lets ordinal-0 bootstrap the cluster (MongoDB primary, etcd leader) before peers join. Use Parallel for stateless workloads that happen to be in a StatefulSet.
Scaling StatefulSets
Scale up: New pods get the next ordinal. kafka-3 is added after kafka-2. The new pod mounts a new PVC (data-kafka-3) and joins the cluster.
kubectl scale statefulset kafka --replicas=4
# kafka-3 starts, gets a fresh PVC, connects to ZooKeeper/KRaft and joins as a broker
Scale down: Pods are removed highest-ordinal-first. kafka-3 is removed before kafka-2. You must rebalance data first — Kafka does not automatically move partitions off a broker being removed:
# 1. Reassign partitions off kafka-3 before scaling down
kafka-reassign-partitions.sh --bootstrap-server kafka-0.kafka:9092 \
--reassignment-json-file remove-broker-3.json --execute
# 2. Wait for reassignment to complete
kafka-reassign-partitions.sh --bootstrap-server kafka-0.kafka:9092 \
--reassignment-json-file remove-broker-3.json --verify
# 3. Only now safe to scale down
kubectl scale statefulset kafka --replicas=3
For databases with automatic rebalancing (Elasticsearch, MongoDB), scale down triggers cluster-level rebalancing automatically — but still wait for it to complete before going further.
Anti-Affinity for High Availability
Without anti-affinity, the scheduler might place all 3 replicas on the same node — a single node failure takes down the entire cluster:
spec:
template:
spec:
affinity:
podAntiAffinity:
# Hard: refuse to schedule if this node already has a mydb pod
requiredDuringSchedulingIgnoredDuringExecution:
- labelSelector:
matchLabels:
app: mydb
topologyKey: kubernetes.io/hostname
# Soft: prefer different availability zones (if hard constraint met)
preferredDuringSchedulingIgnoredDuringExecution:
- weight: 100
podAffinityTerm:
labelSelector:
matchLabels:
app: mydb
topologyKey: topology.kubernetes.io/zone
Hard vs Soft anti-affinity tradeoff:
requiredDuring...(hard): a pod staysPendingforever if no eligible node exists. In a 3-node cluster trying to place 3 replicas with this rule, if you only have 2 nodes, the 3rd pod is permanentlyPending. Use when you absolutely cannot tolerate two replicas on the same node.preferredDuring...(soft): the scheduler tries to spread but will co-locate if necessary. Safer for small clusters, but means HA is best-effort.
StatefulSet vs Deployment vs DaemonSet
Use for: Databases, message brokers, distributed coordination systems — anything that needs stable identity or persistent per-instance storage.
Pod naming: mydb-0, mydb-1, mydb-2 — stable ordinal identity.
Storage: volumeClaimTemplates — one PVC per pod, survives pod deletion.
Scale order: 0 → 1 → 2 on up; 2 → 1 → 0 on down (with OrderedReady).
Rolling update: Reverse ordinal order, one pod at a time, waits for ready.
Examples: PostgreSQL, MongoDB, Kafka, Elasticsearch, etcd, Redis Cluster, ZooKeeper.
Use for: Stateless services — web servers, API servers, workers, microservices.
Pod naming: app-7d4f9b-xkz2p — random hash suffix, no identity.
Storage: Shared volumes only (ReadWriteMany), or no persistent storage. All pods share the same PVC — unsuitable for databases.
Scale order: Any order; all new pods start simultaneously.
Rolling update: New ReplicaSet created; pods replaced in batches.
Examples: nginx, REST APIs, gRPC services, batch workers, Prometheus.
Use for: Node-level agents that must run on every (or specific) node.
Pod naming: fluentbit-node1 — one pod per node, tied to that node.
Storage: Typically hostPath mounts to read node-level files (logs, /proc, /sys).
Scale: Automatically matches node count; no manual replica count.
Examples: Fluent Bit, Prometheus node-exporter, Calico, Cilium, Falco agent.
Rewriting volumeClaimTemplates (StatefulSet Recreation)
volumeClaimTemplates is immutable — you cannot change storage size, storage class, or access mode via kubectl edit or kubectl apply. Changing these requires recreating the StatefulSet. The safe procedure preserves the existing PVCs:
kubectl get sts mydb -o yaml > mydb-sts.yaml. Edit the volumeClaimTemplates section in the file to reflect the new spec (e.g., larger storage, different storageClassName).
kubectl delete sts mydb --cascade=orphan. The --cascade=orphan flag removes the StatefulSet controller object but leaves all pods and PVCs running. Clients can continue to connect.
For each PVC: kubectl patch pvc data-mydb-0 -p '{"spec":{"resources":{"requests":{"storage":"1Ti"}}}}'. Wait for the FileSystemResizePending condition to clear on each PVC (happens when the pod using it restarts).
kubectl apply -f mydb-sts.yaml. The new StatefulSet adopts the orphaned pods — no pod restarts occur at this step. The volumeClaimTemplates in the new manifest must match the existing PVC specs exactly (the already-patched size).
kubectl rollout restart statefulset/mydb. Each pod restart triggers the OS-level filesystem resize to fill the expanded PVC. Monitor: kubectl rollout status statefulset/mydb.
You delete a StatefulSet with kubectl delete sts mydb (no flags). What happens to the pods and PVCs?
--cascade=orphan only when you want the pods to keep running during the StatefulSet transition.A PodDisruptionBudget with maxUnavailable: 0 is set on your 3-node database. An SRE tries to drain a node with kubectl drain. What happens?
maxUnavailable: 0 means zero pods can be voluntarily evicted — the PDB refuses all drain requests. To proceed, the SRE must either temporarily delete the PDB (kubectl delete pdb mydb-pdb), change it to maxUnavailable: 1, or use kubectl drain --disable-eviction (bypasses PDB, use only in emergencies).