StatefulSets — Running Stateful Applications
A StatefulSet is the workload API object used to manage stateful applications. Unlike Deployments, StatefulSets provide guarantees about ordering and uniqueness of pods.
Use StatefulSets for applications that need stable network identities, persistent storage, or ordered deployment — like databases, message queues, and distributed systems.
StatefulSet vs Deployment
Deployment: StatefulSet:
┌──────────────────┐ ┌──────────────────┐
│ Pods are │ │ Pods are │
│ interchangeable │ │ uniquely named │
│ │ │ │
│ nginx-abc-123 │ │ web-0 │
│ nginx-def-456 │ │ web-1 │
│ nginx-ghi-789 │ │ web-2 │
│ │ │ │
│ No guaranteed │ │ Stable hostnames │
│ ordering │ │ Ordered startup │
│ Shared storage │ │ Per-pod storage │
└──────────────────┘ └──────────────────┘
Stable network identity — Each pod gets a predictable name (e.g., web-0, web-1) that does not change even if the pod is rescheduled.
Ordered deployment — Pods are created and deleted in strict order. web-0 must be Running before web-1 is created.
Stable storage — Each pod gets its own PersistentVolumeClaim that follows it wherever it goes.
Creating a StatefulSet
apiVersion: apps/v1
kind: StatefulSet
metadata:
name: web
spec:
serviceName: "nginx"
replicas: 3
selector:
matchLabels:
app: nginx
template:
metadata:
labels:
app: nginx
spec:
containers:
- name: nginx
image: nginx
ports:
- containerPort: 80
volumeMounts:
- name: www
mountPath: /usr/share/nginx/html
volumeClaimTemplates:
- metadata:
name: www
spec:
accessModes: ["ReadWriteOnce"]
resources:
requests:
storage: 1Gi
volumeClaimTemplates — Each pod automatically gets a PersistentVolumeClaim. The PVC follows the pod even if it is rescheduled to a different node.
Scaling StatefulSets
# Scale up
kubectl scale statefulset web --replicas=5
# Pods are created in order: web-3, then web-4
# Scale down
kubectl scale statefulset web --replicas=2
# Pods are deleted in reverse order: web-4, then web-3
Ordering matters. StatefulSets guarantee that web-0 is healthy before web-1 starts, and web-1 is deleted before web-0.