Overview

16 Handling stateful applications with StatefulSets

This chapter explains how Kubernetes handles stateful workloads and why StatefulSets are the right tool compared to Deployments for applications that need stable identities and persistent storage. It contrasts “pets vs. cattle,” shows how StatefulSets provide stable pod names with ordinal indexes, one-or-more PersistentVolumeClaims per replica via claim templates, and stable network identities through a required headless Service. It also covers the DNS records (including SRV) that let clients and peers discover specific replicas, and illustrates all of this with a MongoDB-backed “quiz” example where each replica needs its own volume and address, plus careful initialization of a replica set. The result is predictable identity, ordered creation when needed, and scalable patterns that respect per-replica state.

The chapter then examines StatefulSet behavior in depth: at‑most‑one semantics prevent duplicate identities during node failures; replacement pods keep the same names and reclaim their volumes; and special care is required when storage is local or when volumes can’t be detached from failed nodes. Scaling up creates new pods and claims; scaling down deletes pods but typically retains claims (with a configurable retention policy) so data can be reattached later. It compares the OrderedReady and Parallel pod management policies, showing how strict ordering can avoid race conditions but may deadlock if readiness depends on quorum, and how adjusting readiness probes or policies can break such stalemates. It also shows how to import seed data safely, how Services and readiness interact for client traffic, and how to choose between one or two Services for stateful clusters.

Finally, it covers StatefulSet updates: RollingUpdate replaces pods one by one (with optional minReadySeconds) and supports partitioning for staged or canary rollouts; OnDelete gives full operator control to update pods in any order and pace. It shows how to monitor rollouts, inspect revision history via ControllerRevisions, and roll back safely. The chapter concludes by motivating Kubernetes Operators for end‑to‑end automation beyond what StatefulSets provide—demonstrating the MongoDB Community Operator, which introduces a custom resource to declare desired state, and then handles creating StatefulSets, Services, security artifacts, replica‑set initialization, and scaling logic so teams can manage complex stateful systems declaratively and reliably.

All pods from a Deployment use the same PersistentVolumeClaim and PersistentVolume.
Providing each replica with its own volume and address.
Treating entities as pets vs. treating them as cattle
A StatefulSet, its pods, and PersistentVolumeClaims
A headless Service used in combination with a StatefulSet
StatefulSets don’t delete PersistentVolumeClaims when scaling down; then they reattach them when scaling back up.
Comparison between the OrderedReady and Parallel Pod management policy
How the pods are updated over time with different update strategies
Partitioning a rolling update
Managing an application through custom resources and operators

Summary

  • Stateful workloads are harder to manage than their stateless counterparts because managing state is difficult. However, with StatefulSets, managing stateful workloads becomes much easier because the StatefulSet controller automates most of the work.
  • With StatefulSets you can manage a group of pods as pets, whereas Deployments treat the pods like cattle. The pods in a StatefulSet use ordinal numbers instead of random names.
  • A StatefulSet ensures that each replica gets its own stable identity and its own PersistentVolumeClaim(s). These claims are always associated with the same pods.
  • In combination with a StatefulSet, a headless Service ensures that each pod receives a DNS record that always resolves to the pod’s IP address, even if the pod is moved to another node and receives a new IP address.
  • StatefulSet Pods are created in the order of ascending ordinal numbers and deleted in reverse order.
  • The Pod management policy configured in the StatefulSet determines whether pods are created and deleted sequentially or simultaneously.
  • The PersistentVolumeClaim retention policy determines whether claims are deleted or retained when you scale down or delete a StatefulSet.
  • When you update the pod template in a StatefulSet, the controller updates the underlying pods. This happens on a rolling basis, from highest to lowest ordinal number. Alternatively, you can use a semi-automatic update strategy, where you delete a pod and the controller then replaces it.
  • Since StatefulSets don’t provide everything needed to fully manage a stateful workload, these types of workloads are typically managed via custom API object types and Kubernetes Operators. You create an instance of the custom object, and the Operator then creates the StatefulSet and supporting objects.

FAQ

