What Is a StatefulSet in Kubernetes?
Most Pods in Kubernetes are disposable and interchangeable, but databases and clustered software need names, storage and start-up order that stay steady. A StatefulSet is the Kubernetes tool built for exactly that. This guide explains it from zero, in plain words.
Imagine a school where every class has a different teacher with a different name badge, a personal desk drawer full of marked exercise books, and a fixed seat in the staff room. If one teacher falls ill, the substitute who arrives wears the same badge, opens the same drawer, and sits in the same seat, so the pupils and the other teachers carry on as if nothing changed.
Kubernetes has a special tool that works in this way for software. Ordinary Pods are like paper cups: use one, throw it away, take another. But some programs, such as databases, cannot live like that. They need to keep their name, their data and their place in the group. The tool that gives them this is called a StatefulSet, and this article will explain it slowly, step by step, with everyday pictures to help each idea stick.
1The Problem: Not Everything Can Be Disposable
Kubernetes loves replaceable Pods, but some programs must remember.
Kubernetes runs programs in containers, and containers live inside Pods. By design, Pods are temporary. When one dies, a new one with a new name and a new address takes its place, and anything stored inside the old one is lost. For many applications, such as websites that only show pages, this is perfectly fine, because any copy can serve any visitor.
Now think about a database. A database must remember information for years. It may have several members, where one member is the leader and the others follow it. Each member needs to know who it is, where its data lives, and how to find its friends. If Kubernetes replaced a database Pod with a stranger that had a new name and empty storage, the cluster would be confused and data could be lost.
A taxi company does not mind which taxi picks you up, because any taxi does the job. A bank, however, would be alarmed if a different clerk turned up every morning and could not find yesterday’s paperwork. Stateless programs are like taxis. Stateful programs are like bank clerks with their own filing cabinets.
Those three steady things are the heart of the StatefulSet. If you remember nothing else, remember this trio: name, storage, order.
2A Quick Refresher: Pods, State and Storage
A few basics make everything that follows easier.
A Pod is the smallest unit Kubernetes runs: a small wrapper around one or more containers that share a home. A node is one computer in the cluster where Pods run. A controller is a watcher that compares what you want with what exists and creates or removes Pods to match.
State means memory: the information a program must keep between requests, such as customer records, messages in a queue or the current leader of a group. A stateless program keeps no such memory inside itself, while a stateful program does. Because container file space disappears when a Pod is replaced, stateful programs need storage that lives outside the Pod.
| Question | Stateless program | Stateful program |
|---|---|---|
| Does it remember things? | Not inside itself | Yes, it must keep data |
| Can any copy replace another? | Yes, freely | Only if the replacement gets the same data and identity |
| Example | A website that shows pages | A database or message queue |
| Best Kubernetes tool | Deployment | StatefulSet |
A vending machine gives the same result no matter which identical machine you use. A librarian who remembers which books each member has borrowed cannot be swapped for a stranger without handing over the records. The vending machine is stateless; the librarian is stateful.
Being stateful does not make a program bad or old-fashioned. Every useful system stores data somewhere. The question is only where the memory lives and how safely it survives change.
3So, What Exactly Is a StatefulSet?
The short version: a controller that gives Pods a lasting identity.
A StatefulSet is a Kubernetes object that manages a group of Pods and gives each of them three guarantees. First, every Pod gets a stable, predictable name that never changes, built from the StatefulSet’s name and a number, such as database-0, database-1 and database-2. Second, every Pod gets its own personal storage that follows it, even if the Pod is replaced. Third, Pods are created, updated and removed in a careful, defined order.
Like a Deployment, a StatefulSet watches the real number of Pods and replaces any that are lost. The difference is in what the replacement looks like. A Deployment replaces a Pod with a fresh stranger. A StatefulSet replaces it with a Pod that has the same name and reconnects to the same storage.
Think of a football team with numbered shirts. If player number seven is injured, the substitute wears shirt seven, plays in the same position, and uses the same locker. The team keeps its shape even though the person is new. A StatefulSet is the coach who makes sure shirt seven is always filled.
A StatefulSet does not make a Pod immortal, and it does not make a database magically safe. Pods can still be lost. What the StatefulSet promises is that the replacement will inherit the name and the storage. Backups and correct database setup are still your responsibility.
4Core Concepts and Vocabulary
Ten simple words that unlock every StatefulSet conversation.
Ordinal
The number at the end of a Pod’s name, starting from zero. It is the shirt number of the Pod.
Stable network identity
A name that always leads to the same member, even after the Pod is replaced and its address changes.
Headless Service
A special Service that gives each Pod its own individual name instead of hiding them behind one shared address.
Persistent volume
A piece of lasting storage, such as a network disk, that exists independently of any Pod.
Persistent volume claim
A Pod’s request for storage of a certain size and type. Kubernetes matches it with a volume.
Volume claim template
A blueprint inside the StatefulSet that creates a separate storage claim for each Pod automatically.
Storage class
A description of a kind of storage, such as fast or cheap, that lets Kubernetes create disks on demand.
Pod management policy
The rule that decides whether Pods start one by one in order, or all together in parallel.
Update strategy
The rule that decides how Pods are replaced when you release a new version.
Replica
One member of the group. Three replicas mean three Pods numbered zero, one and two.
If you keep only two words, keep ordinal and volume claim template. The first gives every Pod its name, and the second gives every Pod its own storage.
5The Anatomy of a StatefulSet
Four pieces that always work together.
A working StatefulSet is not a single object. It is a small team of four pieces, each with a clear job. Understanding how they fit together is the key to the whole topic.
The StatefulSet itself
The controller that creates the numbered Pods, keeps the count, and manages their order and updates.
The Pods
The actual running members, named with their ordinals, each built from the same template.
The headless Service
The naming service that gives each Pod a steady, individual address by name inside the cluster.
The storage claims
One personal claim per Pod, created from the template, each attached to its own lasting disk.
flowchart TD
SS["StatefulSet: keeps 3 numbered members"] --> P0["Pod database-0"]
SS --> P1["Pod database-1"]
SS --> P2["Pod database-2"]
HS["Headless Service: gives each Pod its own name"] --- P0
HS --- P1
HS --- P2
P0 --> C0["Claim for database-0"]
P1 --> C1["Claim for database-1"]
P2 --> C2["Claim for database-2"]
C0 --> V0[("Disk 0")]
C1 --> V1[("Disk 1")]
C2 --> V2[("Disk 2")]
Picture a block of flats. The building manager is the StatefulSet. The flats are the Pods, each with a number on the door. The intercom directory is the headless Service, letting visitors call any flat by its number. The storage cupboard belonging to each flat is the claim and its disk.
6Guarantee One: Stable Names and Network Identity
Every member can be found by name, always.
In a StatefulSet, Pod names are predictable. If the StatefulSet is called database and has three replicas, the Pods are called database-0, database-1 and database-2. Unlike Pods made by a Deployment, there are no random letters. When database-1 is lost, its replacement is again called database-1.
To let other programs and other members find each Pod by name, the StatefulSet works with a headless Service. A normal Service hides all its Pods behind one shared address and picks any Pod for each visitor. A headless Service does the opposite: it gives each Pod its own individual name that points straight to it. So the group can talk about “database-0” and always reach the right one.
What stays the same after a replacement
The Pod’s name and its network name. Other members and clients can keep using the same name and reach the new Pod.
What may change after a replacement
The Pod’s own internal address may change, and the Pod may run on a different computer. Programs should therefore use names, not addresses.
Why the name matters to databases
Clustered software often stores the names of its members in its own settings. A steady name lets the cluster recognise a replacement as the same member returning home.
Think of office desk phone extensions. Extension seven always reaches whoever sits at desk seven, even if the person changes. Colleagues never need to update their contacts. The extension is the stable name, and the person at the desk is the Pod.
A StatefulSet expects a headless Service to exist and be named in its settings. Kubernetes does not create it for you, so forgetting it is a classic beginner slip that leaves Pods without their individual names.
7Guarantee Two: Stable, Personal Storage
Every member owns a private disk that follows it.
The second guarantee is storage. Inside the StatefulSet’s description, you include a blueprint called a volume claim template. For each Pod, Kubernetes uses that blueprint to create a separate claim, named after the Pod. Each claim is matched with its own lasting disk, either an existing one or one created automatically by a storage plugin.
When a Pod is replaced, the new Pod with the same number reconnects to the same claim and therefore the same disk. All the data, exactly as it was left, is waiting. The Pod is temporary. The disk is not.
The StatefulSet creates a Pod
For example, database-0, using the shared Pod blueprint.
A personal claim is created
From the volume claim template, Kubernetes makes a claim that belongs to database-0 alone.
A disk is provided
The storage class creates or selects a disk, and the claim is bound to it.
The disk is mounted into the Pod
The kubelet on the chosen node attaches the disk and makes it appear as a folder inside the container.
The Pod is lost and replaced
The new database-0 finds the same claim already waiting and mounts the same disk, with all the data intact.
Every teacher in our school has a personal locker with their name on it. If the teacher is replaced by a substitute for a day, the substitute is given the key to the same locker and finds all the marked books. The locker belongs to the position, not to the person.
By default, when a Pod is deleted or the StatefulSet is scaled down or even removed, the personal disks are kept. This is a deliberate safety choice to protect your data from accidents.
8Guarantee Three: Ordered Start, Stop and Scaling
Members arrive and leave one at a time, in a planned order.
Many clustered programs need a careful start. The first member sets up the group, and the others join it. So, by default, a StatefulSet creates its Pods one at a time in number order. It creates the Pod with number zero, waits until it is running and ready, and only then creates number one, and so on.
Removal works in the opposite direction. When you reduce the number of replicas, the highest-numbered Pod is removed first, and the next removal waits until the previous Pod has fully ended. This keeps the founding members in place as long as possible.
sequenceDiagram
participant SS as StatefulSet controller
participant P0 as Pod 0
participant P1 as Pod 1
participant P2 as Pod 2
SS->>P0: Create Pod 0
P0-->>SS: Running and ready
SS->>P1: Create Pod 1
P1-->>SS: Running and ready
SS->>P2: Create Pod 2
P2-->>SS: Running and ready
Note over SS,P2: Scaling down goes the other way
SS->>P2: Remove Pod 2 first
P2-->>SS: Fully terminated
SS->>P1: Then remove Pod 1
When a theatre company sets up a show, the stage manager arrives first, then the lighting crew, then the actors. When the show ends, the actors leave first, then the lights are switched off, and the stage manager locks up last. The order is not decoration; each step depends on the previous one.
Why readiness matters so much
Because the controller waits for each Pod to be ready before moving on, the health checks you define become very important. If Pod zero never reports ready, the StatefulSet will never create Pod one. This is a feature, since it stops a broken first member from being joined by more members, but it means broken readiness checks can freeze a rollout.
If a Pod cannot become ready, later Pods will wait forever. When a StatefulSet appears to be doing nothing, look at the first Pod that is not ready.
9StatefulSet Versus Deployment
Two tools for two different kinds of program.
Deployments and StatefulSets look similar at first, because both keep a number of Pods running from a common blueprint. But they are built on opposite philosophies. A Deployment treats Pods as identical and interchangeable. A StatefulSet treats each Pod as an individual with a role.
| Feature | Deployment | StatefulSet |
|---|---|---|
| Pod names | Random suffix, different after each replacement | Ordered number, same after each replacement |
| Storage | Usually none, or one shared disk | Own personal disk for each Pod |
| Start order | All together, in any order | One by one, in number order by default |
| Stop order | Any order | Highest number first, by default |
| Network identity | Shared Service, Pods hidden behind it | Headless Service, each Pod has its own name |
| Update order | Gradual mix of old and new | Highest number first, one at a time by default |
| Best for | Stateless applications | Databases, queues, clustered software |
A Deployment is like a fleet of identical delivery vans: if one breaks, any other van takes the parcel. A StatefulSet is like a group of specialist surgeons: each has a role, and a replacement must be trained for that exact role and given the same patient files.
If your program does not truly need stable names, personal storage or ordered start-up, a Deployment is simpler and easier to operate. Use a StatefulSet when the guarantees are genuinely required.
10What Happens When a Pod or Node Fails
Identity is returned carefully, and never twice at once.
When a Pod in a StatefulSet fails, the controller notices that a member is missing and creates a replacement with the same name. The replacement reattaches to the same disk and rejoins the group. This is the everyday healing story, and it usually takes only a short time.
A harder situation arises when a whole computer becomes unreachable. The control plane cannot be sure whether the Pod on it is dead or merely cut off from the network, still running and still writing to its disk. If Kubernetes created a second Pod with the same identity and the same disk, two members could write to the same data at once, and the data could be corrupted.
To protect against this, a StatefulSet follows an at-most-one rule: it never runs two Pods with the same identity at the same time. So if a node vanishes, the Pod on it is left in a waiting state until Kubernetes can be sure it is gone, and only then is the replacement created.
flowchart TD
A["Node becomes unreachable"] --> B["Pod on it cannot be confirmed as stopped"]
B --> C{"Is it safe to replace it?"}
C -- "Node recovers, or is confirmed gone" --> D["Old Pod is removed"]
D --> E["New Pod with the same name is created"]
E --> F["New Pod reattaches to the same disk"]
C -- "Not sure yet" --> G["StatefulSet waits: at most one Pod per identity"]
Imagine a night watchman who stops answering the radio. The security company cannot be sure whether he is unwell or simply out of range. Sending a second guard with the same keys and same assigned post, while the first is still on duty, could cause chaos. So they wait until they know for certain, and only then send the replacement.
Forcing a stuck Pod to disappear tells Kubernetes it is safe to create a replacement immediately. If the old Pod is actually still running somewhere, you may get two members with one identity. Only do this when you are certain the old one is really dead.
11Pod Management Policies: Ordered or Parallel
Sometimes order is essential, and sometimes it only slows things down.
By default, a StatefulSet uses the ordered policy: one Pod at a time, each waiting for the last. This suits software that needs a careful start. But some stateful programs need stable names and storage without needing a strict start order. For them, waiting for every Pod in turn just wastes time, especially with many members.
For such cases, StatefulSets offer a parallel policy, where Pods are started or stopped together without waiting for each other. The names and storage guarantees still apply; only the sequence rule is relaxed.
| Policy | How Pods start and stop | Good for |
|---|---|---|
| Ordered, the default | One at a time, each must be ready before the next starts | Software where the first member sets up the group and others join |
| Parallel | All at once, without waiting | Software that needs identity and storage but can start in any order |
A group of climbers roped together must move one at a time, each waiting until the person ahead is secure. A group of shoppers entering a shop can walk in together, because nobody depends on anyone else’s position.
Whether your database tolerates parallel start-up is a property of the database, not of Kubernetes. Always follow the vendor’s advice when choosing the policy.
12Rolling Updates and Staged Rollouts
Updating a database member by member, with a safety brake.
Releasing a new version of a stateful program is more delicate than updating a website. If you replace all members at once, the whole database could go down. The default update strategy of a StatefulSet is therefore a careful rolling update: it replaces one Pod at a time, starting with the highest number and moving downwards, waiting for each new Pod to become ready before touching the next.
Going from the highest number to the lowest means the founding members, such as Pod zero, are updated last. Many clustered systems rely on those early members for stability, so updating them at the end is a sensible choice.
The partition: a staged rollout brake
A StatefulSet lets you set a partition number. Only Pods with a number equal to or higher than the partition are updated. Pods below it stay on the old version, even if they are deleted and recreated. This lets you update just one member first, watch how it behaves, and then lower the partition step by step to roll the update out to the rest. It is a built-in canary release.
Rolling update, the default
Pods are replaced one at a time from the highest number down. Each new Pod must be ready before the next is touched.
Rolling update with a partition
Only Pods at or above a chosen number are updated. Lower the number gradually to move the rollout forward, or leave it to test a new version on a single member.
Update on delete
Nothing changes automatically. Pods are updated only when you delete them yourself, giving you full manual control over timing.
Imagine renovating a hotel floor by floor while it stays open. You start with the top floor, check that guests are happy, and only then move to the next floor down. The reception on the ground floor, which everyone relies on, is done last.
If a new version never becomes ready, the rollout stops and waits. Simply fixing the description may not be enough, because the stuck Pod may need to be removed by hand so that a corrected Pod can be created.
13Scaling a StatefulSet
Adding and removing members is easy for Kubernetes, but not always for the software.
Changing the number of replicas is simple on the Kubernetes side. Scaling up adds new numbered Pods and creates a personal disk for each. Scaling down removes the highest-numbered Pods but leaves their disks in place by default.
The harder part lives inside the application. A new database member may need to copy data from others before it is useful. A departing member may need to hand over its share of the data first. Kubernetes creates and removes Pods, but it does not know your database’s rules for joining and leaving.
What Kubernetes handles
- Creating or removing Pods in the right order
- Giving each new Pod a stable name
- Creating a personal storage claim for each new Pod
- Keeping disks after scale-down, so data is not lost by accident
What the application must handle
- Joining a new member to the group and copying data to it
- Handing over responsibilities before a member leaves
- Re-balancing data across members after a change
- Cleaning up leftover disks and old member records
A landlord can add a new flat to a building and give it a number and a storage cupboard. But teaching the new tenant how the neighbours share the laundry room is a different job. Kubernetes is the landlord; the database is the neighbourhood.
What happens to leftover disks
Because disks stay after scaling down, scaling back up later will reconnect the returning Pod to its old disk, which may contain outdated data. Newer versions of Kubernetes let you choose a retention policy that decides whether disks are kept or deleted when Pods are scaled away or when the StatefulSet is removed. The safe default is to keep them, and changing it should be a deliberate decision.
14Storage Choices and Traps
The disk under a StatefulSet decides how safe and fast it is.
A StatefulSet is only as good as its storage. Kubernetes asks a storage plugin to provide disks, and different plugins behave very differently. Some disks live on the network and can be re-attached to any computer. Others live on a specific computer’s own drive and can only be used by Pods on that computer.
Network disks
Can follow a Pod to a new computer in the same zone. Flexible, but slightly slower and tied to zones in many clouds.
Local disks
Very fast, because they sit inside the computer. But if the computer dies, the disk and its data may be unreachable.
Shared file storage
Several Pods can use the same folder at once. Useful for some programs, but most databases want their own private disk.
Storage classes
Named recipes for disks, such as fast, cheap or encrypted, that the StatefulSet can request by name.
Traps to watch for
A common trap is the zone problem. Many cloud disks exist in one zone only. If a Pod is replaced and Kubernetes tries to start it in a different zone, it cannot reach its disk and stays waiting. Good storage settings make Kubernetes place the Pod in the same zone as its disk. Another trap is running out of space: disks have fixed sizes, and a full disk can crash a database. Many storage classes allow the disk to be enlarged later, but the ability depends on the plugin.
A local disk is like a locker inside your own office: quick to reach, but useless if the office burns down. A network disk is like a locker in a secure storage building across town: slightly slower to reach, but safe if your office is lost.
Many databases keep copies of data on several members themselves. Combining that with disks that survive Pod loss gives two layers of protection, but neither replaces proper backups.
15Configuration, Secrets and Health Checks
Every member needs settings, secrets and a way to prove it is well.
All Pods in a StatefulSet share one blueprint, so settings and secrets are usually delivered from the cluster’s configuration and secret stores. But members often need small differences, such as knowing their own number or the names of their peers. The predictable Pod names make this possible, because a start-up step can read the Pod’s own name and work out its role.
Health checks matter even more than usual. The readiness check tells Kubernetes when a member is truly ready to serve, and the ordered start policy waits for it. A liveness check tells Kubernetes when a member is stuck and needs a restart. A startup check gives slow programs extra time, which is especially valuable for databases that need to recover their data when starting.
Readiness for a database
The check should confirm that the member has really joined the group and can answer requests, not just that its process is running.
Liveness for a database
The check should be gentle and only look at the member itself. A check that depends on other members can cause a chain of needless restarts.
Startup patience
Databases may need minutes to replay their logs after a restart. A startup check prevents Kubernetes from killing a member that is simply still recovering.
A surgeon returning after a break needs time to scrub in and check the instruments. The hospital does not declare the surgeon absent because the operating room is not yet ready. A startup check is that patient allowance.
A liveness check that is too strict can restart a member in the middle of recovering data, making the recovery start over again and again. Give stateful programs generous, patient checks.
16Backups, Snapshots and Disaster Recovery
Lasting disks are not the same as safe data.
It is tempting to think that because a StatefulSet keeps disks safe from Pod loss, the data is fully protected. It is not. Disks can be deleted by mistake, software bugs can corrupt data, and whole zones or clusters can fail. Backups are still essential.
Application-level backups
Use the database’s own tools to create consistent copies of the data and store them outside the cluster.
Volume snapshots
Storage plugins can take point-in-time snapshots of disks, useful for quick restores when the application is quiet or prepared.
Replication to another place
Keeping a copy in another zone or region protects against larger failures than a single computer.
Restore drills
A backup that has never been restored is only a hope. Practise restoring into a separate environment on a schedule.
Keeping documents in a fireproof cabinet protects them from a small fire, but not from someone shredding them by mistake or from the whole building flooding. A copy stored in another town is what protects you from those larger problems.
The moment of restoring is the moment you learn whether your backups are useful. Rehearse it calmly before you need it in an emergency.
17Security Around StatefulSets
The data inside is valuable, so guard the doors.
Stateful workloads usually hold the most valuable information a company owns: customer records, payments, messages. That makes them a favourite target. Several layers of protection work together.
Access control
Limit who can view, change or delete the StatefulSet and its disks. Deleting a claim can destroy data, so protect that permission.
Network rules
Allow only the applications that need the database to reach it, and block everyone else with network policies.
Secrets handling
Deliver passwords and keys from a protected secret store, never bake them into container packages.
Encryption
Encrypt data on disk and in transit between members and clients, so stolen disks or eavesdroppers learn nothing.
Hardened containers
Run members with minimal privileges, as non-administrator users, with only the permissions they need.
Audit and backup protection
Record who did what, and store backups in a place that an intruder in the cluster cannot delete.
A bank vault has thick walls, a guard at the door, a logbook of who entered, cameras, and a separate vault in another city for copies. No single measure is enough, but together they make theft very hard.
Giving every application in the cluster network access to the database, or using one shared password for everything, makes a small breach into a large one. Restrict and separate.
18Monitoring, Logging and Metrics
Stateful systems fail quietly, so keep watching.
A stateless website that fails is obvious, because pages stop loading. A stateful system can fail in slower, quieter ways: a disk fills up, a replica falls behind, a member silently loses touch with the group. Good monitoring catches these problems before they become disasters.
Metrics
Track disk space, memory, request rates, replication lag and the number of ready members over time.
Logs
Send each member’s logs to a central place. If a Pod is replaced, its local logs vanish, but central logs remain.
Events
Kubernetes events reveal problems such as disks that cannot attach or Pods waiting to be scheduled.
What to watch first
Start with a short list: is every member ready, how full is each disk, how far behind is each follower, how long do restarts take, and how many errors do clients see? An alert on disk usage at a comfortable margin is often the single most valuable alert for stateful workloads.
A doctor checking a patient reads pulse, temperature and blood pressure. A slow, silent illness shows in these numbers long before the patient feels ill. Disk usage and replication lag are the pulse and temperature of a database.
Space alerts should fire while there is still time to enlarge a disk or clean up, not when the database has already stopped.
19Reading the Signs: Common Problems
What you see, and what it usually means.
| What you see | Plain meaning | Where to look |
|---|---|---|
| Only the first Pod exists, and it is not ready | The ordered policy is waiting for it before creating the next | Readiness check, logs of the first Pod |
| Pod stays Pending | Kubernetes cannot place it or its disk | Storage class, zones, available capacity |
| Claim stays Pending | No disk could be created or matched | Storage class and the storage plugin |
| Pod stuck Terminating after node loss | Kubernetes cannot confirm the node has stopped it | Node status, and careful decision on force deletion |
| Rollout stops halfway | A new Pod is not becoming ready | Health checks, new version’s logs |
| Data seems old after scaling back up | A returning Pod reused its old disk | Application-level re-sync, retention policy |
| Disk full | Storage size is too small or data grew faster than planned | Disk usage graphs, enlarging or cleaning up |
A warning light on a car dashboard does not fix the car, but it points at the right part of the engine. Reading the status words on Pods and claims works the same way: the words tell you which system to inspect next.
Look at the StatefulSet’s status first, then the lowest-numbered Pod that is not ready, then its events and logs, then its storage claim. Working in order saves time.
20Advantages and Trade-offs
A powerful tool with real costs.
Advantages
- Stable names let clustered software recognise its members
- Personal disks follow each member across replacements
- Ordered start-up and shutdown protect fragile groups
- Careful rolling updates with a partition for staged releases
- At-most-one rule protects data from duplicate members
- Runs on any cluster with the same behaviour
Disadvantages / Trade-offs
- Slower and more delicate to change than stateless Deployments
- Does not know your database’s rules for joining, leaving or backups
- Stuck Pods often need careful human decisions
- Storage choices add complexity, costs and zone limitations
- Leftover disks must be managed and cleaned up
- Running databases yourself needs skill, time and monitoring
Many databases have an operator, a custom controller that adds the missing expert knowledge on top of a StatefulSet: setting up replication, handling failover, taking backups and upgrading safely. For serious databases, an operator is often the wiser route than a hand-built StatefulSet.
21Patterns to Follow and Anti-patterns to Avoid
Lessons other teams already paid for.
Helpful patterns
One StatefulSet, one headless Service
Always pair the StatefulSet with a headless Service for individual names, and a normal Service if clients need a single entry point.
Spread members across computers and zones
Use placement rules so that no single computer or zone holds all members, and make sure disks and Pods end up in the same zone.
Protect with disruption budgets
Limit how many members can be taken down at once during planned maintenance, so the group always keeps enough healthy members.
Use operators for serious databases
Let a well-maintained operator handle failover, backups and upgrades, and keep the StatefulSet as the foundation underneath.
Anti-patterns
Problem
Using a StatefulSet for an application that is really stateless.
Why It’s Harmful
You pay for slower updates, ordered rollouts and disk management without getting any benefit, and make simple changes harder.
Correct Approach
Use a Deployment for stateless programs, and keep StatefulSets for workloads that truly need stable identity or personal storage.
Problem
Believing that persistent disks are a backup, and taking no separate backups.
Why It’s Harmful
A deleted claim, a corrupt write or a lost zone destroys the only copy of the data.
Correct Approach
Take regular application-level backups or snapshots, store them outside the cluster, and rehearse restoring them.
Problem
Force-deleting stuck Pods casually to make problems disappear.
Why It’s Harmful
If the old Pod is still alive on an unreachable node, two members may share one identity and one disk, risking corrupted data.
Correct Approach
Confirm that the node and Pod are truly gone before forcing anything, and prefer restoring the node or draining it properly.
Problem
Running a single replica of a database and calling it highly available.
Why It’s Harmful
While the lone Pod is being replaced, the service is down. A StatefulSet with one member is stable, not resilient.
Correct Approach
Run several members with replication configured inside the database, spread across computers and zones.
22Best Practices and Beginner Mistakes
Small habits that keep stateful workloads calm.
Decide first whether you need a StatefulSet
Consider a managed database service or an operator before building your own. Running databases well is real work.
Choose storage deliberately
Pick a storage class with the speed, safety and expandability you need, and understand its zone behaviour.
Set thoughtful health checks
Use readiness to control the ordered start, gentle liveness checks, and a startup check for slow recovery.
Set resource requests and limits
Databases need reliable memory and processing power. Without settings, they may be evicted first under pressure.
Back up and rehearse restores
Automate backups, store them elsewhere, and practise recovery until it is routine.
Upgrade with a staged rollout
Use the partition to try a new version on one member first, watch it, and continue only when it behaves.
Without it, members cannot find each other by name, and clustered software fails to form a group.
Removing a storage claim can destroy a member’s data. Treat claim deletion as seriously as deleting the database itself.
Choosing a tiny disk because it is cheap leads to a full disk and a crashed database. Plan for growth and alert early.
23Real-World Examples
Where StatefulSets quietly hold important data.
A relational database with replicas
A primary member and followers each have their own disk and name. If the primary is lost, the software promotes a follower, and the replacement Pod returns as a follower with its old disk.
A message streaming system
Brokers need stable identities because clients and other brokers refer to them by name, and each broker holds its own share of the messages on its own disk.
A search and analytics cluster
Nodes in the cluster keep pieces of the search index on personal disks. Stable names let the cluster recognise a returning node and reuse its data.
A distributed coordination service
Small groups of servers that agree on configuration and leadership depend on stable member names and ordered start-up to form and keep their group.
A key-value store or cache with persistence
Members keep data on disk so a restart does not empty the cache, and each member knows which slice of data it owns.
A document database cluster
Replica set members are addressed by name in the database’s own settings. A steady name and steady disk mean a replacement rejoins without manual repair.
24Frequently Asked Questions
Quick answers to questions beginners ask most.
No. A Deployment with a shared disk still gives Pods random names and no personal disks. A StatefulSet gives each Pod a fixed name, its own disk and an ordered life.
Not necessarily. The internal address can change. What stays the same is the Pod’s name and its network name through the headless Service, so programs should always use names.
By default, the Pods are removed but the storage claims and disks are kept, to protect your data. Newer versions of Kubernetes let you choose a different retention behaviour, but keeping is the safe default.
With the default ordered policy, the next Pod is not created until the previous one is running and ready. If Pod zero is not ready, the rest wait. Check its readiness and logs.
Not by itself. It provides stable names, disks and ordering. High availability also needs several members, replication set up inside the database, spreading across computers, and tested failover.
Yes, using the parallel management policy. Names and disks still stay stable, but Pods start and stop together instead of one by one. Use it only if your software tolerates any start order.
It is a number that limits which Pods are updated. Only Pods with a number equal to or higher than it get the new version. Lowering it step by step gives a staged rollout.
Sometimes. A single-member database with one persistent disk can run under a Deployment with one replica, although updates then need care. Many teams use managed database services outside the cluster instead.
Because it tells Kubernetes the old Pod is definitely gone. If it is actually still running on an unreachable computer, a replacement could start with the same identity and disk, and two members might write to the same data.
Learn Pods, Deployments and Services, then storage volumes and claims. After that, practise with a small StatefulSet, deleting Pods and watching how names and disks come back. Seeing it happen makes the idea click.
25Summary and Key Takeaways
A StatefulSet is the Kubernetes tool for programs that must remember. It manages a group of numbered Pods and promises three steady things: a stable name for each member, a personal disk that follows it, and a careful order for starting, stopping and updating. It replaces lost Pods with the same identity, refuses to run two Pods with the same identity at once, and keeps disks safe by default. But it does not know your database’s own rules, and it does not replace backups, replication or monitoring. Use it when identity and storage truly matter, choose storage and health checks with care, and consider operators for serious databases.
Key Takeaways
- Stable identity — each Pod gets an ordered name, and a headless Service gives every member its own network name.
- Personal storage — a volume claim template creates a private disk for each Pod, and the replacement Pod reconnects to the same disk.
- Ordered life — Pods start in ascending order, stop in descending order, and are updated from the highest number down, with a partition for staged rollouts.
- Safety over speed — the at-most-one rule means a member is only replaced when the old one is surely gone, so force deletion needs great care.
- Not a complete database solution — the application must handle joining, leaving, replication, failover and backups, which operators can automate.
- Storage needs planning — choose storage classes wisely, watch zones and disk space, and remember that kept disks may hold old data.
- Choose it for the right reasons — use a Deployment for stateless programs, a StatefulSet for members with identity, and protect, back up and monitor everything.