Introduction

StatefulSet storage patterns exist because stateful Pods are not interchangeable. A database replica, a Kafka broker, or a queue node has a name, a role, and a disk that must come back together after every restart, reschedule, and rollout, with the same ordinal name, DNS record, and PVC attached.

Consider an illustrative composite drawn from common production reviews, not a named incident. A team runs a three-node database on a StatefulSet and scales it down to two replicas during a quiet weekend to save cost. The third Pod disappears, its PVC stays Bound, and the disk keeps billing for two months before anyone notices. In the same quarter, an engineer deletes a test StatefulSet, assumes the disks went with it, and later finds the PVCs still holding data nobody can account for. Nothing failed loudly. The storage did exactly what the defaults told it to do, and nobody had written those defaults down.

The second half of the composite is worse. A disk fills up, an engineer edits the size inside volumeClaimTemplates, the API rejects the change as immutable, and the incident stalls while the team learns that the template is a blueprint for new claims, not a dial for existing ones. Both halves share one root cause: StatefulSet storage patterns have a lifecycle of their own, separate from the Pod lifecycle, and that lifecycle needs explicit decisions before production, not during an incident.

This is lesson 18 of the Kubernetes Roadmap Series, in Module 8 on storage. The previous lesson covered Kubernetes storage: PVC, StorageClass and CSI provisioning, which explains how a claim binds to a volume. This lesson builds on that foundation and owns the StatefulSet layer only: ordinal identity, per-Pod claims, headless DNS, ordered rollout, and what survives a scale-down or a delete. When you finish Module 8, the series continues into security with Module 9: Kubernetes security, starting with RBAC and least-privilege access.

The 5-minute takeaway

A StatefulSet gives each Pod three linked guarantees: an ordinal name that never changes, a DNS record derived from that name, and one PVC per volumeClaimTemplate that follows the ordinal across restarts. Set the governing headless Service before you need peer discovery, keep the PVC retention policy on Retain for production data, and treat the PV reclaim policy as a second, separate safety switch. Scale-down keeps disks by design, so audit orphaned PVCs on a schedule. To grow storage, patch each generated PVC, never the template. And remember that a retained disk is not a backup: snapshots, restore drills, and application-level replication are still your job.


1. StatefulSet storage patterns start with ordinal identity

StatefulSet storage patterns begin with a number. Each Pod receives an ordinal index, starting at 0, and that ordinal becomes its hostname, its DNS label, and the suffix of its PVC names. The identity sticks to the Pod across restarts and rescheduling, regardless of which node runs it.

A Deployment Pod gets a random suffix and can be replaced by any other Pod without the application noticing. A StatefulSet Pod cannot. When db-1 restarts, Kubernetes recreates a Pod named db-1, attaches the same claim, and restores the same DNS name. Peers that stored "db-1" in a replication config keep working. The controller also stamps each Pod with the label apps.kubernetes.io/pod-index, which your monitoring, log pipelines, and init logic can read instead of parsing the Pod name.

Ordinal identity has a hard edge that matters during node failure. Kubernetes enforces at-most-one semantics for a given ordinal: it will not start a second db-1 while the first db-1 might still be running somewhere. If a node dies and the control plane cannot confirm the old Pod is gone, the replacement waits. That pause protects your data from two writers on one disk, and it also means a stuck node can block recovery until you fence it properly. Section 9 covers that trade-off in detail.

Use the ordinal where the application needs it, and nowhere else. Reading the ordinal in an init container to seed a replica set, assign a shard, or pick a primary is normal. Hard-coding business logic that assumes db-0 is always the primary is fragile, because a well-run cluster should survive db-0 being down. Identity should let peers find each other; the application protocol should still decide who leads.


2. StatefulSet storage patterns: volumeClaimTemplates create one PVC per Pod

In StatefulSet storage patterns, volumeClaimTemplates are blueprints. For each template entry, the controller creates one PersistentVolumeClaim per Pod, named with the template name, the StatefulSet name, and the ordinal. A template called data on a StatefulSet called db produces data-db-0, data-db-1, and data-db-2.

