StatefulSets
notes-web copies are interchangeable: any pod can serve any request. The database is different. Each database pod has its own data on its own disk, and a replacement must come back with the same name and the same disk. That is what a StatefulSet promises.
The rule
A StatefulSet gives each pod a fixed name, a fixed disk and a turn in line.
Compared with a Deployment, a StatefulSet adds three guarantees:
- Stable names: pods are
notes-db-0,notes-db-1,notes-db-2, not random suffixes. A replacednotes-db-1is stillnotes-db-1. - Stable storage:
volumeClaimTemplatescreate one PersistentVolumeClaim per pod (data-notes-db-0, …). A replaced pod reattaches to its own claim. - Ordered steps: by default pods start in order 0, 1, 2 — each waits for the one before to be ready — and are removed in reverse.
It also needs a headless Service (one with clusterIP: None), named in serviceName, which gives each pod its own DNS name such as notes-db-0.notes-db.notes.svc.cluster.local.
apiVersion: apps/v1
kind: StatefulSet
metadata:
name: notes-db
namespace: notes
spec:
serviceName: notes-db
replicas: 1
selector:
matchLabels:
app: notes-db
template:
metadata:
labels:
app: notes-db
spec:
containers:
- name: postgres
image: postgres:16
volumeMounts:
- name: data
mountPath: /var/lib/postgresql/data
volumeClaimTemplates:
- metadata:
name: data
spec:
accessModes: ["ReadWriteOnce"]
resources:
requests:
storage: 5GiA StatefulSet does not make a database replicate or fail over. It only gives each pod a stable identity; the database software must do the rest.
The shortcut
Ask: "If this pod died, must its replacement be the same one?" Same name and same data needed → StatefulSet. Any copy will do → Deployment.
Replacement
The StatefulSet recreates a pod named exactly
notes-db-0.
The trap: deleting a StatefulSet (or scaling it down) does not delete its claims by default. That protects data — and leaves storage you may still be paying for.
Drills
Answer fast — trust the rule.
A StatefulSet named notes-db has 3 replicas. What are the pod names?
Which field gives each StatefulSet pod its own persistent disk?
Which workload fits a Deployment rather than a StatefulSet?
You scale notes-db from 3 to 1. What happens to data-notes-db-2?
Remember
- A StatefulSet gives each pod a fixed name, a fixed disk and a turn in line.
- Must the replacement be the same one? StatefulSet. Any copy? Deployment.
- Trap: claims outlive the pods; clean them up on purpose.
