StatefulSet Storage Patterns in Kubernetes

StatefulSet Storage Patterns in Kubernetes

A patient, plain-English guide to running applications that must remember things, covering how each pod gets its own disk, how that disk follows the pod, and which storage designs work best for which job.

Imagine two kinds of restaurant workers. The first is a person who takes orders at the counter. It does not matter which person does it today. If one goes home sick, another steps in, and customers notice nothing, because the counter worker remembers nothing between customers. The second is a head chef who keeps a private notebook of secret recipes. If that chef goes home sick and a stranger takes over, the notebook must be there too, or the restaurant loses years of knowledge. The stranger must also be recognized as “the head chef”, not just any cook.

Most Kubernetes applications are like the counter workers. They are stateless: any copy can replace any other, and nothing is lost when one disappears. But databases, message queues, and search engines are like the head chef. They are stateful: they keep valuable data, and each copy has a distinct identity and its own notebook. Kubernetes gives such applications a special manager called a StatefulSet, and a special way of attaching storage that keeps each pod’s notebook safe.

In this guide you will learn how StatefulSets give every pod a stable name and its own disk, how storage is created, attached, resized, and protected, and which storage patterns suit which kinds of applications. No earlier knowledge is needed. Every new term is explained the first time it appears, and there is no code to copy. Instead you will get pictures, analogies, and worked examples in plain words.

1Why Remembering Things Is Hard in Kubernetes

Kubernetes was built around the idea that pods are disposable. Data is the opposite of disposable.

Kubernetes treats pods like paper cups. If one gets dirty, spills, or is on a table that is being cleared, Kubernetes throws it away and pours a fresh one somewhere else. This makes the platform resilient. But the same disposability creates a problem for any application that keeps data. A container’s own filesystem lives and dies with the container. When a pod is replaced, everything written inside it disappears.

Storing data safely therefore needs two things at once. First, the data must live outside the pod, on a disk that survives the pod’s death. Second, when a replacement pod starts, it must find the same disk again, and know who it is, so it can rejoin its group properly. Solving both together is the job of the StatefulSet and its storage system.

Everyday analogy

Think of a hotel where guests keep personal belongings in a safe deposit box, and the box is tied to the room number, not to the guest’s shoes. When a housekeeper replaces the room’s furniture, the box stays. A new guest in room 12 finds the same box in the same place. A StatefulSet ties the box to the room’s number, not to the temporary furniture.

What can go wrong without the right design

Loss

Data vanishes with the pod

A database running with only container storage loses everything on its first restart.

Identity

Members forget who they are

Clustered systems need each member to have a fixed name. A random new name confuses the group and breaks elections.

Sharing

Two pods fight over one disk

Most disks can be used by only one machine at a time. Two copies writing the same disk can corrupt it.

Location

A disk lives in one place

A cloud disk exists in a single zone. A pod placed in another zone cannot use it.

Growth

Disks fill up

Databases grow. A disk that was large enough at launch may run out months later.

Protection

A disk is not a backup

A disk that survives a pod does not survive a deletion mistake, corruption, or a lost cloud account.

i
Good to know

Running databases on Kubernetes is a choice, not a requirement. Many teams use managed database services from their cloud provider instead. Understanding StatefulSet storage helps in both cases, because managed services and operators use the same ideas underneath.

2A Quick Storage Refresher

A handful of storage words are enough to understand everything that follows.

WordPlain meaningEveryday picture
VolumeStorage attached to a pod so its data can outlast a single containerA cupboard next to your desk
Persistent VolumeA piece of real storage in the cluster, such as a cloud diskA specific locker in a storage room
Persistent Volume ClaimA request for storage by an application: how big, what kind, how it may be usedA rental request form for a locker
Storage ClassA menu of storage types and the recipe for creating them on demandA menu offering “fast”, “standard”, or “cheap” lockers
ProvisionerThe program that creates the real disk when a claim arrivesThe storage room manager who prepares a locker
CSI driverA standard plugin that lets Kubernetes talk to any storage systemA universal adapter for different locker systems
Access modeWho may use the volume and how many at once“One person at a time” or “many people together”
SnapshotA saved picture of a volume at one momentA photograph of the locker’s contents
ZoneA separate data-center location within a cloud regionA different building on the same campus
Headless ServiceA special Service that gives each pod its own name instead of one shared addressA phone directory listing each person’s direct line

The most important relationship to remember is the chain: an application asks for storage with a claim, the storage system creates a volume to satisfy it, and the claim and volume are bound together. The pod mounts the claim, and the data lives on the volume. A StatefulSet automates creating a separate claim for every pod.

Everyday analogy

You fill in a rental form asking for a medium locker (the claim). The manager finds or builds a suitable locker (the volume) and writes your name on it (binding). You then carry your key (the mount) wherever you go, and always open the same locker.

3What Is a StatefulSet?

A StatefulSet is a Kubernetes manager for pods that need stable names, stable storage, and orderly starting and stopping.

A StatefulSet looks after a group of pods built from one template, much like a Deployment does. But it makes three extra promises that a Deployment does not. First, every pod gets a permanent, predictable name with a number: the first is number zero, the next is number one, and so on. Second, every pod gets its own storage, which stays attached to that name even if the pod is replaced. Third, pods are created, updated, and removed in a careful order rather than all at once.

What it is, why it exists, where it is used

What it is: a workload manager for stateful applications, giving each pod a sticky identity and its own storage.

Why it exists: because clustered data systems need members that can be told apart, found by name, and reunited with their own data after any restart.

Where it is used: for databases, message brokers, search clusters, coordination services, and any application where each copy keeps its own state.

Everyday analogy

A Deployment is like a pool of interchangeable taxi drivers: any driver can take any car. A StatefulSet is like a school with numbered classrooms and named teachers. If teacher number three is absent, the substitute takes over classroom three, using classroom three’s books and roster. The classroom identity and its belongings remain fixed.

!
Watch out

A StatefulSet does not make an application safe or highly available by itself. It provides identity and storage. The application, such as a database, must still replicate its data and handle failures. Think of the StatefulSet as the stage, and the application as the actor.

4Deployment and StatefulSet Compared

The best way to understand a StatefulSet is to see how it differs from the Deployment you already know.

flowchart LR
    subgraph DEP["Deployment: interchangeable pods"]
        D1["Pod with random name a1x9"] --> DV["One shared volume or none"]
        D2["Pod with random name b7k2"] --> DV
        D3["Pod with random name c4m8"] --> DV
    end
    subgraph STS["StatefulSet: numbered pods with their own disks"]
        S0["Pod db-0"] --> V0["Volume data-db-0"]
        S1["Pod db-1"] --> V1["Volume data-db-1"]
        S2["Pod db-2"] --> V2["Volume data-db-2"]
    end
    
Figure 1: Deployment pods are interchangeable. StatefulSet pods are numbered and each owns a disk.
FeatureDeploymentStatefulSet
Pod namesRandom suffixes that change on every replacementFixed, numbered names that never change
Network identityShared Service address onlyEach pod also has its own stable DNS name
StorageUsually none, or one shared volumeA separate volume for every pod, created automatically
Start and stop orderAll at once, in any orderOne at a time in order, by default
Replacement behaviorAny new pod takes the place of an old oneA new pod gets the same name and the same volume
UpdatesRolling replacement in any orderReverse order, from the highest number down, with fine control
Best forWeb servers, APIs, stateless workersDatabases, brokers, clustered stores
Everyday analogy

Hotel rooms with numbered doors and personal safes are like a StatefulSet. A pool of shared bicycles with no owner is like a Deployment. You do not care which bicycle you get, but you care very much which room and safe are yours.

i
Practical hint

If an application does not need a stable name and does not keep private data per copy, choose a Deployment. StatefulSets add operational care, and using them where they are not needed only adds work.

5Architecture and Components

Several small parts cooperate to give each pod a name, a disk, and a place to run.

