Skip to main content

Running StatefulSets for Databases on Kubernetes

Deploy and manage stateful database workloads on Kubernetes using StatefulSets with stable network identities, ordered scaling, and persistent storage.

52 Terms

Overview and What You Will Learn

A StatefulSet runs pods that need a stable identity: each pod gets a fixed name, its own DNS record, its own persistent volume, and ordered startup and shutdown. A Deployment treats pods as interchangeable, which suits stateless APIs but breaks databases where identity, order and storage matter. In this lab you will run a single PostgreSQL instance, then a three-pod Redis primary with replicas, and practice ordered startup, a canary rolling update, scaling and troubleshooting. It assumes the StorageClass gp3-encrypted from the Persistent Volumes topic, so use your own class name if you do not have it.

  • Choosing between a Deployment and a StatefulSet
  • Creating the headless Service that gives each pod a stable DNS name
  • Running PostgreSQL with a volume per pod
  • Building primary and replica roles from the pod's ordinal
  • Rolling out updates in stages with partition
  • Scaling safely and handling the PVCs that remain
  • Troubleshooting stuck pods and volumes

Why This Matters in Production

Databases fail in unpleasant ways when their identity or storage is not stable. Imagine a platform team at a company like Zerodha running Redis for session data. If replicas start before the primary exists, or the application finds nodes by pod IP, every restart becomes an incident. With a StatefulSet, each pod keeps a name such as redis-0 and a DNS record that never changes, replicas start only after the primary is Ready, and each pod reattaches to its own volume after a restart.

Core Principles

A StatefulSet gives every pod an ordinal number and ties three things to it: the pod name, the DNS name and the volume.

Feature Deployment StatefulSet
Pod names Random suffix, such as api-7d9f8b-xkp2q Stable ordinal, such as redis-0
Identity Interchangeable Unique and stable
Storage Shared or none One PVC per pod from volumeClaimTemplates
Startup order All pods start together redis-0 must be Ready before redis-1 starts
Termination All pods stop together Reverse order, highest ordinal first
DNS One Service IP Per-pod DNS through a headless Service
flowchart TD SS[StatefulSet redis]:::tool --> P0[redis-0]:::soft SS --> P1[redis-1]:::soft SS --> P2[redis-2]:::soft P0 --> V0[(PVC redis-data-redis-0)]:::slate P1 --> V1[(PVC redis-data-redis-1)]:::slate P2 --> V2[(PVC redis-data-redis-2)]:::slate classDef tool fill:#326CE5,color:#FFFFFF classDef soft fill:#DBEAFE,color:#1E293B classDef slate fill:#475569,color:#FFFFFF

Choose a StatefulSet for databases such as PostgreSQL and MySQL, message brokers such as Kafka and RabbitMQ, search engines such as Elasticsearch, and anything that needs stable pod DNS or a volume per replica. Choose a Deployment for REST APIs, web servers, stateless workers and anything with no local state.

Two limits matter before you start. A StatefulSet gives you identity and storage, but it does not configure replication, elect a primary or fail over, so a database still needs its own replication setup. And scaling PostgreSQL from one pod to three creates three separate, empty databases, not a replica set. For production PostgreSQL high availability, use an operator such as CloudNativePG, the Zalando Postgres Operator or Crunchy Postgres, which manage replication, failover and backups on top of StatefulSet-style pods.

Detailed Step-by-Step Practical Lab

Step 1 - Create the Namespace, Secret and Headless Service

A headless Service has clusterIP: None. Instead of one load-balanced IP, it creates a DNS record for every pod, such as postgres-0.postgres.statefulset-lab.svc.cluster.local. Its name must match the StatefulSet's serviceName, and a mismatch is the most common StatefulSet setup mistake:

Bash
kubectl create namespace statefulset-lab
read -s -p "Postgres password: " PGPASS
kubectl create secret generic postgres-credentials -n statefulset-lab \
--from-literal=username=rahul \
--from-literal=password="$PGPASS"
YAML
apiVersion: v1
kind: Service
metadata:
name: postgres
namespace: statefulset-lab
labels:
app: postgres
spec:
clusterIP: None
selector:
app: postgres
ports:
- name: postgres
port: 5432
targetPort: 5432
Bash
kubectl apply -f postgres-headless-service.yaml
Step 2 - Run a Single PostgreSQL Instance

