☁️ Cloud

StatefulSet

A Kubernetes resource for stateful applications

📖 Detailed Explanation

StatefulSet is a Kubernetes workload resource for managing stateful applications. Unlike a Deployment, it provides each Pod with a unique network ID and stable persistent storage, and Pods are deployed and deleted in order.

StatefulSet vs Deployment:

  • Unique Pod names: myapp-0, myapp-1, myapp-2 (not random suffixes)
  • Headless Service: Provides a DNS entry for each Pod (myapp-0.myapp-svc)
  • Ordering guarantee: Created sequentially starting from 0, deleted in reverse order
  • PVC retention: PersistentVolumeClaims are retained when a Pod is deleted

Main use cases:

  • Databases: MySQL, PostgreSQL, MongoDB clusters
  • Message brokers: Kafka, RabbitMQ, ZooKeeper
  • Distributed caches: Redis Cluster, Memcached
  • Distributed storage: Elasticsearch, Cassandra

Pod management policy:

  • OrderedReady (default): Sequential creation/deletion; the next Pod is created after the previous Pod is Ready
  • Parallel: All Pods are created/deleted simultaneously (when order does not matter)

Update strategy: Provides the options RollingUpdate (rolling update in reverse order), OnDelete (update when manually deleted), and partition (update only Pods at or above a specific index).

💻 Code Example

PostgreSQL StatefulSet Example

# postgres-statefulset.yaml
apiVersion: v1
kind: Service
metadata:
  name: postgres-headless
  labels:
    app: postgres
spec:
  ports:
    - port: 5432
      name: postgres
  clusterIP: None  # Headless Service
  selector:
    app: postgres

---
apiVersion: apps/v1
kind: StatefulSet
metadata:
  name: postgres
spec:
  serviceName: postgres-headless  # Headless Service 연결
  replicas: 3
  selector:
    matchLabels:
      app: postgres
  template:
    metadata:
      labels:
        app: postgres
    spec:
      containers:
        - name: postgres
          image: postgres:15
          ports:
            - containerPort: 5432
              name: postgres
          env:
            - name: POSTGRES_PASSWORD
              valueFrom:
                secretKeyRef:
                  name: postgres-secret
                  key: password
            - name: PGDATA
              value: /var/lib/postgresql/data/pgdata
          volumeMounts:
            - name: postgres-data
              mountPath: /var/lib/postgresql/data
          resources:
            requests:
              memory: "256Mi"
              cpu: "250m"
            limits:
              memory: "512Mi"
              cpu: "500m"
          readinessProbe:
            exec:
              command: ["pg_isready", "-U", "postgres"]
            initialDelaySeconds: 5
            periodSeconds: 10

  # PersistentVolumeClaim 템플릿
  volumeClaimTemplates:
    - metadata:
        name: postgres-data
      spec:
        accessModes: ["ReadWriteOnce"]
        storageClassName: standard
        resources:
          requests:
            storage: 10Gi

  # 업데이트 전략
  updateStrategy:
    type: RollingUpdate
    rollingUpdate:
      partition: 0  # 모든 Pod 업데이트

  # Pod 관리 정책
  podManagementPolicy: OrderedReady

Pod DNS and Access

# StatefulSet Pod DNS 형식
# {pod-name}.{headless-service}.{namespace}.svc.cluster.local

# 예시: postgres StatefulSet (3 replicas)
# postgres-0.postgres-headless.default.svc.cluster.local
# postgres-1.postgres-headless.default.svc.cluster.local
# postgres-2.postgres-headless.default.svc.cluster.local

# 같은 네임스페이스에서 접근
psql -h postgres-0.postgres-headless -U postgres

# 애플리케이션 연결 문자열 (Primary)
postgresql://postgres:password@postgres-0.postgres-headless:5432/mydb

# kubectl로 상태 확인
kubectl get statefulset postgres
# NAME       READY   AGE
# postgres   3/3     10m

kubectl get pods -l app=postgres
# NAME         READY   STATUS    RESTARTS   AGE
# postgres-0   1/1     Running   0          10m
# postgres-1   1/1     Running   0          9m
# postgres-2   1/1     Running   0          8m

# PVC 확인 (Pod별 별도 PVC)
kubectl get pvc
# NAME                    STATUS   VOLUME    CAPACITY   ACCESS MODES
# postgres-data-postgres-0   Bound   pvc-xxx   10Gi       RWO
# postgres-data-postgres-1   Bound   pvc-yyy   10Gi       RWO
# postgres-data-postgres-2   Bound   pvc-zzz   10Gi       RWO

Canary Update (partition)

# partition을 사용한 단계적 롤아웃
# partition=2면 인덱스 2 이상 Pod만 업데이트 (postgres-2만)

# 1. partition 설정으로 일부만 업데이트
kubectl patch statefulset postgres -p \
  '{"spec":{"updateStrategy":{"type":"RollingUpdate","rollingUpdate":{"partition":2}}}}'

# 2. 이미지 업데이트 (postgres-2만 업데이트됨)
kubectl set image statefulset/postgres postgres=postgres:16

# 3. postgres-2 테스트 후 partition 낮추기
kubectl patch statefulset postgres -p \
  '{"spec":{"updateStrategy":{"rollingUpdate":{"partition":1}}}}'
# postgres-1, postgres-2 업데이트됨

# 4. 전체 롤아웃
kubectl patch statefulset postgres -p \
  '{"spec":{"updateStrategy":{"rollingUpdate":{"partition":0}}}}'
# postgres-0, postgres-1, postgres-2 모두 업데이트됨

🗣️ Examples of Practical Conversations

Architecture Design

Developer: "I want to run a DB on Kubernetes. Can I just use a Deployment?"

Senior: "You should use a StatefulSet for a DB. With a Deployment, Pod names are random, and PVCs are hard to manage once Pods are deleted. A StatefulSet has fixed names like postgres-0, postgres-1, and each Pod keeps its own dedicated PVC."

Developer: "What about a master-slave setup?"

Senior: "Pin postgres-0 as the master, and set postgres-1 and postgres-2 as slaves. Thanks to the Headless Service, you can reach each Pod directly via DNS, so separating roles is easy."

Technical Interview

Interviewer: "Please explain the difference between a StatefulSet and a Deployment."

Candidate: "There are three main differences. First, Pod names are fixed. A Deployment appends a random hash, but a StatefulSet uses sequential indexes like 0, 1, 2. Second, together with a Headless Service, each Pod is given its own unique DNS name. Third, a PVC is mapped 1:1 to a Pod, so even if the Pod restarts, it uses the same volume."

Interviewer: "When should you use a StatefulSet?"

Candidate: "When each instance has a unique ID and needs persistent storage, like databases, Kafka, and ZooKeeper. On the other hand, stateless apps like web servers are better suited to a Deployment."

Troubleshooting

Operations team: "I can't scale out the StatefulSet. The Pods are stuck in Pending."

Developer: "It's most likely a PVC provisioning problem. Check whether the StorageClass is configured correctly and whether there is enough storage capacity. If you check the events with kubectl describe pvc, you should find the cause."

Operations team: "I deleted the Pod, but the PVC is still there."

Developer: "A StatefulSet intentionally does not delete PVCs. It's to preserve data. If you really want to delete it, you have to manually run kubectl delete pvc."

Take a mock interview on this topic → WIA SOOM AI Interview · Start for free

⚠️ Cautions

🔗 Related Terms

Deployment PersistentVolume Headless Service VPA Operator

📚 Learn More