flowchart TD
    USER["Engineer or pipeline"] -->|"Creates StatefulSet"| API["API Server"]
    API --> SSC["StatefulSet Controller"]
    SSC -->|"Creates numbered pod"| POD["Pod db-0"]
    SSC -->|"Creates claim from template"| PVC["PersistentVolumeClaim data-db-0"]
    PVC --> PVCC["Volume binding controller"]
    PVCC --> SC["StorageClass"]
    SC --> CSI["CSI provisioner"]
    CSI --> DISK["Real disk in cloud or data center"]
    PVCC --> PV["PersistentVolume"]
    PV --> DISK
    POD --> SCH["Scheduler picks a node"]
    SCH --> NODE["Node and kubelet"]
    NODE -->|"Attaches and mounts"| DISK
    HS["Headless Service"] -->|"Publishes db-0 DNS name"| POD
    
Figure 2: From a StatefulSet to a running pod with its own mounted disk and its own name.
Manager

StatefulSet controller

Creates pods in order with fixed names, and creates one claim per pod from a template. It also replaces pods when they disappear.

Request

PersistentVolumeClaim

The pod’s rental form for storage. There is one per pod, named after the template and the pod’s number.

Menu

StorageClass

Describes the kind of storage available and which driver creates it, plus rules about timing and deletion.

Builder

CSI driver and provisioner

Talks to the real storage system to create, attach, resize, and snapshot disks.

Storage

PersistentVolume

The cluster’s record of a real disk, tied to one claim once bound.

Directory

Headless Service

Publishes a separate DNS name for every pod, so members can find each other by number.

Placement

Scheduler

Chooses a node for each pod, taking into account where its disk lives.

Executor

Kubelet on the node

Attaches the disk to the node, prepares its filesystem, and mounts it into the container.

Everyday analogy

Think of a boarding school. The headmaster (the StatefulSet controller) assigns numbered beds. The bursar (the storage class) offers locker types. The storeman (the CSI driver) builds each locker. The receptionist (the headless Service) keeps a directory of which student sleeps in which bed. Each student finds the same bed and the same locker every term.

6The Anatomy of a StatefulSet

A StatefulSet has a small number of parts. Learning them once makes every StatefulSet easy to read.

PartWhat it saysWhy it matters
ReplicasHow many numbered pods to runSets the number of members and disks
Service nameThe headless Service that gives pods their DNS namesWithout it, pods have no stable individual names
Selector and labelsHow the StatefulSet finds its own podsMust match the pod template’s labels
Pod templateThe description of each pod: containers, settings, mountsDefines what runs
Volume claim templatesThe recipe for the per-pod storage claimsDefines each pod’s private disk: size, class, access
Pod management policyWhether to start pods one by one or togetherOrdered by default; parallel for faster startup
Update strategyHow new versions replace old podsRolling with a partition, or manual on delete
Claim retention policyWhat happens to claims when the set is scaled down or deletedDecides whether data is kept or removed automatically
Minimum ready secondsHow long a new pod must stay ready before counting as availableSlows updates to catch late failures
Everyday analogy

Think of a school’s enrollment plan: how many classrooms, which corridor names to use, what each classroom contains, what locker each student receives, in what order students arrive in the morning, and what happens to their lockers when they leave. A StatefulSet writes all of this down in one place.

!
Watch out

Several fields of a StatefulSet cannot be changed after creation, especially the storage templates. Plan sizes, classes, and names carefully, because fixing them later takes special steps.

7Stable Identity: Names, Numbers, and the Headless Service

Every StatefulSet pod carries a name that never changes, and a matching address that other pods can look up.

A StatefulSet named “db” with three replicas produces pods named “db-0”, “db-1”, and “db-2”. If db-1 is deleted or crashes, the replacement is again called “db-1”. It is not “db-4” or a random word. The number is called the ordinal. Ordinals let applications answer the question “which member am I?” simply by reading their own name. A database can decide that member zero is the first primary, or that members one and two join it.

The headless Service

A normal Service gives one shared address for a group and sends each request to any member. A headless Service does not have a shared address. Instead, it publishes separate DNS records for each pod, so “db-0” and “db-1” each have their own name that stays the same even when the pod’s underlying address changes. A StatefulSet must name a headless Service to provide these per-pod names.

Name you look upWhat you getTypical use
The Service name itselfThe addresses of all ready pods, or a chosen oneClients that can talk to any member
A pod’s own name under the ServiceThat specific pod’s current addressMembers contacting each other directly
A separate ordinary Service in frontOne shared address that balances across podsApplications that just want to read data from any replica
Everyday analogy

A company switchboard number reaches whichever agent is free. That is a normal Service. A staff directory listing “Room 3 direct line” always reaches the person in room three, whoever sits there today. A headless Service is that directory.

i
Practical hint

Many stateful systems use two Services: a headless one for members to find each other, and an ordinary one for clients. This keeps internal chatter and public access neatly separated.

8Volume Claim Templates: One Disk per Pod

The signature storage feature of a StatefulSet is a template that automatically creates a separate claim for every pod.

A volume claim template is a recipe, written once, describing the storage each pod needs: how large, which storage class, and which access mode. For every pod the StatefulSet creates, it uses the recipe to produce a separate claim. The claim’s name combines the template’s name, the StatefulSet’s name, and the pod’s number. So a template called “data” in a StatefulSet called “db” yields claims named “data-db-0”, “data-db-1”, and “data-db-2”.

The link between name and disk

When a pod named “db-1” starts, the StatefulSet looks for a claim named “data-db-1”. If it exists, the pod is reunited with it, with all the data. If it does not, a new one is created. This name-based matching is how a replacement pod finds the same disk as the pod it replaces.

1

Template written once

You describe the desired storage in the StatefulSet’s template section.

2

A claim is made per pod

The controller creates one claim for each new pod number, named from the template and the pod.

3

A disk is provisioned

The storage system creates a real disk to satisfy the claim.

4

The pod mounts its claim

The pod starts and mounts the disk at the path the template specifies.

5

Replacement pods rejoin the same claim

If the pod is replaced, the new pod with the same number attaches to the same claim, and so to the same data.

Everyday analogy

A school issues each numbered desk a labeled drawer. If the student sitting at desk five changes, the drawer stays labeled “desk five” and the new student sees the same contents. The drawer belongs to the desk, not the student.

!
Watch out

Claims created from the template are ordinary, independent objects once created. If you later change the template, existing claims are not modified. Only newly created claims use the new recipe.

9How It Works Internally: Creating Pods and Claims

Follow a new StatefulSet from creation to a running, storage-backed pod.

sequenceDiagram
    participant U as Engineer
    participant API as API Server
    participant SSC as StatefulSet Controller
    participant PVCC as Binding and Provisioning
    participant SCH as Scheduler
    participant K as Kubelet
    U->>API: Create StatefulSet with 3 replicas
    API->>SSC: Notify of new StatefulSet
    SSC->>API: Create claim data-db-0
    SSC->>API: Create pod db-0
    PVCC->>PVCC: Wait for first pod placement if class says so
    SCH->>API: Place db-0 on node in zone A
    PVCC->>API: Provision disk in zone A and bind claim
    K->>K: Attach disk to node, mount into container
    K-->>API: db-0 is running and ready
    SSC->>API: Create claim data-db-1 and pod db-1
    Note over SSC,K: Repeat in order for db-2
    
Figure 3: The controller creates each pod’s claim and pod, then waits for readiness before moving on.
1

The controller creates pod zero

By default, it creates one pod at a time, beginning with number zero, together with its claim.

2

The claim waits or provisions

Depending on the storage class, the disk is created immediately, or only after the scheduler chooses a node, so that it lands in the right zone.

3

The kubelet attaches and mounts

The disk is attached to the chosen node, formatted if it is new, and mounted into the container.

4

The pod becomes ready

The application starts, and its readiness probe passes.

5

The controller advances

Only when pod zero is running and ready does it create pod one, and so on. This gives applications a predictable start order.

6

Steady state watching

The controller keeps watching. If any pod vanishes, it recreates the same numbered pod, which reattaches to its same claim.

Everyday analogy

Think of a school on its first morning. The caretaker opens classroom zero, checks the lights and desks, and only then opens classroom one. If a classroom is later closed for repair, the caretaker reopens the same numbered room, with the same lockers, once it is ready.

10The Life of a Claim: Data Flow and Lifecycle

A storage claim passes through clear stages, and knowing them makes stuck volumes easy to diagnose.