The pod-level fsGroup makes the mounted volume writable by the postgres group, so no root init container is needed. Setting PGDATA to a subdirectory avoids the lost+found directory at the root of a new volume:

YAML
# postgres-statefulset.yaml
apiVersion: apps/v1
kind: StatefulSet
metadata:
name: postgres
namespace: statefulset-lab
spec:
serviceName: postgres
replicas: 1
selector:
matchLabels:
app: postgres
template:
metadata:
labels:
app: postgres
spec:
terminationGracePeriodSeconds: 60
securityContext:
fsGroup: 999
fsGroupChangePolicy: OnRootMismatch
containers:
- name: postgres
image: postgres:16
ports:
- name: postgres
containerPort: 5432
env:
- name: POSTGRES_DB
value: trading
- name: POSTGRES_USER
valueFrom:
secretKeyRef:
name: postgres-credentials
key: username
- name: POSTGRES_PASSWORD
valueFrom:
secretKeyRef:
name: postgres-credentials
key: password
- name: PGDATA
value: /var/lib/postgresql/data/pgdata
- name: POSTGRES_INITDB_ARGS
value: "--encoding=UTF8 --auth-host=scram-sha-256"
resources:
requests:
cpu: 500m
memory: 1Gi
limits:
memory: 2Gi
livenessProbe:
exec:
command:
- pg_isready
- -U
- $(POSTGRES_USER)
- -d
- $(POSTGRES_DB)
initialDelaySeconds: 30
periodSeconds: 10
failureThreshold: 6
readinessProbe:
exec:
command:
- pg_isready
- -U
- $(POSTGRES_USER)
- -d
- $(POSTGRES_DB)
initialDelaySeconds: 5
periodSeconds: 5
failureThreshold: 3
volumeMounts:
- name: postgres-data
mountPath: /var/lib/postgresql/data
volumeClaimTemplates:
- metadata:
name: postgres-data
spec:
accessModes:
- ReadWriteOnce
storageClassName: gp3-encrypted
resources:
requests:
storage: 20Gi
Bash
kubectl apply -f postgres-statefulset.yaml
kubectl get pods -n statefulset-lab -w
# The PVC name is the template name plus the pod name
kubectl get pvc -n statefulset-lab
# postgres-data-postgres-0 Bound ... 20Gi
# Confirm the stable DNS name resolves from another pod
kubectl run dns-test --rm -it --restart=Never --image=busybox:1.36 \
-n statefulset-lab -- nslookup postgres-0.postgres

Connect applications to postgres-0.postgres, never to a pod IP, because the IP changes on every restart and the name does not.

Step 3 - Build a Redis Primary with Replicas

Three Redis pods from one StatefulSet are three independent servers until you configure replication. This start script reads the ordinal from the hostname: pod 0 becomes the primary and every other pod replicates from redis-0. It works because ordered startup guarantees redis-0 is Ready, and its DNS record exists, before redis-1 starts:

