StatefulSets

A StatefulSet is a Kubernetes controller for running stateful apps—apps that need each Pod to keep its identity and storage, even if rescheduled. Think databases, message queues, or anything that can't just be replaced with a blank copy.


Why Use a StatefulSet?

Use a StatefulSet when your app needs:

  • Stable network identity (like pod-0, pod-1)
  • Persistent storage per Pod that sticks around if the Pod is rescheduled
  • Ordered startup, scaling, and deletion

Examples: Databases (PostgreSQL, Cassandra), Zookeeper, Kafka, etc.


How It Differs from Deployments

StatefulSets guarantee identity and storage for each Pod, while Deployments just care about keeping the right number of Pods running (not which is which).

StatefulSets Diagram StatefulSets Diagram

Top Half (Deployment): Pod reschedule = new IP, broken volume mount
Bottom Half (StatefulSet): Pod is recreated with the same IP, same volume


Key Features

Feature Deployment StatefulSet
Pod name Random (e.g., pod-abc123) Stable (e.g., web-0, web-1)
Pod start/delete order Any Ordered
Persistent VolumeClaim Shared/ephemeral One per Pod
DNS hostname Random Stable via headless service

Sample YAML

apiVersion: apps/v1
kind: StatefulSet
metadata:
  name: web
spec:
  serviceName: "web"  # Headless service
  replicas: 2
  selector:
    matchLabels:
      app: web
  template:
    metadata:
      labels:
        app: web
    spec:
      containers:
        - name: nginx
          image: nginx
          volumeMounts:
            - name: data
              mountPath: /usr/share/nginx/html
      tolerations:
      - key: "node-role.kubernetes.io/master"
        operator: "Exists"
        effect: "NoSchedule"
  volumeClaimTemplates:
    - metadata:
        name: data
      spec:
        accessModes: ["ReadWriteOnce"]
        resources:
          requests:
            storage: 1Gi

Networking & DNS

Pods in a StatefulSet get predictable hostnames:

web-0.web.default.svc.cluster.local
web-1.web.default.svc.cluster.local

This is enabled by the headless Service:

apiVersion: v1
kind: Service
metadata:
  name: web
spec:
  clusterIP: None  # Headless
  selector:
    app: web
  ports:
    - port: 80

Volume Behavior

Each Pod gets its own PVC:

  • web-0data-web-0
  • web-1data-web-1

These volumes are retained even if the Pod is deleted.


Summary

  • StatefulSets are for apps that need stable identity and storage.
  • Use them for databases, queues, and apps that can't just be replaced with a blank Pod.
  • Deployments are for stateless, replaceable workloads.

Tip

Only use StatefulSets when you really need sticky identity or storage. For most apps, Deployments are simpler and easier to manage.