stateDiagram-v2
    [*] --> Pending
    Pending --> Bound : "Disk created and matched"
    Pending --> Pending : "Waiting for a node or capacity"
    Bound --> InUse : "A pod mounts the claim"
    InUse --> Bound : "Pod stops or is replaced"
    Bound --> Resizing : "Larger size requested"
    Resizing --> Bound : "Disk and filesystem expanded"
    Bound --> Terminating : "Claim deleted"
    InUse --> Terminating : "Claim deleted while in use"
    Terminating --> Released : "Pod stops using it"
    Released --> [*] : "Disk deleted or kept, per policy"
    
Figure 4: The states a storage claim moves through during its life.
StateWhat it meansWhat to check if stuck
PendingNo disk matched yetStorage class exists, provisioner healthy, capacity available, zone has a node
BoundA disk is matched to the claimNormal and healthy
In useA pod has mounted itNormal; protects the claim from accidental deletion
ResizingA larger size was requestedWhether the class allows expansion, and whether a restart is needed
TerminatingDeletion requested but the disk is protected while in useWhich pod still uses it
Released or lostThe claim is gone, or its disk cannot be foundReclaim policy and the cloud console
Everyday analogy

A locker rental goes from “form submitted” to “locker assigned”, then “in use” while you carry the key, and at the end “returned”. The manager will not take back a locker whose key is still in your pocket. Kubernetes similarly refuses to fully remove a claim while a pod is using it.

11Storage Classes, Provisioners, and CSI

A storage class is the menu that decides what kind of disk each claim receives.

A storage class names a type of storage, such as “fast solid-state disk” or “standard magnetic disk”, together with the driver that can create it and settings that control its behavior. When a claim names a class, the driver creates a disk of that type on demand. This is called dynamic provisioning, and it replaces the old way, where an administrator pre-created every disk by hand.

Drivers follow a standard called the Container Storage Interface, or CSI. Because of it, a single set of Kubernetes objects works with cloud disks, network file systems, and storage appliances alike. Each vendor supplies a CSI driver that translates Kubernetes requests into its own language.

Setting

Type and performance

Which disk technology, and how many operations per second and how much throughput it offers. Classes often map to tiers.

Setting

Binding mode

Whether the disk is created at once, or only after the pod is placed on a node. This affects zones.

Setting

Reclaim policy

Whether a disk is deleted or kept when its claim is deleted.

Setting

Expansion allowed

Whether claims of this class can later be enlarged.

Setting

Encryption

Many classes can request encrypted disks, using keys managed by the provider or by you.

Setting

Filesystem type

Which filesystem to place on a new disk.

Everyday analogy

A restaurant menu offers fast, hearty, or light dishes. Each order leads to a different kitchen station and price. A storage class is the menu entry, and the CSI driver is the kitchen station that prepares it.

!
Watch out

Many clusters have a default storage class that is chosen when a claim names none. It may not suit databases: it could be slow, unencrypted, or set to delete disks when claims are removed. Always choose a class deliberately for important data.

12Binding Modes, Zones, and Where the Disk Lives

A cloud disk exists in one place. If the pod cannot reach that place, it cannot start.

Most cloud block disks live in a single zone. A pod placed on a machine in a different zone cannot attach it. This is a source of the most common stuck-pod problem in stateful systems. Kubernetes gives two binding modes to handle it.

Binding modeWhen the disk is createdResult
ImmediateAs soon as the claim is made, before any pod existsThe disk lands in a zone chosen without regard to where the pod will run. The pod may later be forced into that zone, or fail to fit
Wait for first consumerOnly after the scheduler chooses a node for the podThe disk is created in the same zone as the pod. This is the safer choice for zone-bound disks
flowchart TD
    A["Pod db-1 needs to start"] --> B{"Does its claim already have a disk?"}
    B -->|No| C["Scheduler picks a node"]
    C --> D["Disk is created in that node's zone"]
    D --> E["Pod starts"]
    B -->|Yes| F{"Is there a node with room in the disk's zone?"}
    F -->|Yes| G["Pod is placed on that node"]
    G --> E
    F -->|No| H["Pod stays pending"]
    H --> I["Fix: add capacity in that zone, or restore from a snapshot elsewhere"]
    
Figure 5: Once a disk exists in a zone, its pod is tied to that zone.
Everyday analogy

Suppose your locker is in the east building. On the day the east building is full of guests, you cannot use your locker by sitting in the west building. If lockers are assigned only after you choose which building you will work in, you always get one next to your desk.

i
Practical hint

Ensure that every zone in which a stateful pod might land keeps spare capacity. Otherwise a node failure can leave a pod pending, because the only zone where its disk exists is full.

13Access Modes: Who May Use the Disk?

An access mode says how many machines may use a volume at once, and whether they may write.

ModeMeaningTypical storageTypical use
Read-write, one nodeOne machine may read and write at a time; several pods on that same machine may shareCloud block disksThe everyday choice for databases
Read-write, one podExactly one pod may use it, even on the same machineNewer CSI block disksStrict single-writer protection
Read-only, many nodesMany machines may read, none may writeShared file systems, some snapshotsShared reference data
Read-write, many nodesMany machines may read and write togetherNetwork file systems and shared storageShared content, with careful application design

For StatefulSets, the usual pattern is a private, single-writer disk for each pod. That matches how most databases work: each member owns its own files. Sharing one disk among several database members that each expect to own it invites corruption.

Everyday analogy

A private notebook is written by one person. A shared whiteboard can be written by many at once, but people need rules so they do not scribble over each other. Most databases are notebooks, not whiteboards.

!
Watch out

Being able to mount a disk from many machines does not mean the application handles concurrent writers safely. Only use shared writable storage when the application was designed for it.

14Reclaim Policies and What Happens on Scale-Down or Delete

Deleting the wrong thing can erase data forever. Understanding the defaults protects you.

Two settings decide what happens to data when things are removed. The reclaim policy belongs to the storage class or volume, and decides what happens to the real disk when a claim is deleted: either the disk is deleted along with its data, or it is retained so it can be recovered by hand. The claim retention policy belongs to the StatefulSet in newer versions, and decides whether claims themselves are removed when the set is scaled down or deleted.

flowchart TD
    A["StatefulSet is scaled down or deleted"] --> B{"Claim retention policy?"}
    B -->|"Retain (default)"| C["Claims stay, with their data"]
    B -->|"Delete"| D["Claims are deleted"]
    D --> E{"Reclaim policy of the storage class?"}
    E -->|"Delete"| F["Disk and data are destroyed"]
    E -->|"Retain"| G["Disk is kept, claim is gone; recovery by hand"]
    C --> H["Scaling back up reattaches the same data"]
    
Figure 6: Two policies together decide whether data survives scale-down or deletion.
CombinationEffect of deleting the StatefulSetEffect of scaling down
Retain claims (default), any reclaim policyClaims and disks remainClaims and disks remain; scaling up reuses them
Delete claims, class reclaim policy deleteClaims and disks are destroyedRemoved pods’ claims and disks are destroyed
Delete claims, class reclaim policy retainClaims removed; disks remain for manual recoverySame
Everyday analogy

When a student leaves a school, one rule says whether their locker is kept until they return or emptied at once. A second rule says whether the locker’s contents are thrown away or boxed and stored in the basement. The safest combination keeps things until a person deliberately decides otherwise.

i
Practical hint

For important data, keep the default of retaining claims and set the class to retain disks. Then clean up deliberately, and only after confirming that backups exist. The retention options are conveniences for test environments, not substitutes for backups.

15Ordering and Pod Management Policy

By default, a StatefulSet does things one step at a time, in a fixed order. This is a feature, and sometimes a speed limit.

The default policy, called ordered ready, creates pods from the lowest number to the highest, waiting for each to be running and ready before starting the next. When scaling down or deleting, it removes them in reverse order, from the highest number to the lowest, and waits for each to finish. This suits systems where member zero must start first, such as a primary that others copy from, or where the group must never lose several members at once.

The alternative policy, parallel, launches or removes all pods at the same time without waiting. This speeds up large groups whose members do not depend on start order, such as search shards or cache nodes that discover each other on their own.

PolicyStartupShutdownBest for
Ordered readyOne at a time, waiting for ready, lowest number firstOne at a time, highest number firstDatabases with a primary, systems needing careful bootstrapping
ParallelAll at onceAll at onceLarge groups of peers that do not need ordering
Everyday analogy

