Difficulty: Intermediate
When would you use a Deployment versus a StatefulSet in Kubernetes, and what guarantees does a StatefulSet give that a Deployment does not?
Use a Deployment for stateless workloads where every replica is interchangeable, like REST APIs and web frontends. Use a StatefulSet when each replica needs a stable identity: a fixed name (db-0, db-1), a stable DNS hostname, and its own persistent volume that follows it across restarts, which is what databases, Kafka and ZooKeeper need.
A Deployment manages ReplicaSets, which manage Pods. Pods get random suffixes (api-7d9f8c-x2kqp), are created and deleted in any order, and if they use a PersistentVolumeClaim it is usually shared (or there is none at all). That is ideal for a payment API at a company like Razorpay: any Pod can serve any request, so you can scale from 3 to 30 replicas, roll out with RollingUpdate, and let a Service load-balance across them.
<name>-0 through <name>-(N-1). A replacement for mysql-1 is again called mysql-1.mysql-1.mysql.default.svc.cluster.local, so a replica can always find the primary at mysql-0.volumeClaimTemplates creates one PVC per Pod (data-mysql-0, data-mysql-1). When mysql-1 is rescheduled to another node, it reattaches the same PVC.podManagementPolicy: OrderedReady, Pods start one by one (0, then 1, then 2) and are removed in reverse. Rolling updates also go from the highest ordinal down. You can switch to Parallel when ordering is not needed.| Aspect | Deployment | StatefulSet |
|---|---|---|
| Pod names | Random hash suffix | Ordinal: app-0, app-1 |
| Storage | Shared PVC or none | One PVC per Pod via volumeClaimTemplates |
| Network identity | Through Service only | Stable per-Pod DNS via headless Service |
| Scaling order | Any order, in parallel | Ordered by default, reverse on scale down |
| Typical use | APIs, web apps, workers | Databases, Kafka, Elasticsearch, etcd |
persistentVolumeClaimRetentionPolicy.apiVersion: v1
kind: Service
metadata:
name: postgres
spec:
clusterIP: None # headless: gives each Pod its own DNS record
selector:
app: postgres
ports:
- port: 5432
---
apiVersion: apps/v1
kind: StatefulSet
metadata:
name: postgres
spec:
serviceName: postgres # must match the headless Service
replicas: 3
selector:
matchLabels:
app: postgres
template:
metadata:
labels:
app: postgres
spec:
containers:
- name: postgres
image: postgres:16
volumeMounts:
- name: data
mountPath: /var/lib/postgresql/data
volumeClaimTemplates: # one PVC per Pod: data-postgres-0, -1, -2
- metadata:
name: data
spec:
accessModes: ["ReadWriteOnce"]
resources:
requests:
storage: 20Gi
Each replica gets its own 20Gi volume and a DNS name like postgres-0.postgres. Replication between them is still the job of Postgres or an operator.
Deployment, StatefulSet, Stable Network Identity, volumeClaimTemplates, Ordered Rollout