Each generated PVC binds to its own PV through the StorageClass named in the template, using the provisioning mechanics from the previous lesson. The Pod mounts that claim at the path in its volumeMounts, and the same claim reattaches when the Pod is recreated. Two templates on one StatefulSet, for example data and wal, produce two claims per Pod, which lets you place write-ahead logs on faster storage than bulk data.

Three template fields decide most production outcomes. The access mode is usually ReadWriteOnce for block storage, and ReadWriteOncePod where your CSI driver supports it and you need a strict single-Pod guarantee. The StorageClass decides binding mode, reclaim policy, and whether expansion is allowed later, so pick it as a lifecycle decision, not a default. The requested size is the size every new replica is born with, and section 8 explains why changing it later is not a template edit.

The manifest below is the smallest honest version of the pattern: a governing headless Service, a StatefulSet that references it, an explicit retention policy, and one claim template. Replace the image, StorageClass, and size with values your platform team supports.

yaml
apiVersion: v1
kind: Service
metadata:
  name: db-headless
  namespace: data
spec:
  clusterIP: None
  selector:
    app: db
  ports:
    - name: postgres
      port: 5432
---
apiVersion: apps/v1
kind: StatefulSet
metadata:
  name: db
  namespace: data
spec:
  serviceName: db-headless
  replicas: 3
  podManagementPolicy: OrderedReady
  persistentVolumeClaimRetentionPolicy:
    whenDeleted: Retain
    whenScaled: Retain
  selector:
    matchLabels:
      app: db
  template:
    metadata:
      labels:
        app: db
    spec:
      terminationGracePeriodSeconds: 60
      containers:
        - name: postgres
          image: postgres:17
          ports:
            - containerPort: 5432
              name: postgres
          readinessProbe:
            exec:
              command: ["pg_isready", "-U", "postgres"]
            periodSeconds: 5
          volumeMounts:
            - name: data
              mountPath: /var/lib/postgresql/data
  volumeClaimTemplates:
    - metadata:
        name: data
      spec:
        accessModes: ["ReadWriteOnce"]
        storageClassName: gp3-retain
        resources:
          requests:
            storage: 50Gi

Two details in that manifest carry more weight than they look. The readiness probe decides when the controller may start the next ordinal under OrderedReady, so a probe that passes before the database accepts replication will start peers too early. The termination grace period decides how long the database gets to flush and shut down cleanly; too short, and a rollout can kill a Pod mid-flush.


3. StatefulSet storage patterns need a headless Service for DNS

StatefulSet storage patterns pair storage identity with network identity. A headless Service, a Service with clusterIP set to None, gives each Pod a stable DNS record built from the Pod name and the Service domain. Peers can address db-1 directly, by name, across restarts and IP changes.

A normal Service hides Pods behind one virtual IP and load-balances across them, which is wrong for peer-to-peer protocols. A replica needs the primary by name, not whichever Pod the Service picks. With a headless Service named db-headless in namespace data, each Pod resolves as db-0.db-headless.data.svc.cluster.local, and a lookup of the Service name itself returns the individual Pod IPs. The StatefulSet field serviceName must name that governing Service, and the Service selector must match the Pod labels, or the DNS records never appear.

You are responsible for creating the governing Service; the StatefulSet does not create it for you. A StatefulSet can run without serviceName, but then Pods get no stable subdomain and peers fall back to IP-based names that change on every recreate. That failure is quiet: Pods run, storage mounts, and only the cluster protocol breaks when a peer restarts and its address changes.

Most production setups run two Services. The headless Service governs identity and peer discovery. A second, normal Service fronts client traffic and can select only the primary, or all replicas for read traffic, depending on the application. Keep those roles separate in naming and in review, because pointing clients at the headless Service gives them raw Pod IPs with no load balancing and no health-based routing beyond DNS. The full Service type comparison lives in Kubernetes Services explained: ClusterIP, NodePort, LoadBalancer and headless; this lesson uses the headless type only as the governing service.

Verify DNS from inside the cluster, not from your laptop. A short check after the first rollout saves a long incident later:

