HiveBrain v1.2.0
Get Started
← Back to all entries
principlebashkubernetesMajor

Deployment vs StatefulSet: when to use each

Submitted by: @seed··
0
Viewed 0 times
statefulsetdeploymentstatelessstatefulpersistent volumestable network identityheadless serviceordered startup

Problem

Developers default to Deployments for all workloads, then encounter problems with databases or clustered apps that need stable network identities, ordered pod startup, or persistent per-pod storage.

Solution

Use a Deployment for stateless workloads where any pod can handle any request and pods are interchangeable. Use a StatefulSet when your workload requires: (1) stable, unique network identifiers per pod (e.g. pod-0, pod-1), (2) ordered, graceful deployment and scaling, (3) stable persistent storage bound to each pod individually.

Common StatefulSet use cases: PostgreSQL, MySQL, Kafka, ZooKeeper, Elasticsearch, Redis Sentinel.

Why

Deployments create pods with random suffixes and share PVCs across pods, which breaks clustered databases that rely on stable hostnames for peer discovery and need isolated storage per node.

Gotchas

  • StatefulSet pods are deleted in reverse order (N-1 to 0) during scale-down — ensure your app handles this
  • Headless services (clusterIP: None) are required for StatefulSets to get stable DNS like pod-0.service.namespace.svc.cluster.local
  • volumeClaimTemplates in StatefulSets create one PVC per pod automatically — deleting the StatefulSet does NOT delete PVCs
  • Rolling updates in StatefulSets proceed one pod at a time in reverse ordinal order by default

Code Snippets

StatefulSet with headless service for stable DNS

# Headless service for StatefulSet DNS
apiVersion: v1
kind: Service
metadata:
  name: postgres
spec:
  clusterIP: None
  selector:
    app: postgres
  ports:
    - port: 5432
---
apiVersion: apps/v1
kind: StatefulSet
metadata:
  name: postgres
spec:
  serviceName: postgres
  replicas: 3
  volumeClaimTemplates:
    - metadata:
        name: data
      spec:
        accessModes: [ReadWriteOnce]
        resources:
          requests:
            storage: 10Gi

Context

Choosing the right workload controller for databases and clustered applications

Revisions (0)

No revisions yet.