An orchestra tunes to the first violin, then each section joins one by one. That is ordered startup. A crowd of street performers can simply begin playing whenever they arrive. That is parallel startup. The right choice depends on whether the group needs a leader’s note to begin.

!
Common trap

With ordered ready, one stuck pod blocks everything after it. If pod one never becomes ready, pod two is never created. This is safe, but it can look like the whole set has stalled. Check the lowest-numbered pod that is not ready first.

16Updating a StatefulSet Safely

A careful update replaces one member at a time and gives you a way to test on a few before trusting all.

When you change the pod template, for example to a new version of the database software, the StatefulSet replaces pods according to its update strategy. The default is a rolling update that moves from the highest number to the lowest: pod two first, then pod one, then pod zero. Each replacement keeps the same name and reattaches to the same disk, and the controller waits for it to be ready before touching the next.

Two tools for control

  • Partition. You can set a number below which pods are not updated. With five members and a partition of three, only pods three and four are updated; pods zero to two stay on the old version. Lowering the partition step by step lets you canary the new version on a few members first.
  • On delete. A manual strategy in which nothing is replaced automatically. Each pod is updated only when you delete it yourself. This gives total control, at the cost of effort.
flowchart TD
    A["New version defined"] --> B["Partition set high: only top pods eligible"]
    B --> C["Highest numbered pod is replaced"]
    C --> D{"Ready and healthy for the wait time?"}
    D -->|No| E["Pause, investigate, roll back the change"]
    D -->|Yes| F["Lower the partition to include the next pod"]
    F --> G{"All pods updated?"}
    G -->|No| C
    G -->|Yes| H["Update complete"]
    
Figure 7: A staged update that moves the partition down one pod at a time, checking health at each step.
Everyday analogy

A school introducing a new textbook might start with one class. If it works well, the next class adopts it, and then the rest. The partition is the line on the corridor wall marking which classrooms have switched.

i
Practical hint

Combine updates with a short minimum-ready wait and a good readiness check, so that a member that starts but fails a moment later is caught before the next one is touched. For databases, make readiness mean “caught up with the group”, not merely “process started”.

17Growing Volumes: Resizing Storage

Databases only ever grow. Plan for the day the disk is nearly full, before it arrives.

Enlarging a volume is supported by many storage classes, if their expansion setting is enabled. You request a larger size on the claim, the storage system grows the disk, and the filesystem is expanded to use the new space. Depending on the driver, this may happen while the pod runs, or may need a restart of the pod.

The tricky part with StatefulSets is that the volume claim template cannot be edited once the set exists. Changing the template will not resize the existing claims, and the platform refuses to modify that section. The usual approach is to enlarge each claim directly, one by one, and then recreate the StatefulSet object itself while leaving its pods and claims running, so that its template records the new size for future pods.

1

Check that the class allows expansion

If it does not, growing in place is not possible, and you must migrate data to a larger volume instead.

2

Take a backup or snapshot first

Resizing is usually safe, but a fresh backup costs little compared with the risk.

3

Request the larger size on each claim

Do one claim at a time, watching that it reaches its new size before moving on.

4

Wait for the filesystem to grow

Some drivers expand it while running. Others expand it when the pod next restarts.

5

Update the StatefulSet definition

Recreate the object with the new size in its template, without removing the running pods or claims, so future members match.

6

Confirm and watch

Check the free space reported by the application, and set alerts earlier next time.

!
Watch out

Disks generally can be enlarged but not shrunk. An oversized disk cannot be reduced later, and you pay for it. Choose a size with room to grow, but not wildly beyond your needs, and watch usage trends.

18When a Node Fails: Recovery of Stateful Pods

A StatefulSet is cautious. It would rather wait than risk two pods writing the same disk.

When a node stops responding, Kubernetes cannot tell whether the machine has really died or is only cut off from the network. If the machine is still running, the old pod might still be writing to its disk. Starting a second pod with the same name and the same disk would then risk two writers and corrupted data. To avoid that, a StatefulSet guarantees at most one pod with a given identity at any time. It will not create the replacement until it is sure the old one is gone.

sequenceDiagram
    participant N as Failed node
    participant CP as Control plane
    participant SSC as StatefulSet Controller
    participant D as Cloud disk
    participant N2 as Healthy node
    N--xCP: Stops reporting
    CP->>CP: Marks node not ready after a grace time
    CP->>CP: Marks pod db-1 as terminating but cannot confirm
    Note over SSC: Will not create a second db-1 while the first might be alive
    CP->>CP: Node confirmed gone, or force deleted by an operator
    SSC->>CP: Create replacement db-1
    D->>D: Detach from failed node, possibly after a wait
    D->>N2: Attach to healthy node
    N2-->>CP: db-1 running with same data
    
Figure 8: A replacement starts only after the old pod is confirmed gone and the disk is released.

Why recovery can take a while

  • Detection delay. The cluster waits some time before deciding that a node is not ready.
  • Terminating limbo. A pod on an unreachable node remains “terminating” until the node returns or is confirmed removed.
  • Disk release. The cloud may hold the disk attached to the dead machine for a few minutes, causing errors saying the volume is already in use.
  • Placement. The replacement must land in the disk’s zone, where capacity must exist.
Everyday analogy

If a teacher stops answering the phone, the head teacher will not hand classroom three’s key to a substitute until it is certain the first teacher has left the room. Otherwise two teachers might teach two lessons in one room. The caution avoids chaos at the price of a delay.

i
Practical hint

Application-level replication is your real speed-up. If the database has replicas that can take over, users are served by those while the stuck pod waits. The StatefulSet restores the lost member later, in the background.

19Network Disks Versus Local Disks

The biggest storage decision is whether the disk is separate from the machine or part of it.

Network-attached disks

  • Survive the loss of the machine; can be reattached to another one.
  • Easy to snapshot, resize, and manage through the cloud provider.
  • Slightly higher latency and limited operations per second per disk.
  • Tied to a zone, and attachment takes time.

Local disks on the machine

  • Very fast, with low latency and high throughput.
  • Data is lost or stranded if the machine fails or is replaced.
  • Pods are tied to the specific machine that holds the data.
  • Requires application-level replication to be safe.
NeedBetter fitReason
General databases with moderate loadNetwork disksSimplicity and data survival outweigh raw speed
Very high speed search or analytics nodes with replicationLocal disksSpeed matters, and copies exist elsewhere
Single-copy critical dataNetwork disks with backupsLosing a machine must not lose the data
Cache or scratch data that can be rebuiltLocal or temporary storageLoss is acceptable and speed is valuable
Everyday analogy

A notebook kept in your own desk drawer is very fast to reach, but if the desk is thrown out, the notebook goes with it. A notebook kept in a shared archive room takes longer to fetch, but survives any change to your desk. Which you choose depends on how precious the notes are.

20A Catalogue of Storage Patterns

Real systems reuse a few well-tested designs. Knowing the catalogue lets you choose instead of invent.

flowchart TD
    A["What does the application need?"] --> B{"Does each member own its own data?"}
    B -->|Yes| C{"Can the app replicate data between members?"}
    C -->|Yes| D["Pattern 1: Private disk per pod with app replication"]
    C -->|No| E["Pattern 2: Private disk per pod plus strong backups"]
    B -->|No| F{"Must many pods share the same files?"}
    F -->|Yes| G["Pattern 3: Shared file storage"]
    F -->|No| H{"Can the data be rebuilt?"}
    H -->|Yes| I["Pattern 4: Temporary or local scratch storage"]
    H -->|No| J["Reconsider design: use a managed service or object storage"]
    D --> K["Add: snapshots, sidecar backups, zone spreading"]
    E --> K
    
Figure 9: A simple path for choosing a storage pattern.
Pattern 1

Private disk per pod with app-level replication

The standard for clustered databases. Each member owns a disk, and the software copies data between members.

Pattern 2

Private disk plus strong backups

For single-copy systems. The disk survives pod loss, and backups protect against everything else.

Pattern 3

Shared file storage

Many pods read and write the same files, such as media uploads. Requires storage designed for sharing.

Pattern 4

Temporary scratch storage

Fast, disposable space for caches and temporary files, lost when the pod ends.