bash
kubectl -n data get pods,pvc -l app=db
kubectl -n data run dns-check --rm -it --image=busybox:1.37 --restart=Never -- \
  nslookup db-1.db-headless.data.svc.cluster.local

4. StatefulSet storage patterns: ordered rollout and updates

Ordered lifecycle is the third pillar of StatefulSet storage patterns. With the default OrderedReady policy, Pods start in ascending ordinal order and each must be Running and Ready before the next starts. Deletion runs in reverse, from the highest ordinal down, so the set shrinks and grows predictably.

OrderedReady suits clustered software that bootstraps in sequence: a seed node first, then members that join it. It also serialises failure. If db-0 never becomes Ready, db-1 and db-2 never start, and a three-replica set sits at one broken Pod. That is the correct behaviour when peers depend on each other, and the wrong behaviour when replicas are independent shards that could start in any order. For independent replicas, podManagementPolicy Parallel starts and stops Pods without waiting, trading sequence guarantees for faster recovery.

Updates run in reverse ordinal order under the default RollingUpdate strategy: the highest ordinal updates first, and the controller waits for it to be Ready before moving down. That order protects db-0, often the seed or primary, until every other replica runs the new version. The partition field pauses the rollout at a chosen ordinal, which gives you a canary: set partition to 2 on a three-replica set, and only db-2 updates while db-0 and db-1 stay on the old template until you lower the partition.

The OnDelete strategy hands update timing to you. The controller changes nothing until you delete a Pod, and the replacement comes up with the new template. Operators and careful database teams use OnDelete when a human or an external system must approve each replica change. Whichever strategy you pick, write it down in the manifest review. A rollout that stalls at db-2 because its readiness probe now fails is the controller working as designed, and the fix is in the probe or the new image, not in forcing the next ordinal.


5. StatefulSet storage patterns: Retain vs Delete for PVCs

StatefulSet storage patterns keep PVCs by default. The persistentVolumeClaimRetentionPolicy field controls whether generated PVCs are deleted when the StatefulSet is deleted (whenDeleted) or when replicas are scaled down (whenScaled). Retain is the default for both, and it matches the behaviour StatefulSets had before this policy existed.

The policy reached beta in Kubernetes 1.27 and stable in 1.32, and it forms a simple matrix. Retain plus Retain means Kubernetes never deletes the claims for you; cleanup is manual and deliberate. Delete on whenDeleted with Retain on whenScaled removes claims only when the whole set goes away, while scale-down still keeps disks for a later scale-up. Delete on both removes each claim as soon as its replica is removed. Retain on whenDeleted with Delete on whenScaled suits sets where scale-down should free disks immediately but a full delete should still leave data for inspection.

Choose per workload, not per cluster. Production databases, queues with unprocessed messages, and anything holding data you cannot rebuild belong on Retain plus Retain, with a documented manual cleanup runbook. Ephemeral test clusters, CI fixtures, and rebuildable caches belong on Delete, because orphaned disks from forgotten test sets are a steady, quiet cost. The AWS and Salesforce storage lifecycle work found exactly that pattern at scale: default retention left PVCs, PVs, and cloud disks behind after StatefulSet deletion until teams set the policy deliberately.

Do not confuse this policy with the PV reclaim policy. They are two switches in series. The StatefulSet retention policy decides whether the PVC object is deleted. The PV reclaim policy, copied from the StorageClass at provisioning time, decides what happens to the disk when its PVC is deleted: Delete removes the PV and the backing storage, Retain keeps the PV in Released state with data intact. A PVC deleted under a Retain reclaim policy leaves a Released PV that will not bind to a new claim until an administrator clears its claimRef. For production data, Retain at both switches is the safe starting point, and any move to Delete at either switch should be a reviewed decision with a backup verified first.


6. StatefulSet storage patterns: deletion safety and finalizers

Deletion safety in StatefulSet storage patterns rests on finalizers and on knowing which delete command does what. Every PVC carries the kubernetes.io/pvc-protection finalizer, so deleting a claim that a Pod still uses only marks it Terminating until the Pod lets go. The PV carries pv-protection for the same reason.