Why are Deployments a poor fit for scaling stateful workloads that share storage?Most clouds only provide ReadWriteOnce (RWO) volumes, so the same PersistentVolume cannot be attached read/write to multiple nodes. If you scale a Deployment that mounts a single PersistentVolumeClaim, new pods may fail to start (volume attach conflicts) or the app (for example, MongoDB) may refuse to run because multiple instances attempt to use the same data directory. Each replica typically needs its own volume and stable identity—something Deployments don’t provide.
How do StatefulSets differ from Deployments for stateful apps?- Stable identity: Pods get predictable names with ordinal indexes (setname-0, setname-1, …) and keep the same identity across restarts.
- Storage per replica: volumeClaimTemplates create one or more PersistentVolumeClaims per pod replica and keep them associated by ordinal.
- Ordered semantics: By default, pods are created/deleted one at a time (OrderedReady), though you can opt into Parallel creation.
- Direct ownership: StatefulSets own pods directly (no intermediate ReplicaSet).
Why does a StatefulSet need a headless Service and what DNS records are created?A headless Service (clusterIP: None) gives each pod a stable DNS name and IP resolution. When paired with a StatefulSet, Kubernetes publishes per-pod A/AAAA records, e.g., pod-0.service.namespace.svc.cluster.local. If you set publishNotReadyAddresses: true, DNS entries are created before pods are ready. If the Service port is named mongodb, SRV records (_mongodb._tcp.service.ns.svc.cluster.local) are also created, allowing clients to discover all replicas and their ports automatically.
What were the key steps to deploy the MongoDB replica set with a StatefulSet in the chapter?- Create a headless Service (quiz-pods) with publishNotReadyAddresses: true and a port named mongodb.
- Create the quiz StatefulSet with volumeClaimTemplates and run mongod with --replSet.
- Initiate the replica set once pods are up, using each pod’s fully-qualified DNS name.
- Optionally use an SRV URI (mongodb+srv://quiz-pods.kiada.svc.cluster.local).
- Import data via a one-shot “importer” pod instead of an init container, so data isn’t duplicated across replicas.
Why were the quiz pods initially not ready, and how was it fixed?The quiz-api readiness probe depended on MongoDB, but mongod was started with --replSet and the replica set had not yet been initiated. The API could connect but not execute commands, so readiness failed. Running rs.initiate with all pod hostnames brought the set to quorum; afterward all pods became ready.
How does a StatefulSet handle pod deletion and node failures?- Deletion: If you delete a pod (e.g., quiz-1), the controller recreates a pod with the same name and reattaches its PVC(s), preserving state and identity.
- Node failures: StatefulSets enforce “at-most-one” semantics. If a node becomes unreachable, the controller does not immediately recreate the pod elsewhere to avoid two identical identities running at once. Operators must verify failure and may need to force-delete the Pod object; with local storage, scheduling can be blocked; with network volumes, attach/detach can block if the volume is still attached to the failed node.
What happens to PersistentVolumeClaims when scaling a StatefulSet, and how can I control it?When scaling down, pods are deleted in reverse ordinal order, but their PVCs are retained by default to avoid data loss. You can configure this with spec.persistentVolumeClaimRetentionPolicy: set whenScaled and whenDeleted to Retain or Delete. Use Delete only if data is safely retained elsewhere or can be rebuilt; otherwise prefer Retain and delete PVCs manually when you’re sure it’s safe.
What are OrderedReady vs Parallel podManagementPolicy, and what pitfalls exist?- OrderedReady (default): Creates and deletes pods one at a time, waiting for each to be ready. Good for apps that require strict startup/shutdown ordering. Drawback: can deadlock if readiness depends on quorum (e.g., first pod never becomes ready, so others never start). Scale-down is blocked if not all replicas are ready.
- Parallel: Creates/deletes pods concurrently; faster but relaxes ordering guarantees. Choose based on app requirements.
How are StatefulSets updated, and how can I control rollout pace and scope?- Strategies: RollingUpdate (default) replaces one pod at a time, highest ordinal first; OnDelete updates only when you manually delete each pod.
- Pace: minReadySeconds adds a delay after a pod is ready before updating the next one.
- Partitioned rollout: With RollingUpdate, spec.updateStrategy.rollingUpdate.partition prevents updating pods with ordinals lower than the partition value—useful for staging changes or canarying a single pod.
- History and rollback: Revisions are tracked in ControllerRevision objects; use kubectl rollout history/undo to inspect and revert.
When should I use a Kubernetes Operator instead of managing StatefulSets directly?Use an Operator when the application requires domain-specific automation beyond StatefulSets, such as automatically initiating and reconfiguring a database replica set on scale events, handling failover workflows, managing users/credentials, or enforcing best practices. With the MongoDB Community Operator, you declare a MongoDBCommunity custom resource; the operator creates/maintains the StatefulSet and Services, handles replica set initiation and scaling logic, and reconciles drift so you manage MongoDB declaratively.

pro $24.99 per month

  • access to all Manning books, MEAPs, liveVideos, liveProjects, and audiobooks!
  • choose one free eBook per month to keep
  • exclusive 50% discount on all purchases
  • renews monthly, pause or cancel renewal anytime

lite $19.99 per month

  • access to all Manning books, including MEAPs!

team

5, 10 or 20 seats+ for your team - learn more


choose your plan

team

monthly
annual
$49.99
$499.99
only $41.67 per month
  • five seats for your team
  • access to all Manning books, MEAPs, liveVideos, liveProjects, and audiobooks!
  • choose another free product every time you renew
  • choose twelve free products per year
  • exclusive 50% discount on all purchases
  • renews monthly, pause or cancel renewal anytime
  • renews annually, pause or cancel renewal anytime
  • Kubernetes in Action, Second Edition ebook for free
choose your plan

team

monthly
annual
$49.99
$499.99
only $41.67 per month
  • five seats for your team
  • access to all Manning books, MEAPs, liveVideos, liveProjects, and audiobooks!
  • choose another free product every time you renew
  • choose twelve free products per year
  • exclusive 50% discount on all purchases
  • renews monthly, pause or cancel renewal anytime
  • renews annually, pause or cancel renewal anytime
  • Kubernetes in Action, Second Edition ebook for free
choose your plan

team

monthly
annual
$49.99
$499.99
only $41.67 per month
  • five seats for your team
  • access to all Manning books, MEAPs, liveVideos, liveProjects, and audiobooks!
  • choose another free product every time you renew
  • choose twelve free products per year
  • exclusive 50% discount on all purchases
  • renews monthly, pause or cancel renewal anytime
  • renews annually, pause or cancel renewal anytime
  • Kubernetes in Action, Second Edition ebook for free