Pattern 5

Separate volumes for data and logs

Databases write logs constantly. Putting them on a different volume avoids competition and allows independent sizing.

Pattern 6

Object storage for bulk and backups

Large files and backups go to cheap, durable object storage, and only hot data stays on disks.

Pattern 7

Snapshot and clone to grow the group

New members start from a snapshot of an existing one, then catch up, saving hours of copying.

Pattern 8

Operator-managed storage

A specialized controller handles disks, backups, resizing, and failover for a specific database.

21Pattern in Depth: A Private Disk per Pod with Replication

This is the workhorse pattern. Understanding its moving parts explains most of what StatefulSets are for.

In this design, each member of a database has its own disk, and the software keeps the members in step. One member, the primary, accepts writes. The others, the replicas, copy those writes and can serve reads. If the primary fails, a replica is promoted. Kubernetes supplies stable names and disks. The database supplies the copying and the promotion.

flowchart LR
    C["Client application"] -->|"Writes"| P["db-0 Primary"]
    C -->|"Reads"| R1["db-1 Replica"]
    C -->|"Reads"| R2["db-2 Replica"]
    P -->|"Sends changes"| R1
    P -->|"Sends changes"| R2
    P --- VP["Volume data-db-0 in zone A"]
    R1 --- V1["Volume data-db-1 in zone B"]
    R2 --- V2["Volume data-db-2 in zone C"]
    HS["Headless Service"] -.->|"Names for each member"| P
    HS -.-> R1
    HS -.-> R2
    
Figure 10: Three members, three disks in three zones, one headless Service for names.
ConcernWho is responsibleHow
Stable member namesStatefulSet and headless ServiceNumbered pods with their own DNS names
Each member’s diskStatefulSet and storage classClaim per pod, reattached after replacement
Copying data between membersThe database softwareReplication protocol
Choosing a new primaryThe database software or an operatorElection or managed failover
Spreading across zonesScheduling rulesSpread constraints and anti-affinity
Protecting against deletion mistakesBackupsSnapshots and exports to separate storage
Everyday analogy

Three branch libraries each keep their own copy of the catalog. The main branch records new books and sends updates to the others each evening. If the main branch closes, a second branch takes over. Each library needs its own building and shelves (the disks), and the head office supplies the update process (replication).

i
Practical hint

Spread members across zones so that a zone failure removes only one copy. Also check that the disks can be found in those zones after a failure, since each disk stays in its own zone.

22Pattern in Depth: Shared Storage and Its Cautions

Sometimes several pods need the same files. This is possible, but it changes the rules.

A shared file system can be mounted by many pods on many machines at once. This suits content such as uploaded images, shared configuration files, or build outputs. Because the volume is shared, one claim can serve a whole Deployment, and no per-pod claim is needed. It also means the StatefulSet’s main storage feature, one disk per pod, is not the point.

Good fit

Media and uploads

Many web pods serve and store user files in one place.

Good fit

Shared reference data

Read-only data, such as models or dictionaries, used by many pods.

Poor fit

Databases that expect their own files

Most databases assume exclusive access and use locking that behaves poorly on network file systems.

Poor fit

High rate of small writes

Network file systems can be slow under heavy small-file workloads.

Caution

Concurrent writers

Applications must coordinate to avoid overwriting each other’s files.

Caution

Single point of failure

The shared system becomes a dependency for every pod. Its availability limits yours.

Everyday analogy

A shared whiteboard in an office works well for announcements that anyone may read and post. It is a poor place to keep each person’s private diary. Choose the whiteboard for shared content and separate notebooks for private data.

23Pattern in Depth: Init Containers and Sidecars

Small helper containers prepare the disk before the main application starts and look after it while it runs.

Init containers: getting ready

An init container is a short-lived helper that runs to completion before the main containers start. In stateful systems it is commonly used to prepare a new disk: fix ownership and permissions, generate a configuration file from the pod’s number, or copy initial data from a snapshot or a peer. Because the pod’s name contains its ordinal, the init container can decide whether this member should start as a primary or a replica.

Sidecars: looking after the disk

A sidecar is a second container that runs alongside the main one for the pod’s whole life and shares its volumes. Typical sidecar jobs for storage include streaming backups to object storage, shipping log files, exporting metrics about disk use, and running small checks.

HelperWhen it runsTypical jobs
Init containerBefore the application starts, once per pod startSet permissions, generate settings from the ordinal, seed data
SidecarAlongside the application throughout its lifeBackups, log shipping, metrics, config reload
Everyday analogy

Before a chef begins service, an assistant sets out the ingredients and labels the stations. That is the init container. During service, a second assistant washes dishes and records what was used. That is the sidecar.

!
Watch out

An init container that runs on every start must be safe to repeat. It should never wipe or reinitialize a disk that already holds data. Check for existing data before doing any setup.

24Pattern in Depth: Snapshots and Clones

A snapshot is a fast, frozen picture of a disk, and a clone is a new disk made from one.

The CSI standard supports volume snapshots where the driver allows it. A snapshot request produces a point-in-time copy, often within seconds, because many storage systems record only changes after that moment. From a snapshot you can create a new claim with the same contents, which is called restoring or cloning. Some drivers also clone one volume directly into another.

Use

Quick recovery points

Take a snapshot before a risky change such as an upgrade or a schema change.

Use

Adding a replica quickly

Restore a new member’s disk from a snapshot of an existing one, then let it catch up on recent changes.

Use

Test environments

Create a copy of production data in a separate namespace to test upgrades safely, respecting data privacy rules.

Caution

Consistency

A snapshot taken while the database is writing may capture a half-finished state. Use application hooks or quiet moments to ensure consistency.

Caution

Same failure domain

Snapshots often live in the same cloud account and region. They do not protect against account loss or regional disaster.

Caution

Driver support varies

Not every storage driver supports snapshots or cloning. Check before relying on them.

Everyday analogy

A snapshot is like photographing an exercise book page before you start erasing and rewriting. If you make a mistake, you can copy the page back. But if the photo is stored in the same drawer that catches fire, it will not help. Keep at least one copy elsewhere.

25Backup and Restore: The Part People Skip

A persistent disk protects you from a pod dying. Only a backup protects you from everything else.

flowchart LR
    APP["Database pods"] --> SNAP["Volume snapshots"]
    APP --> DUMP["Logical export by sidecar or job"]
    APP --> WAL["Continuous change log shipping"]
    SNAP --> OBJ["Object storage in another account or region"]
    DUMP --> OBJ
    WAL --> OBJ
    OBJ --> TEST["Regular restore test in a scratch namespace"]
    TEST --> OK["Verified recovery time and data loss window"]
    
Figure 11: Several kinds of backup flow into separate storage, and restore tests prove that they work.
Backup typeWhat it capturesStrengthWeakness
Volume snapshotThe disk at one momentFast and simpleOften in the same place as the original; consistency needs care
Logical exportThe data as portable recordsWorks across versions and platformsSlower for large data; a moment in time only
Continuous log shippingEvery change as it happensAllows recovery to any point in timeNeeds more setup and storage
Replica in another regionA live copy far awayFast failover after a disasterCopies mistakes too; it is not a backup against bad deletes

Two numbers to decide first

  • How much data can we lose? Measured in minutes or hours. This sets how often backups must run.
  • How long can we be down? This sets how fast your restore process must be, and therefore how often you must practice it.
i
Practical hint

A backup that has never been restored is only a hope. Schedule regular restores into a scratch namespace, time them, and record the results. A failed test in calm conditions is a gift.

26Permissions, Ownership, and Temporary Volumes

Many storage problems turn out to be simple file ownership problems.

A new disk is often owned by the machine’s administrator. If your application runs as an ordinary, unprivileged user, as it should, it may be unable to write to the new disk. Kubernetes helps through a pod-level setting that assigns a group to the volume’s files, so the application’s user can write. On large disks with many files, changing ownership at every start can be slow, so newer versions let you control when it happens.

Ownership

Group setting for the volume

Lets an unprivileged application own files it creates, without running as an administrator.

Speed

Avoiding slow recursive changes

Changing ownership of millions of files at each restart can delay startup. Options exist to do it only when the top level differs.

Temporary

Scratch volumes