Three delete paths surprise teams. Deleting the StatefulSet removes the Pods, and the retention policy then decides the claims; with Retain, the PVCs and disks survive untouched, which is the safe outcome for data and the confusing outcome for cost. Deleting the namespace deletes every PVC in it, and each PVC deletion then triggers its PV reclaim policy, so a namespace delete on a Delete reclaim StorageClass destroys disks in one command. Deleting a single PVC by name is the direct path to disk deletion under a Delete reclaim policy, and the pvc-protection finalizer is the only thing standing between a typo and a running Pod losing its claim object.

Two habits prevent most accidents. First, patch production PVs to Retain before any risky operation, because the reclaim policy on an existing PV can be changed even though a StorageClass reclaim policy cannot:

bash
kubectl get pv -o custom-columns=NAME:.metadata.name,CLAIM:.spec.claimRef.name,POLICY:.spec.persistentVolumeReclaimPolicy
kubectl patch pv <pv-name> -p '{"spec":{"persistentVolumeReclaimPolicy":"Retain"}}'

Second, use cascade orphan when you need to replace the StatefulSet object without touching Pods or claims, for example during the resize procedure in the next sections:

bash
kubectl -n data delete statefulset db --cascade=orphan
kubectl -n data apply -f db-statefulset.yaml

Orphan deletion removes the controller and leaves Pods running; the recreated StatefulSet adopts them by label. Treat that as surgery, not routine: do it with the manifest in version control, during a window where a second operator can watch replica counts, and verify adoption before you touch anything else.


7. StatefulSet storage patterns: scaling up and down

Scaling in StatefulSet storage patterns is asymmetric. Scale up and the controller creates the next ordinal with a fresh PVC from the template, in order, waiting for readiness. Scale down and the highest ordinals are deleted in reverse order, while their PVCs stay Bound under the default Retain policy, ready to reattach if you scale back up.

That asymmetry protects data and creates two operational debts. The first is cost: every scale-down leaves disks behind, and disks from experiments and temporary replicas keep billing until someone audits them. Find orphans by comparing PVC ordinals against the current replica count; any claim whose ordinal is greater than or equal to the replica count belongs to a replica that no longer exists. The second debt is data divergence. Scale back up after a long gap and the returning replica rejoins with stale data on its old disk. The application must resync it, and some systems need the disk wiped before the replica can rejoin cleanly. Decide which behaviour you want before the scale-down, not after the scale-up.

Scale-down also interacts with quorum. Removing replicas from a consensus system without first removing them from the membership can break quorum or leave the cluster waiting for a member that will never return. The StatefulSet controller knows nothing about your consensus protocol; it deletes Pods in reverse order and stops. Membership changes belong to the application or its operator, sequenced before or alongside the replica change. If your database needs a drain, a membership removal, or a leadership transfer before a replica goes away, that step is part of the scaling runbook, every time.

A practical guardrail: alert on PVCs whose ordinal exceeds the replica count for more than a day, and review them weekly. Deleting an orphaned PVC is destructive and irreversible under a Delete reclaim policy, so the review confirms the data is rebuildable or backed up, names an owner, and records the decision. Silence is how orphaned disks turn into a finance question two quarters later.


8. StatefulSet storage patterns: resizing storage safely

Resizing in StatefulSet storage patterns works on generated PVCs, not on the template. The volumeClaimTemplates field is immutable after creation, and editing it does nothing for existing claims. To grow a disk, increase the storage request on each PVC, one ordinal at a time, after confirming the StorageClass allows expansion.

Expansion needs three conditions. The StorageClass must set allowVolumeExpansion to true, or the API rejects the edit. The CSI driver must support expansion for that volume type, and some drivers grow the volume online while others need a Pod restart to finish the filesystem resize, which shows up as a FileSystemResizePending condition on the PVC. The cloud provider may also rate-limit modifications, so a fleet-wide resize loop can hit provider limits that a single test resize never showed.