YAML
# redis-config.yaml
apiVersion: v1
kind: ConfigMap
metadata:
name: redis-config
namespace: statefulset-lab
data:
redis.conf: |
dir /data
appendonly yes
appendfsync everysec
maxmemory 1gb
maxmemory-policy noeviction
save 900 1
save 300 10
save 60 10000
start.sh: |
#!/bin/sh
ORDINAL=${HOSTNAME##*-}
if [ "$ORDINAL" = "0" ]; then
exec redis-server /etc/redis/redis.conf
else
exec redis-server /etc/redis/redis.conf --replicaof redis-0.redis 6379
fi
YAML
# redis-headless-service.yaml
apiVersion: v1
kind: Service
metadata:
name: redis
namespace: statefulset-lab
labels:
app: redis
spec:
clusterIP: None
selector:
app: redis
ports:
- name: redis
port: 6379
YAML
# redis-statefulset.yaml
apiVersion: apps/v1
kind: StatefulSet
metadata:
name: redis
namespace: statefulset-lab
spec:
serviceName: redis
replicas: 3
selector:
matchLabels:
app: redis
template:
metadata:
labels:
app: redis
spec:
terminationGracePeriodSeconds: 30
securityContext:
fsGroup: 999
containers:
- name: redis
image: redis:7.2
command:
- sh
- /etc/redis/start.sh
ports:
- name: redis
containerPort: 6379
resources:
requests:
cpu: 250m
memory: 1Gi
limits:
memory: 1536Mi
livenessProbe:
exec:
command:
- redis-cli
- ping
initialDelaySeconds: 15
periodSeconds: 10
readinessProbe:
exec:
command:
- redis-cli
- ping
initialDelaySeconds: 5
periodSeconds: 5
volumeMounts:
- name: redis-data
mountPath: /data
- name: redis-config
mountPath: /etc/redis
volumes:
- name: redis-config
configMap:
name: redis-config
volumeClaimTemplates:
- metadata:
name: redis-data
spec:
accessModes:
- ReadWriteOnce
storageClassName: gp3-encrypted
resources:
requests:
storage: 10Gi
Bash
kubectl apply -f redis-config.yaml -f redis-headless-service.yaml -f redis-statefulset.yaml
kubectl get pods -n statefulset-lab -w
# redis-0 becomes Ready first, then redis-1, then redis-2

The maxmemory of 1 GiB leaves headroom under the 1.5 GiB container limit, so Redis evicts or rejects writes before the kernel kills the container. This setup uses noeviction, which suits a data store. For a pure cache, use allkeys-lru.

Step 4 - Verify Order, Roles and Stable Names
Bash
kubectl exec -n statefulset-lab redis-0 -- redis-cli info replication
# role:master
# connected_slaves:2
kubectl exec -n statefulset-lab redis-1 -- redis-cli info replication
# role:slave
# master_host:redis-0.redis
# Write on the primary, read from a replica
kubectl exec -n statefulset-lab redis-0 -- redis-cli set order:ORD-48214 confirmed
kubectl exec -n statefulset-lab redis-2 -- redis-cli get order:ORD-48214
# confirmed

Applications reach each node at redis-0.redis.statefulset-lab.svc.cluster.local:6379, and the names survive pod restarts. This setup has no automatic failover. If redis-0 dies, nothing promotes a replica, so use Redis Sentinel or a Redis operator for that.

Step 5 - Roll Out an Update in Stages

By default a StatefulSet updates pods in reverse ordinal order, so redis-2 goes first and the primary redis-0 goes last. The partition setting limits the update to pods whose ordinal is equal to or higher than the number, which lets you canary one pod and check it before continuing:

YAML
# partition-2.yaml
spec:
updateStrategy:
type: RollingUpdate
rollingUpdate:
partition: 2
Bash
kubectl patch statefulset redis -n statefulset-lab --patch-file partition-2.yaml
kubectl set image statefulset/redis redis=redis:7.4 -n statefulset-lab
kubectl get pods -n statefulset-lab -l app=redis \
-o custom-columns=NAME:.metadata.name,IMAGE:.spec.containers[0].image
# Only redis-2 runs redis:7.4
# Check replication on redis-2, then lower the partition to continue
kubectl exec -n statefulset-lab redis-2 -- redis-cli info replication

Lower partition to 1 and then to 0 by changing partition-2.yaml and patching again. To roll back, run kubectl rollout undo statefulset/redis. If a bad update leaves a pod crashing, a StatefulSet does not repair it automatically, so you may need to delete that pod after fixing the template.

Step 6 - Scale and Handle Leftover PVCs

New pods start in order, and the start script makes each one a replica automatically:

Bash
kubectl scale statefulset redis -n statefulset-lab --replicas=5
kubectl get pods -n statefulset-lab -w
# Scale down: highest ordinals stop first
kubectl scale statefulset redis -n statefulset-lab --replicas=3
# The PVCs of the removed pods are kept
kubectl get pvc -n statefulset-lab -l app=redis
Remember

By default, Kubernetes keeps a StatefulSet's PVCs after a scale-down or a delete, so data is never lost by accident. The persistentVolumeClaimRetentionPolicy field, with whenScaled and whenDeleted set to Retain or Delete, changes that, so review it before scaling down or deleting a database.

Step 7 - Troubleshoot Common Failures
Symptom Likely cause What to do
Pod stuck in Terminating Node is unreachable, or a finalizer or volume detach is blocking it Check the node and finalizers, and force delete only once the node is confirmed gone
Replacement pod never starts after a node failure The StatefulSet keeps at most one pod per identity and waits until the old one is confirmed deleted Remove the dead node or force delete the pod, accepting the data risks below
Multi-Attach error on the new pod The block volume is still attached to the failed node Wait for detach, or fix the node state, then retry
PVC shows Pending The class uses WaitForFirstConsumer, or the zone has no capacity Check pod scheduling first, then kubectl describe pvc
redis-1 never appears redis-0 is not Ready, so ordered startup is waiting Run kubectl describe pod redis-0 and read its logs
Bash
kubectl describe pod redis-0 -n statefulset-lab
kubectl logs redis-0 -n statefulset-lab
kubectl get pod redis-0 -n statefulset-lab -o jsonpath='{.metadata.finalizers}'
kubectl get events -n statefulset-lab --sort-by=.lastTimestamp

Force deleting a pod removes it from the API immediately, without proof that the process has stopped. If the node is only unreachable and not dead, two pods with the same identity could write to the same data, so force delete only when you are certain the node is gone:

Bash
kubectl delete pod redis-0 -n statefulset-lab --force --grace-period=0
Step 8 - Clean Up

Scale to zero first so pods stop in order, because deleting a StatefulSet does not guarantee ordered termination. Then delete the leftover PVCs on purpose:

Bash
kubectl scale statefulset redis postgres -n statefulset-lab --replicas=0
kubectl delete statefulset redis postgres -n statefulset-lab
kubectl delete pvc --all -n statefulset-lab
kubectl delete namespace statefulset-lab

Production Best Practices & Common Pitfalls

Common Mistake

Scaling a database StatefulSet and assuming it created replicas. Without replication configured, extra PostgreSQL or MySQL pods are separate, empty databases. Configure replication yourself or use an operator that does it.

Tip

Use partition for major upgrades. Update one pod, verify replication lag and health, then lower the partition to continue, and update the primary last.

Remember

Set terminationGracePeriodSeconds to at least 60 for databases. The default 30 seconds can be too short for a clean checkpoint, and a hard kill risks recovery time or data loss.

  • Use an operator for production PostgreSQL and MySQL. Operators automate replication, failover, backups and upgrades, which a StatefulSet alone does not.
  • Spread pods across nodes and zones. Add topology spread constraints or pod anti-affinity, and remember that each volume is tied to one zone, so a pod can only run where its disk is.
  • Protect pods with a PodDisruptionBudget. A budget keeps drains and autoscaler scale-downs from taking too many replicas at once, and a single-replica database needs a plan for maintenance instead.
  • Set memory requests equal to limits. A database with a limit far above its request can be killed under node pressure.
  • Use podManagementPolicy: Parallel only for independent pods. It suits data nodes that do not depend on each other, and it removes the ordering guarantees that primary and replica setups rely on.
  • Back up beyond volume snapshots. Snapshots are crash-consistent, so add logical backups or WAL archiving, schedule them, and test a restore.
  • Watch replication lag. A replica that falls far behind loses recent writes if the primary fails, so alert on lag.

Quick Reference & Troubleshooting Commands

Command Description
kubectl get statefulset -n NS List StatefulSets and replica counts
kubectl describe statefulset NAME -n NS Show configuration and events
kubectl get pods -n NS -w Watch ordered startup and termination
kubectl scale statefulset NAME --replicas=N -n NS Scale up or down
kubectl rollout status statefulset/NAME -n NS Watch a rolling update
kubectl rollout undo statefulset/NAME -n NS Roll back to the previous revision
kubectl get pvc -n NS -l app=NAME List the PVCs a StatefulSet created
kubectl exec -it NAME-0 -n NS -- sh Open a shell in the first pod
kubectl delete pod NAME-0 -n NS --force --grace-period=0 Force delete a stuck pod on a confirmed-dead node

Resources

Velero vs etcd Snapshot: Which Do You Need?

Velero vs etcd Snapshot: Which Do You Need?

Velero and etcd snapshots protect different layers of a Kubernetes cluster. See what each backs up, what each misses, and why most DR needs both.

11 min read•Aug 2026
Istio Ambient vs Linkerd in 2026: Which Mesh?

Istio Ambient vs Linkerd in 2026: Which Mesh?

Istio Ambient cuts the sidecar tax at L4, but L7 adds waypoint hops, and Linkerd stable builds now come from Buoyant. Choose with tests.

11 min read•Aug 2026
Nginx Ingress vs Traefik vs Gateway API in 2026

Nginx Ingress vs Traefik vs Gateway API in 2026

Ingress-NGINX is retired. Compare Traefik and Gateway API controllers as replacements, plus a safe migration plan that avoids outages.

10 min read•Aug 2026
OPA Gatekeeper vs Kyverno: Policy Engine in 2026

OPA Gatekeeper vs Kyverno: Policy Engine in 2026

OPA Gatekeeper vs Kyverno compared for 2026: Rego vs YAML, mutation, reporting, and operations, plus how to pick a Kubernetes policy engine.

10 min read•Aug 2026
Helm vs Kustomize in 2026: Templating vs Patching

Helm vs Kustomize in 2026: Templating vs Patching

Helm vs Kustomize compared for 2026 - templating vs patching, Helm 4's new features, and why most production teams end up running both.

5 min read•Aug 2026
Prometheus vs Datadog vs New Relic: Real Costs

Prometheus vs Datadog vs New Relic: Real Costs

Prometheus, Datadog, and New Relic compared for 2026 - real pricing at scale, hidden cost drivers, and which fits a Kubernetes-heavy stack.

5 min read•Aug 2026
Cluster Autoscaler vs Karpenter for EKS in 2026

Cluster Autoscaler vs Karpenter for EKS in 2026

Cluster Autoscaler vs Karpenter on EKS: scale-up speed, bin-packing, Spot handling, Auto Mode limits and a safe migration path, with v1 NodePool YAML.

11 min read•Aug 2026
GKE vs EKS vs AKS in 2026: Which Fits Your Team?

GKE vs EKS vs AKS in 2026: Which Fits Your Team?

GKE, EKS, and AKS compared for 2026 - control plane pricing, Autopilot vs Karpenter vs Node Auto Provisioning, and which platform actually fits your team.

5 min read•Aug 2026
K3s vs K8s vs MicroK8s: Which Distro in 2026?

K3s vs K8s vs MicroK8s: Which Distro in 2026?

Compare K3s, upstream Kubernetes and MicroK8s on footprint, datastores, HA and updates, and pick the right fit for edge, dev or production.

10 min read•Aug 2026
Canary Deployments with Argo Rollouts & Flagger

Canary Deployments with Argo Rollouts & Flagger

Ship to 5% of users first and auto-rollback on bad metrics: canary deployments on Kubernetes with Argo Rollouts, Flagger, and Gateway API.

11 min read•Jun 2026
OpenTelemetry Explained: Metrics, Logs, Traces

OpenTelemetry Explained: Metrics, Logs, Traces

OpenTelemetry in practice: instrument a Node.js service, run a production Collector, sample traces and link metrics, logs and traces in Grafana.

11 min read•Jun 2026
Kubernetes Cost Optimization Without SLO Risk

Kubernetes Cost Optimization Without SLO Risk

Kubernetes clusters average about 8% CPU use. Cut waste safely with request rightsizing, autoscaling, spot, and OpenCost, keeping SLOs.

11 min read•Jun 2026
ArgoCD vs FluxCD: GitOps for Kubernetes in 2026

ArgoCD vs FluxCD: GitOps for Kubernetes in 2026

ArgoCD vs FluxCD compared for 2026: UI, multi-tenancy, Helm, image automation and pruning risks, with a clear guide to picking your GitOps engine.

10 min read•Jun 2026

Explore More in Kubernetes Workload Management

All 6 Topics

Frequently Asked Questions

Is Running StatefulSets for Databases on Kubernetes free to learn on DevOps Network?

Yes - this topic, like everything on DevOps Network, is 100% free with no paywall or sign-up gate.

What does the Running StatefulSets for Databases on Kubernetes topic cover?

Deploy and manage stateful database workloads on Kubernetes using StatefulSets with stable network identities, ordered scaling, and persistent storage.

Found a mistake, an outdated step or a broken link?