A temporary volume lives as long as the pod. It suits caches and working files, never the primary copy of important data.

Danger

Host paths

Mounting a directory of the machine directly ties the pod to that machine and weakens isolation. Avoid it for application data.

Read-only

Read-only mounts for safety

Mount configuration and reference data read-only, so a bug cannot damage them.

Ephemeral

Generic ephemeral volumes

A pod can request a private disk that is created with the pod and deleted with it, using the same storage classes as permanent claims.

Everyday analogy

A newly built cupboard belongs to the builder, and the tenant cannot open the drawers until the builder hands over the key. Setting the group is like giving the tenant the key, so the tenant can use the cupboard without becoming the building’s owner.

27Performance and Scalability

Storage speed is often the true limit of a database. It deserves early measurement.

IOPS
how many small reads and writes per second a disk allows
MB/s
how much data per second can flow to or from the disk
ms
how long one operation takes, the latency
Sizing

Performance can depend on size

On some clouds, larger disks receive more operations per second. A small disk may be slow even when barely full.

Class

Choose the tier deliberately

Fast classes cost more. Match the class to the workload: busy transaction logs need speed, archives do not.

Throttling

Limits at the machine level

A machine can cap the total storage traffic for all its disks. Several busy databases on one machine can compete.

Layout

Separate hot paths

Put write-heavy logs on their own volume so they do not slow the main data files.

Scaling

Adding members

More members can spread reads. Writes to a single primary do not scale that way and need sharding or a bigger disk.

Startup

Attach and mount time

Attaching, checking, and mounting large disks takes time, especially on failure recovery. Plan for it in your recovery targets.

Everyday analogy

A supermarket can have many aisles (many pods), but if it has only one narrow exit door (the disk’s operations limit), the queue forms at the door. Measuring how many people pass the door per minute tells you when to widen it.

i
Practical hint

Test the real database on the real storage class with a realistic workload before launch. Datasheet numbers rarely match your access pattern.

28High Availability and Reliability

A reliable stateful system layers several protections, because no single one is enough.

LayerProtects againstProvided by
Stable identity and diskPod loss and restartsStatefulSet and persistent claims
Multiple members with replicationLoss of one member or machineDatabase replication
Spreading across zonesZone outageScheduling rules and multi-zone disks
Disruption budgetToo many members taken down by maintenancePod Disruption Budget
Readiness meaning “caught up”Sending traffic to a member that lacks dataApplication readiness checks
Backups and restore drillsDeletion, corruption, disasterSnapshots, exports, and log shipping
Deletion protectionAccidental removal of claims or setsRetention settings, access controls, admission rules

Failure scenarios and responses

  • A pod crashes. It restarts with the same name and disk, and rejoins the group.
  • A machine dies. The pod waits for confirmation, then restarts elsewhere in the disk’s zone. Replicas serve users meanwhile.
  • A zone fails. Members in other zones continue. Members in the failed zone remain pending until it returns, because their disks are there.
  • A disk is corrupted. Replication may copy the corruption. Restore from a backup or a clean replica.
  • Someone deletes the claim. With protections, the disk survives. Without them, only a backup can help.
Everyday analogy

A hospital’s records are protected by a locked room (the disk), duplicate copies in other buildings (replicas), fire doors (zones), rules about how many staff may be off at once (disruption budgets), and an offsite archive (backups). Each layer answers a different kind of disaster.

29Security Considerations

Data at rest is the most valuable thing in the cluster. Guard it in layers.

Encryption

Encrypt disks at rest

Choose storage classes that encrypt disks, ideally with keys you control, so that a stolen disk or snapshot is unreadable.

Encryption

Encrypt backups

Backups often hold everything. Protect them with encryption and separate access rights.

Access

Limit who can touch claims

Permission to read or delete claims, volumes, and snapshots is powerful. Grant it narrowly, in only the necessary namespaces.

Access

Limit who can exec into pods

A shell inside a database pod is a shell next to the data. Restrict and audit it.

Network

Restrict who can reach the members

Use network policies so only the application tier and the members themselves may connect to the database ports.

Secrets

Keep credentials out of images

Store database passwords and replication credentials in secrets with limited readers, and rotate them.

Container

Run as an ordinary user

Use the group setting for volumes rather than running as an administrator, and keep the root filesystem read-only where possible.

Deletion

Protect against destructive mistakes

Use retain policies, deletion protection features of the storage system, and admission rules that block deleting claims of production sets.

Everyday analogy

A bank vault is protected by its walls (encryption), its guards (access control), its cameras (audit logs), and its rules about who may carry keys (permissions). Data disks deserve the same layered care, because the value is inside them.

!
Watch out

Snapshots and clones copy everything, including sensitive records. A snapshot restored into a test namespace can expose production data to people who should never see it. Apply the same access and privacy rules to copies as to the original.

30Monitoring, Logging, and Metrics

Disks fail quietly, and they fill slowly. Good monitoring turns both into calm, planned work.

Metric

Used and free space

The kubelet reports how much of each volume is used. Graph it per claim and alert well before it fills.

Metric

Free file slots

Filesystems have a limited number of files, not only bytes. A disk with free space can still fail when file slots run out.

Metric

Claims that are pending

Cluster state metrics reveal claims stuck waiting for a disk. A claim pending for long needs attention.

Metric

Disk latency and operations

Storage provider metrics show how busy and how slow each disk is. Rising latency warns of saturation.

Events

Attach and mount failures

Events such as failed attach, failed mount, and provisioning failed explain most stuck pods.

Metric

Replication lag

How far each replica trails the primary. A lagging replica is a weak safety net.

Metric

Backup age and success

How long since the last good backup, and whether the last restore test passed.

Metric

Members ready

The number of ready pods in the set, compared with the expected number.

Alerts worth setting up

  • A volume is more than seventy or eighty percent full, and forecast to fill within days.
  • A claim has been pending for longer than a normal provisioning time.
  • A member has been not ready for longer than an update should take.
  • Replication lag rises above the limit you set based on your data-loss tolerance.
  • The latest successful backup is older than the agreed limit.
  • A disk’s latency or throttling indicator stays high.
Everyday analogy

A fuel gauge is more useful than a sudden engine stall. Storage gauges that show how full and how busy each disk is let you refill or upgrade on your own schedule, not in an emergency.

31Advantages, Disadvantages, and Trade-offs

StatefulSets solve real problems, and they bring real responsibilities.

Advantages

  • Stable identity. Members are findable by fixed names, which clustered software needs.
  • Automatic per-pod storage. One template gives every member its own disk.
  • Data survives pod replacement. A new pod reattaches to the same disk.
  • Ordered, careful operations. Start, stop, and update happen in a predictable order.
  • Fine control of updates. Partitions allow canaries on a few members.
  • Portable knowledge. The same ideas work across cloud providers and storage systems.

Disadvantages

  • Operational weight. More care is needed than for stateless applications.
  • Slower recovery. Caution about duplicate identities and disk reattachment adds delay.
  • Zone-bound disks. Pods are tied to the zone of their data.
  • Limited template changes. Storage templates cannot be edited easily after creation.
  • Data safety is still your job. Replication, backups, and restore drills are not automatic.
  • Ordered operations can stall. One stuck member can block the rest.

The main trade-offs

Control versus convenience. Running your own database on a StatefulSet gives control over versions, settings, and cost. A managed database service gives convenience and expert operation. Many teams use managed services for critical data and StatefulSets for supporting systems.

Speed versus resilience. Local disks are fastest and least resilient. Network disks are slower and survive machine loss. Replication can recover resilience on top of local disks, at the cost of complexity.

Safety versus automation. Deleting claims automatically is tidy for tests and dangerous for production. Keeping them costs money and needs manual cleanup, but protects data.

A StatefulSet gives your data a home and a name. It does not give it a guardian. That part is your design.

32Anti-patterns to Avoid

These habits lead to lost data, stuck pods, and long nights.

ANTI-PATTERN 01 · A DATABASE ON A PLAIN DEPLOYMENTAvoid
What people do

They run a database as a Deployment with several replicas sharing one claim, or with no claim at all.

Why it hurts

Members have random names and no private disks. Data is lost on restart, or several copies fight over one disk, risking corruption.

What to do instead