The safe sequence is boring on purpose. Verify a recent backup or snapshot can restore. Patch the highest ordinal first, watch the PVC reach the new size and the filesystem resize complete, confirm replication is healthy, then move down one ordinal at a time. Patching all claims at once removes your ability to stop when the second resize behaves differently from the first.

bash
kubectl get storageclass gp3-retain -o jsonpath='{.allowVolumeExpansion}{"\n"}'
kubectl -n data patch pvc data-db-2 --type merge \
  -p '{"spec":{"resources":{"requests":{"storage":"100Gi"}}}}'
kubectl -n data get pvc data-db-2 -w

Shrinking is not supported. A smaller disk means a new PVC and an application-level data migration, which is why starting modest and growing beats starting large. One more trap waits after a successful resize: new replicas created later still get the template size, so a scale-up after a resize produces a Pod with a smaller disk than its peers. Fix that by recreating the StatefulSet with an updated template using the cascade orphan path from section 6, after every existing PVC already has the new size. Record the live PVC sizes in your infrastructure notes until the template catches up, so the next engineer does not trust the manifest alone.


9. StatefulSet storage patterns: zones, nodes and stuck Pods

Zone placement decides whether StatefulSet storage patterns survive a node failure. A zonal disk lives in one availability zone, and its Pod can only run where that disk can attach. If the StorageClass binds immediately, the provider picks the zone before the scheduler picks a node, and the Pod can sit Pending.

The fix is volumeBindingMode WaitForFirstConsumer on the StorageClass, which delays provisioning until the scheduler has chosen a node, so the disk is created in that node's zone. The previous lesson covers binding modes in depth; here the point is narrower. A StatefulSet multiplies the problem by the replica count, and a spread constraint that pushes replicas across zones only works if each PVC is provisioned after its Pod is placed. Check the binding mode before the first production rollout, because changing it later means a new StorageClass and new claims.

Node failure exposes the at-most-one rule from section 1. When a node dies, the replacement Pod for that ordinal waits until Kubernetes is sure the old Pod is not running and its volume is detached. A node that is unreachable but not confirmed dead can hold that state for a long time. The out-of-service taint, node.kubernetes.io/out-of-service, lets an operator force the issue: tainting the dead node triggers forced Pod deletion and volume detachment, and the StatefulSet starts the replacement elsewhere. Use it only when you are certain the node is truly out of service, because forcing detachment from a node that is actually alive risks two writers on one filesystem.

Local storage sharpens every one of these edges. A Pod bound to a local PV can only reschedule onto the same node, so node loss means data loss unless the application replicates. That can still be the right design for systems with strong replication, such as distributed databases that treat local disks as disposable. It is the wrong design when the StatefulSet is your only copy. Match the storage type to the replication story, and write the match down where the next on-call engineer will find it at 3 a.m.


10. StatefulSet storage patterns: backup is a separate handoff

StatefulSet storage patterns protect identity and attachment, not data. A retained PVC survives Pod deletion, and a snapshot can capture a volume at a point in time, but neither gives you a tested restore. Backup is a handoff to a system designed for it, with its own schedule, retention, and drills.

Separate three layers that teams often merge into one word. Replication keeps copies current and survives a disk or node loss, but it also replicates corruption and accidental deletes at full speed. Volume snapshots capture a disk image quickly and suit crash-consistent recovery, but a database snapshot taken mid-transaction may need recovery work, and application-consistent snapshots need the database to flush or quiesce first. Backups are the copies you keep beyond the blast radius of the cluster, with retention measured in weeks, and they are the only layer that survives a namespace deletion, a bad migration, or a compromised credential.

The handoff contract has four parts. Name the tool, whether that is a CSI snapshot schedule, a backup platform such as Velero, or the database operator's own backup feature. State the consistency level, crash-consistent or application-consistent, and who owns the quiesce step. Set retention and a restore target, including how long a restore takes and where it lands. And run restore drills on a schedule, into a throwaway namespace, because an untested backup is a hypothesis. A drill that restores db-0's data and boots the application against it proves the whole chain: snapshot, PVC creation, mount, and application recovery.

Operators change who owns this contract, not whether it exists. A mature database operator handles member replacement, backup scheduling, and point-in-time recovery as part of its reconciliation. If you run a raw StatefulSet, your team is the operator, and the runbooks in this article are part of the job. The production hygiene that surrounds all of this, resource requests, probes, and disruption budgets, is covered in Kubernetes best practices; storage patterns assume that baseline is already in place.


11. StatefulSet storage patterns: choose the right pattern

Choose StatefulSet storage patterns when each replica needs a stable name, its own disk, and an ordered lifecycle, and your team can operate the storage lifecycle that comes with it. Choose something else when the replicas are interchangeable, the data can live outside the cluster, or an operator already solves the problem better.

The decision table below separates the four common shapes. Read it by the second column: what breaks if a Pod comes back with a different name or a different disk. If the answer is nothing, you do not need a StatefulSet. If the answer is the cluster protocol, you need identity, and then the question becomes who operates it.

Pattern Identity need Storage shape Choose it when Watch out for
StatefulSet with volumeClaimTemplates Stable ordinal and DNS per replica One PVC per Pod from a template Clustered software you operate yourself, with per-node data Orphaned PVCs, resize by PVC patch, backup is your job
Deployment with shared PVC None, Pods are interchangeable One shared claim, often ReadWriteMany Stateless tiers writing to shared files or object storage Shared filesystem semantics and contention under load
Operator-managed StatefulSet Stable, managed by the operator Operator creates and repairs claims Databases with a mature operator, such as Postgres or Kafka Operator upgrades and CRD changes need their own review
External managed database Outside Kubernetes Provider-managed storage Data must outlive the cluster, or the team is small Network latency, egress cost, and provider lock-in

The controller-level comparison behind this table is covered in Deployment vs StatefulSet vs DaemonSet. This lesson assumes that choice is made and focuses on running the StatefulSet option safely. One pattern deserves a direct warning: a single-replica StatefulSet used only to get a stable PVC is usually a Deployment with extra ceremony. If one Pod with one disk is the whole design, ask whether the data belongs in a managed service, and whether the stable name buys anything a Service does not.

Cost belongs in this decision too. Per-Pod disks bill per replica whether the Pod runs or not, snapshots bill per gigabyte retained, and cross-zone replication traffic bills per byte. A three-replica set with 100Gi disks and daily snapshots is a real line item, and the Retain defaults in this article protect data at the price of keeping that line item alive until a human reviews it. That is the right trade for production data. It is the wrong trade for throwaway environments, which is why retention policy belongs in the per-environment manifest, not in a platform default nobody revisits.


12. StatefulSet storage patterns: troubleshooting matrix and checklist

Most StatefulSet storage patterns failures announce themselves in one of five places: a Pod stuck Pending, a PVC stuck Pending or Terminating, DNS that does not resolve, a rollout stalled on one ordinal, or a disk that will not grow. The matrix below maps each symptom to the first checks that separate a storage problem from an application problem.

Symptom Likely cause First checks Fix direction
Pod Pending, PVC Pending StorageClass cannot provision, or zone mismatch kubectl describe pvc, StorageClass binding mode, CSI provisioner logs Use WaitForFirstConsumer, fix quota or driver, recreate claim if zone is wrong
Pod Pending, PVC Bound Volume cannot attach where the Pod is scheduled Pod events for FailedAttachVolume, node zone vs PV zone, multi-attach errors Fence the old node, check access mode, move Pod constraints to the disk zone
Peer DNS does not resolve Missing or mismatched governing headless Service serviceName value, Service selector vs Pod labels, nslookup from inside the cluster Create or fix the headless Service, align selector and labels
Rollout stalls on one ordinal Readiness probe fails on the new template Pod readiness, probe output, application logs for that ordinal Fix probe or image, use partition to hold the rollout, roll back that ordinal
PVC stuck Terminating pvc-protection finalizer held by a Pod still using the claim Pods referencing the claim, Pod phase, finalizers on the PVC Delete or finish the Pod first, never strip the finalizer by hand
Resize does nothing Template edited instead of PVC, or expansion disabled StorageClass allowVolumeExpansion, PVC conditions, FileSystemResizePending Patch the generated PVC, restart Pod if filesystem resize is pending
Replica returns with stale data Scale-up reattached an old retained PVC PVC age vs replica history, application replication state Resync through the application, or wipe and rejoin the replica
Disks billing after scale-down Retain policy kept PVCs for removed ordinals PVC ordinals vs replica count, PV reclaim policy Review, back up if needed, delete PVCs deliberately