Use a StatefulSet with a claim per pod, or a managed service or operator built for the database.

ANTI-PATTERN 02 · TRUSTING THE DISK AS A BACKUPAvoid
What people do

They believe that because the disk survives pod restarts, their data is safe, and they skip backups.

Why it hurts

Deletion mistakes, corruption, and account loss destroy the disk as well. Replication copies bad changes to every member.

What to do instead

Keep independent, encrypted backups in another location, and rehearse restores.

ANTI-PATTERN 03 · THE DEFAULT STORAGE CLASS BY ACCIDENTAvoid
What people do

They leave the class unspecified, so the cluster’s default is used.

Why it hurts

The default may delete disks with their claims, may be slow, may not allow expansion, and may not be encrypted.

What to do instead

Name a class deliberately, chosen for speed, expansion, encryption, and retention.

ANTI-PATTERN 04 · HOST PATH FOR DATAAvoid
What people do

They mount a folder of the machine directly into the pod because it is quick.

Why it hurts

Data is bound to one machine, is lost if it is replaced, and the pod gains access to the host’s files, weakening isolation.

What to do instead

Use claims with a proper class, or local persistent volumes designed for the purpose, with replication.

ANTI-PATTERN 05 · ALL MEMBERS IN ONE ZONE OR ON ONE MACHINEAvoid
What people do

They leave scheduling to chance, and all members of a database end up together.

Why it hurts

A single machine or zone failure removes the whole group, defeating the point of replication.

What to do instead

Use anti-affinity and spread constraints across machines and zones, and reserve capacity in each zone.

ANTI-PATTERN 06 · DELETING CLAIMS TO CLEAN UPAvoid
What people do

They delete leftover claims to tidy the cluster, without checking what each holds.

Why it hurts

A leftover claim is often a scaled-down member’s only copy of data. Depending on policy, the data is gone forever.

What to do instead

Label claims with owners and purposes, check backups, and delete deliberately after review.

33Best Practices and Common Mistakes

A short checklist prevents most stateful surprises.

Best practices

Do

Choose the class on purpose

Pick speed, expansion, encryption, binding mode, and reclaim policy deliberately.

Do

Use wait-for-first-consumer

Create disks in the zone where the pod is placed.

Do

Spread members

Different machines and different zones, with spare capacity in each.

Do

Define readiness carefully

Ready should mean caught up and able to serve, not merely started.

Do

Add a disruption budget

Allow only one member to be disrupted at a time for clustered data.

Do

Back up and restore regularly

Independent backups, encrypted, with timed restore tests.

Do

Watch capacity trends

Alert early on space and file slots, and grow before it is urgent.

Do

Consider operators and managed services

They encode years of operational lessons for specific databases.

Common mistakes

Forgetting the headless Service

Without it, pods lack stable individual names, and members cannot find each other reliably.

Assuming template edits change existing disks

Template changes apply only to new claims. Existing disks must be enlarged individually.

Ignoring the stuck lowest-numbered pod

With ordered startup, later pods wait for it. Look there first.

Not planning for zone capacity

A replacement pod must land in its disk’s zone. If that zone is full, it stays pending.

Force-deleting pods casually

Forcing a pod away without confirming that the node is gone risks two writers on one disk.

Sizing disks only for today

Databases grow. Choose room to grow and monitor usage, remembering that disks cannot shrink.

34Real-World and Industry Examples

The same storage ideas appear wherever data must be remembered on Kubernetes.

Relational databases on Kubernetes

Teams running open-source relational databases typically use a StatefulSet or an operator, with one disk per member, replication between members, snapshots before upgrades, and continuous shipping of change logs to object storage for point-in-time recovery.

Message brokers and event logs

Brokers keep partitions of messages on each member’s disk and replicate them to others. Stable names let clients and members find specific brokers, and separate volumes for logs help predictable performance.

Search and analytics clusters

Search nodes hold shards of indexes on fast disks. Local disks are common for speed, with replicas of each shard on other nodes, so losing one machine does not lose data.

Coordination services

Small clusters of three or five members store configuration and elect leaders. They need stable identities and reliable disks, and a Pod Disruption Budget that allows only one member to be disrupted at a time.

Distributed caches and key-value stores

Some cache clusters keep data only in memory and use temporary storage. Others persist to disk for fast restarts, using per-pod claims so a restarted member reloads its own data quickly.

Managed database operators

Operators supplied by database vendors or communities automate creation of StatefulSets, storage, backups, failover, and resizing. Many teams adopt them so that operational lessons are encoded in software rather than in runbooks.

i
Pattern to notice

In every case, the platform provides names and disks, and the application or its operator provides replication, failover, and backups. Successful teams are clear about which responsibility belongs to whom.

35When It Does Not Work: A Troubleshooting Path

Match the symptom to the likely cause, then follow the steps.

SymptomLikely causeWhat to checkTypical fix
Claim stays pendingClass missing, driver unhealthy, no capacity, or waiting for first consumerClaim events and the class settingsFix the class, driver, or capacity; ensure a pod is scheduled if waiting for first consumer
Pod pending with a volume node affinity errorThe disk’s zone has no suitable nodeZone of the disk and free capacity thereAdd capacity in that zone, or restore into another
Error that the volume is already attached elsewhereOld machine still holds the diskNode status and cloud attachmentWait for detach, or resolve the node state safely
Pod stuck terminating on a dead nodeControl plane cannot confirm it is goneNode healthConfirm the node is off, then remove it or force delete carefully
Pod cannot write to the volumeOwnership does not match the container’s userContainer user and volume group settingsSet the volume group, or fix ownership in an init step
Disk fullGrowth beyond size, or file slots exhaustedSpace and file slot metricsExpand the claim, clean data, and add alerts
Later pods never startAn earlier pod is not ready under ordered startupThe lowest-numbered pod not readyFix that pod, or consider parallel policy if appropriate
Data missing after scale-down and scale-upRetention policy deleted the claimsClaim retention and class reclaim settingsRestore from backup; change policies to retain
1

Find the lowest-numbered unhealthy pod

With ordered startup, it is usually the one blocking the rest.

2

Read the pod’s events

Messages about scheduling, attaching, and mounting name most causes directly.

3

Inspect its claim

Is it pending, bound, or resizing? The claim’s events show provisioning problems.

4

Check the zone story

Where does the disk live, and does that zone have room for the pod?

5

Check the node story

Is the old node healthy, unreachable, or gone? Is the disk still attached to it?

6

Look inside the application

If storage is fine, logs may show permission errors, corruption warnings, or replication problems.

7

Act carefully and record it

Take a snapshot first if any step is destructive, and write down what you changed.

36A Hands-On Walkthrough in Plain Words

Let us design storage for a small three-member database, describing each step in words rather than code.

You need a database with one primary and two replicas, spread across three zones, with backups and room to grow.

1

Decide the data-loss and downtime limits

Say you accept losing at most five minutes of data and being down for at most thirty minutes. These decide how you back up and how you recover.

2

Create a dedicated storage class

Choose a fast, encrypted disk type, wait-for-first-consumer binding, expansion allowed, and reclaim policy retain.

3

Create the headless Service

It will give the members the names db-0, db-1, and db-2 under a shared service name.

4

Describe the StatefulSet

Three replicas, the headless service name, an ordered start policy, a claim template requesting the chosen class and a generous size, and a rolling update strategy with a partition.

5

Add init and sidecar containers

An init step fixes permissions and decides the member’s role from its ordinal. A sidecar streams change logs to object storage in another account.

6

Spread the members

Add spread rules to place one member in each zone, and check that each zone has spare capacity.

7

Add a disruption budget and readiness meaning

Allow at most one member to be unavailable, and make readiness mean caught up with the primary.

8

Restrict the network and access

Allow only the application tier and the members to reach the database ports, and limit who can open a shell in the pods or delete the claims.

9

Rehearse failure

Delete one member and watch it return with its data. Drain a node. Restore a backup into a scratch namespace and time it.

10

Add monitoring and growth plans

Alert on space, file slots, lag, and backup age. Write down the steps to enlarge each disk.

What this walkthrough teaches

Notice that the walkthrough begins with two business numbers, not with technology. The tolerable data loss and downtime decide everything that follows. Storage design is the art of turning those two numbers into disks, replicas, and backups.