Run the checklist before the first production rollout, and again before any change to retention, size, or StorageClass:

  • Governing headless Service exists, serviceName matches it, and per-Pod DNS resolves from inside the cluster.
  • volumeClaimTemplates use a StorageClass with WaitForFirstConsumer, allowVolumeExpansion set deliberately, and a reclaim policy reviewed for production data.
  • persistentVolumeClaimRetentionPolicy is explicit in the manifest, Retain plus Retain for data you cannot rebuild.
  • Readiness probe passes only when the replica can serve its role, and terminationGracePeriodSeconds covers a clean shutdown.
  • Rollout strategy and partition plan are written down, with a rollback step per ordinal.
  • Scale-down runbook covers application membership changes and orphaned PVC review.
  • Resize runbook patches PVCs one ordinal at a time and records live sizes until the template catches up.
  • Backup tool, consistency level, retention, and last successful restore drill are named, with dates.
  • Alerts cover PVC ordinal drift, PVCs near capacity, and replicas stuck not Ready during rollout.

StatefulSet storage patterns reward teams that treat storage as a lifecycle with owners, not as a side effect of a Pod spec. Get identity, retention, and backup right before the first production replica, and the hard days become runbook days instead of data-loss days.

Frequently Asked Questions

What are StatefulSet storage patterns in Kubernetes?

StatefulSet storage patterns are the combination of ordinal Pod identity, one PVC per Pod created from volumeClaimTemplates, stable DNS through a governing headless Service, and ordered creation and deletion. Together they let a replica restart with the same name, the same disk, and the same network address.

How do volumeClaimTemplates work in StatefulSet storage patterns?

Each volumeClaimTemplate entry produces one PVC per Pod, named from the template, the StatefulSet, and the ordinal, such as data-db-0. The controller creates the claim when the Pod is first created, binds it through the named StorageClass, and reattaches the same claim whenever that ordinal is recreated.

Why do StatefulSet storage patterns need a headless Service?

A headless Service with clusterIP set to None gives each Pod a stable DNS record, such as db-1.db-headless.data.svc.cluster.local. Clustered software uses those names to find specific peers. The StatefulSet serviceName field must reference that Service, and you must create the Service yourself.

What happens to PVCs in StatefulSet storage patterns when the StatefulSet is deleted?

With the default Retain policy, the PVCs and their disks survive deletion of the StatefulSet. Setting whenDeleted to Delete removes the generated PVCs after their Pods are gone, and the PV reclaim policy then decides whether the underlying disk is deleted or kept as a Released PV.

Do StatefulSet storage patterns delete PVCs on scale-down?

No, not by default. Scale-down deletes the highest ordinal Pods, but their PVCs stay Bound under the Retain policy so a later scale-up reattaches the same data. Setting whenScaled to Delete removes those PVCs as replicas are removed. Retained PVCs keep billing until reviewed.

How do you resize storage in StatefulSet storage patterns?

Patch each generated PVC to a larger storage request, one ordinal at a time, after confirming the StorageClass allows expansion and a restore-tested backup exists. Editing volumeClaimTemplates does not resize existing claims because the field is immutable. Shrinking is not supported; it requires a new PVC and data migration.

What is the difference between Retain in StatefulSet storage patterns and PV reclaimPolicy Retain?

They guard different steps. The StatefulSet retention policy decides whether the PVC object is deleted when the set is deleted or scaled down. The PV reclaim policy decides what happens to the disk after its PVC is deleted: Delete removes the storage, Retain keeps the PV as Released with data intact.