37Design Exercise: Choosing Patterns for Four Systems

Practice makes the choice quick. Consider four systems and choose a pattern for each.

SystemFactsRecommended patternReasoning
Customer databaseCritical, moderate size, strict recovery targetsPrivate network disk per pod with replication across zones, snapshots, log shipping, and a managed service consideredData survival and recoverability matter more than raw speed
Search clusterHuge data, needs very fast disks, indexes can be rebuilt from a source of truthLocal fast disks with shard replicas on other machinesSpeed matters, and loss of one machine is covered by replicas and rebuilding
Image upload serviceMany web pods store and serve user imagesObject storage, or shared file storage if files must appear as a folderData is shared and does not belong to any single pod
Session cacheFast, short-lived, safe to loseTemporary scratch storage or memory onlyPersistence adds cost and no value
Small coordination clusterThree members, tiny data, extremely importantPrivate disk per pod, ordered start, one-at-a-time disruption budgetSmall and precious; identity and quorum matter most

Questions to ask about any system

  • Does each copy own its own data, or is the data shared?
  • Can the software replicate data between copies, or must the storage protect it?
  • Could the data be rebuilt from somewhere else, and how long would that take?
  • How much data loss and downtime can the business accept?
  • Would a managed service make this problem someone else’s specialty?
i
Try it yourself

Pick a stateful system you know. Answer the five questions above, then choose a pattern from the catalogue. If you cannot answer the recovery questions, that is the first thing to discover.

38Operators and Managed Services: Who Does the Storage Work?

A plain StatefulSet leaves many chores to you. Operators and managed services take some of them away.

A bare StatefulSet knows nothing about your particular database. It cannot promote a replica, take a consistent backup, or decide whether a member has caught up. An operator is a specialized controller, written by people who know one database well, that adds this knowledge. It watches a custom object that describes the whole database cluster, and creates the StatefulSets, claims, services, and backup jobs needed to match it. A managed service goes one step further: a cloud provider runs the database for you, and Kubernetes only hosts the applications that call it.

ChorePlain StatefulSetWith an operatorWith a managed service
Stable names and disksProvidedProvided, generated for youNot your concern
Replication setupYou configure itAutomatedBuilt in
Failover to a replicaYou script or do it by handAutomatedBuilt in
Backups and restoresYou build themUsually provided as a featureBuilt in, with a clear recovery process
Resizing disksManual, claim by claimOften automatedOften a single setting
Version upgradesManual, carefully stagedGuided or automatedScheduled by the provider
Control and tuningFullHigh, within the operator’s optionsLimited to what the provider exposes
Your operational burdenHighestMediumLowest
Everyday analogy

Cooking at home from raw ingredients gives full control and takes all the work. Using a meal kit removes shopping and measuring, while you still cook. Ordering from a restaurant removes nearly all the work, and you accept the menu. A StatefulSet, an operator, and a managed service sit at those three points.

How to choose

  • If the data is critical and your team has little database experience, prefer a managed service.
  • If you need specific versions, extensions, or cost control, consider a well-maintained operator.
  • If the workload is small, temporary, or a learning exercise, a plain StatefulSet is a good way to understand the ideas.
  • Whatever you choose, test recovery. The tool that takes work away should be proven, not trusted.
i
Practical hint

When evaluating an operator, check how actively it is maintained, how it handles upgrades and backups, and what it does when something goes wrong. An operator is software that manages your data, so it deserves the same scrutiny as the database itself.

39Capacity Planning for Stateful Storage

Storage costs money every hour, and running out costs far more. A little arithmetic finds the balance.

Capacity planning answers three questions: how much space is needed now, how fast it grows, and how much headroom to keep. Because disks can be enlarged but not shrunk, and because each member of a replicated group holds its own full copy, sizing errors are expensive in both directions.

1

Measure today’s data

Find the size of the real data, indexes, and change logs on one member. Do not forget temporary files created during maintenance, which can double usage briefly.

2

Estimate growth

Use recent history to find growth per week or month, and add known future events such as a product launch or a new customer.

3

Add headroom

Leave room so that usage stays below about seventy percent in normal times. Filesystems and databases behave badly when nearly full.

4

Multiply by members and copies

A three-member group holds three copies. Add backups and snapshots, which also consume space.

5

Check performance limits

Confirm that the chosen size and class give enough operations and throughput, since on some clouds these depend on size.

6

Set alerts and review quarterly

Compare real growth with the plan, and enlarge on your schedule, not in an emergency.

70%
a common comfortable ceiling for normal disk usage
3x
copies of the data in a three-member replicated group
1-way
disks can usually grow but not shrink
Everyday analogy

Buying a wardrobe for a growing family is a similar puzzle. Too small, and clothes spill onto the floor within a year. Too large, and you pay for empty space you cannot return. Measuring what you own, guessing how it grows, and leaving a modest margin gives the best answer.

40Frequently Asked Questions

Quick answers to the questions that come up most often.

Q1What is the difference between a Deployment and a StatefulSet?
A Deployment manages interchangeable pods with random names. A StatefulSet manages numbered pods with stable names, their own disks, and ordered operations. Use a StatefulSet when each copy has its own identity and data.
Q2Does a StatefulSet replicate my data?
No. It provides stable identity and a private disk for each pod. Copying data between members is done by the application, such as the database’s replication feature.
Q3What happens to the disk when a pod is deleted?
Nothing. The claim and disk remain. The replacement pod with the same number reattaches to the same claim, and finds its data.
Q4What happens to the disks when I scale down?
By default, the claims and disks of the removed pods remain. Scaling up again reuses them. Newer versions let you change this with a retention policy, but keeping them is the safe default.
Q5Why is my pod pending with a message about volume node affinity?
The disk lives in a particular zone, and no node in that zone can run the pod, often for lack of capacity. Add capacity in that zone or restore the data elsewhere.
Q6Can I change the storage size in the volume claim template?
The template cannot be edited in an existing StatefulSet. Enlarge each claim directly, then recreate the StatefulSet object without deleting its pods, so future members use the new size.
Q7Why is a StatefulSet slow to recover from a node failure?
It will not start a replacement until it is sure the old pod is gone, to prevent two pods writing to one disk. Disk detachment from the dead machine also takes time.
Q8Should I use local disks or network disks?
Network disks suit most databases, since they survive machine loss. Local disks are faster but tied to a machine, and are best when the application replicates data across machines.
Q9Is a persistent volume a backup?
No. It protects against pod loss only. Backups protect against deletion, corruption, and disaster, and must be kept separately and tested.
Q10What does the headless Service do?
It gives each pod its own stable DNS name, so members and clients can reach a specific pod by number, even when its address changes.
Q11When should I use parallel pod management?
When members do not depend on start order, such as peers that discover each other on their own. It speeds up startup and scaling of large groups.
Q12Should I run my database on Kubernetes at all?
It depends on your team’s skills and needs. A managed database service reduces operational work. Running your own with a good operator gives control, at the cost of more responsibility.
Q13Can several pods write to the same volume?
Only if the storage supports shared writing and the application is designed for it. Most block disks allow one writer at a time, which matches how most databases work.

41Summary and Key Takeaways

What to remember about StatefulSet storage

  • Identity and disk go together. A StatefulSet gives each pod a fixed numbered name, a stable DNS name through a headless Service, and its own claim that a replacement pod reattaches to.
  • Storage is a chain. Claims request storage, classes describe it, CSI drivers build it, and binding modes and zones decide where it lives, so a pod is tied to its disk’s zone.
  • Defaults protect data, if you keep them. Claims are retained on scale-down by default. Choose reclaim and retention policies deliberately and avoid automatic deletion for important data.
  • Operations are careful by design. Ordered start, reverse-order updates, partitions, and cautious node-failure recovery all trade speed for safety.
  • Pick the pattern that fits. Private disks with replication suit clustered databases, shared storage suits shared files, scratch storage suits rebuildable data, and managed services suit teams who would rather not operate storage.
  • A disk is not a backup. Keep encrypted backups in another location, and rehearse timed restores against your data-loss and downtime targets.
  • Watch, grow, and protect. Alert on space, file slots, lag, and backup age, plan resizing early, spread members across zones, limit who can delete claims, and combine with budgets and network policies.