Overview

It was 2:40 AM when the on-call phone rang. A StatefulSet running the order database was doing a rolling update, and two of its three replicas were stuck in ContainerCreating for twenty minutes straight. kubectl describe pod gave only a vague FailedMount, kubectl get events was spamming FailedAttachVolume, and nobody could say which step it was stuck on.

I have run into this failure more than once. And the interesting part is that, every time, the root cause was almost never “the storage broke” — the disk was fine, and the cloud console happily showed the volume as healthy. The problem lived in the attach/detach state machine between Kubernetes and the CSI driver: a “ghost” VolumeAttachment object still pointing at an old node was blocking every new attach request.

This article is not about “how to install a CSI driver” — that is a thirty-minute read in the docs. I want to break down something else: when you get woken up at night by ContainerCreating, which layer you should look at first, in what order to dig, and how to make it self-healing afterward. I will use that incident as the spine and thread through six decisions I have actually made in production. You will see:

  • Which two layers CSI actually works at, and who owns attach, mount, and provision — get the responsibility boundaries straight first, or your debugging will be pure guessing;
  • What a ghost VolumeAttachment looks like and how to clean it up safely (delete the wrong one and you get a double-write, which really does destroy data);
  • The three semantic traps that are easiest to “think you understand but don’t”: RWO, volumeBindingMode, and online expansion;
  • How volumes detach during everyday operations — node maintenance, scale-down, and Spot reclamation — and where it most often goes wrong;
  • And a line I keep telling people not to cross casually: building your own CSI driver.

Here is the bottom line up front: 90% of K8s storage failures are not the storage breaking — they are the CSI state machine and the control-plane objects getting out of sync. The entry point for debugging is always VolumeAttachment and the kubelet log, never staring at the Pod.

1. First, See Which Layer CSI Actually Works At

A lot of engineers treat CSI as a black box: “just install it and it works.” That is fine day to day, but the moment something breaks you are stuck, because you do not know which component’s door to knock on. So spend five minutes getting the responsibility boundaries straight.

What CSI is, in one plain-language sentence

CSI (Container Storage Interface) is an interface standard between a container orchestrator and a storage system. A daily-life analogy: it is like USB. Before USB, every peripheral needed the host to have dedicated driver code baked in; with USB, the peripheral vendor just implements the standard connector and the host only has to recognize that connector — it does not care whether the other end is a flash drive or a printer.

Kubernetes used to work the other way: a storage driver had to be written into the K8s main codebase (called in-tree). That produced some very real problems:

  • A storage vendor shipping a new driver version had to wait for a K8s release, so release cycles were chained together;
  • Third-party code in the core repo meant a driver bug could take down kubelet or kube-controller-manager;
  • Those drivers ran with the same privileges as core components, so the security boundary was blurry.

CSI moved storage drivers out of the K8s mainline (out-of-tree): vendors publish and iterate on their own, and K8s only guarantees the interface stays stable. Today it is the only standard for container storage access, and the in-tree cloud-vendor volume plugins have essentially all been replaced by it.

Two processes, each owning one leg of the journey

A CSI driver splits into two components, running in two places, managing two legs of a volume’s lifecycle. This is the foundation of all troubleshooting; commit it to memory.

ComponentDeploymentWho calls itWhat it manages
ControllerStatefulSet or Deployment, usually 1 replicasidecars on the kube-controller-manager sideVolume create/delete/attach-to-node/expand (cluster scope)
NodeDaemonSet, one per nodethe local kubeletVolume formatting / staging mount / bind to the Pod directory (node scope)

And they do not talk to K8s directly — they talk through a set of “glue” sidecar containers that translate requests. Save this table to your notes; when you debug by it, you will save half your time:

sidecarObject it watchesCSI calls it triggersBelongs to
external-provisionerPVCCreateVolume / DeleteVolumeController
external-attacherVolumeAttachmentControllerPublishVolume / ControllerUnpublishVolumeController
external-resizerPVC (capacity change)ControllerExpandVolumeController
external-snapshotterVolumeSnapshotCreateSnapshot / DeleteSnapshotController
node-driver-registrarRegisters driver with kubelet(registration, no business RPC)Node

The full path from a PVC to a Pod

Stringing the roles together, a “request a volume → mount it into a container” flow looks roughly like this:

User / workload
   │  apply PVC (storageClass: my-csi)
   ▼
external-provisioner  ──watch PVC──▶  CSI Controller: CreateVolume
   │                                        │ returns volumeHandle
   ▼                                        ▼
Create PV object, PVC bound  ◀───────────┘
   │  Pod references the PVC, gets scheduled to node N
   ▼
attach/detach controller creates VolumeAttachment(node=N)
   │
   ▼
external-attacher ──▶ CSI Controller: ControllerPublishVolume  (= attach the cloud disk to node N)
   │
   ▼
kubelet(node N) ──▶ CSI Node: NodeStageVolume (format, mount to a global path)
   │
   ▼
kubelet(node N) ──▶ CSI Node: NodePublishVolume (bind mount into the Pod directory)

Two “sticking points” in this diagram cause the most trouble, and they are two words that recur throughout this article:

  1. attach: driven by the control-plane attach/detach controller through external-attacher. It maintains the desired state of the VolumeAttachment object. Stuck here, the Pod stays ContainerCreating forever, and the event log keeps repeating FailedAttachVolume.
  2. mount: done by the kubelet on the node. Stuck here, the event is usually FailedMount, and it only reproduces on a specific node.

An interface definition worth a glance

The CSI interface is defined in gRPC (in the csi.proto of the container-storage-interface/spec repo). You do not need to memorize it, but knowing these RPCs exist lets you map them when reading logs:

// Controller side: volume-level operations (triggered by external-* sidecars)
service Controller {
  rpc CreateVolume(CreateVolumeRequest) returns (CreateVolumeResponse);
  rpc DeleteVolume(DeleteVolumeRequest) returns (DeleteVolumeResponse);
  rpc ControllerPublishVolume(ControllerPublishVolumeRequest) returns (ControllerPublishVolumeResponse);   // attach
  rpc ControllerUnpublishVolume(ControllerUnpublishVolumeRequest) returns (...);                            // detach
  rpc ControllerExpandVolume(ControllerExpandVolumeRequest) returns (ControllerExpandVolumeResponse);         // expand
}

// Node side: mount operations on the node (triggered by kubelet)
service Node {
  rpc NodeStageVolume(NodeStageVolumeRequest) returns (NodeStageVolumeResponse);
  rpc NodePublishVolume(NodePublishVolumeRequest) returns (NodePublishVolumeResponse);
  rpc NodeGetInfo(NodeGetInfoRequest) returns (NodeGetInfoResponse);  // reports topology labels
}

What NodeGetInfo returns matters: it tells K8s which zone this node is in and how many volumes it can attach at most. We will use that when we get to topology binding.

What a minimal CSI Controller deployment looks like

The tables are not quite enough on their own. Here is a typical (simplified) deployment skeleton for a CSI driver’s controller side. You can find the real one in your own cluster with kubectl -n kube-system get statefulset csi-<driver>-controller -o yaml. Once you can read it, you understand how the “out-of-tree” part is bolted on:

apiVersion: apps/v1
kind: StatefulSet
metadata:
  name: csi-example-controller
  namespace: kube-system
spec:
  serviceName: csi-example-controller
  replicas: 1                      # controller side is usually single-replica, to avoid concurrent ops on one volume
  selector:
    matchLabels: { app: csi-example-controller }
  template:
    metadata:
      labels: { app: csi-example-controller }
    spec:
      serviceAccountName: csi-example-controller   # needs permission to operate PV/PVC/VA
      containers:
        - name: csi-provisioner
          image: registry.k8s.io/sig-storage/csi-provisioner:v4.x
          args: ["--csi-address=/csi/csi.sock"]     # talks to the driver container over a UDS
        - name: csi-attacher
          image: registry.k8s.io/sig-storage/csi-attacher:v4.x
          args: ["--csi-address=/csi/csi.sock"]
        - name: csi-resizer
          image: registry.k8s.io/sig-storage/csi-resizer:v1.x
          args: ["--csi-address=/csi/csi.sock"]
        - name: csi-example-driver
          image: example/csi-driver:1.0.0
          args: ["--endpoint=unix:///csi/csi.sock", "--mode=controller"]
          volumeMounts:
            - { name: socket-dir, mountPath: /csi }
      volumes:
        - name: socket-dir                    # all sidecars and the driver share this UDS directory
          emptyDir: {}

All three sidecars point at the same Unix Domain Socket (/csi/csi.sock) — that is, they call the driver container over gRPC through a local socket. This is why you see “four containers in the controller pod”: one real driver plus three dedicated translators. When external-attacher hangs, that is the door you knock on.

CSI vs FlexVolume: why the latter retired

Before CSI, K8s had FlexVolume: a storage vendor provided an executable and K8s invoked it with exec. It sounded decoupled too, but it left two problems unsolved. First, the driver binary had to live on the host and required root, so the security boundary was poor. Second, mounting often required third-party dependencies on the host (Ceph needed the rbd library, GlusterFS needed mount.glusterfs), making deployment heavy. CSI solved both at once with “a containerized driver + a gRPC interface,” so FlexVolume was retired and CSI became the only choice.

In one sentence: provision lives in the Controller, attach lives in the Controller + VolumeAttachment, mount lives in the Node + kubelet. Three stages, three different objects — whoever breaks, look there.

2. A Full Postmortem of an Attach Deadlock

Setting the scene first. On a managed K8s cluster (K8s 1.32.x, cloud-disk CSI driver), after a routine node pool upgrade, a StatefulSet running the order database started a rolling update. The upgrade itself went smoothly — nodes were swapped one by one and the cluster reported all Ready. The problem only surfaced ten minutes after the upgrade finished.

The timeline looked roughly like this:

TimeSymptomWhat people assumed
T+0Node pool upgrade starts, old nodes drain outRoutine, unattended
T+8min2 of 3 StatefulSet replicas stuck in ContainerCreatingSlow image pull
T+15minkubectl describe pod shows FailedAttachVolumeBackend storage glitch
T+22minCloud console shows the disk is healthy, but the attach record points at a retired nodeState inconsistency suspected
T+30minAfter deleting one “ghost” VolumeAttachment, the first Pods come upRoot cause found

What we actually saw on the ground

Start with a few non-obvious symptoms — those are what makes this incident worth writing about. If you only looked at the Pod at the time, you would have found nothing.

First, the VolumeAttachment object’s nodeName pointed at an old node that no longer existed. The object should have been cleaned up when that node was retired, but it had not been — it was stuck there with a finalizer, status.attached stuck at false.

# Inspect each VolumeAttachment; focus on nodeName and attached
kubectl get volumeattachment -o wide
# NAME           ATTACHER          PV              NODE          ATTACHED   AGE
# csi-xxxx       disk.csi.xxx      pvc-9f...       old-node-3    false      21m   <-- ghost

kubectl get volumeattachment csi-xxxx -o yaml

Second, VolumesAttached and VolumesInUse did not match. On a node object, status.volumesAttached records “volumes I attached,” while status.volumesInUse records “volumes I am currently using.” When an old detach never finished and a new attach was coming in, these two sets drifted apart, and the attach/detach controller — unable to tell whether the volume was still on the old node — refused to let it through.

kubectl get node old-node-3 -o jsonpath='{.status.volumesAttached}' | python -m json.tool
kubectl get node old-node-3 -o jsonpath='{.status.volumesInUse}' | python -m json.tool

Third, the kubelet log and the controller log were saying two different things. The kubelet side was shouting Volume not attached; the attach/detach controller side was waiting for external-attacher’s ControllerUnpublishVolume to return. One waiting for the other to move first, the other waiting too — a textbook deadlock.

# Node side: you will see "Volume not attached" / "WaitForAttach"
journalctl -u kubelet --since "30 min ago" | grep -i -E "attach|mount|volume"

# Control-plane side: the external-attacher container log
kubectl -n kube-system logs deploy/csi-<driver>-controller -c external-attacher --tail=100

Root cause: the “double lock” behind attach/detach

Put those three symptoms together and the root cause is clear. It is a classic defensive design in distributed systems — understanding it is what lets you see why “deleting an object” can put out the fire.

To guarantee that a single volume is never written by two nodes at once (a double-write corrupts the filesystem outright), the system actually has two locks that never talk to each other:

  • The first lock, the control-plane state machine: before attaching a volume to node N, the attach/detach controller must confirm the volume has been cleanly detached from any other node, and to do that it sends ControllerUnpublishVolume.
  • The second lock, the actual mount on the node: the kubelet manages the real mount points through its volume manager, and only it knows whether the mount has actually been unmounted.

Normally the two coordinate: detach first, then attach. But when the old node went down abnormally — deleted outright, or swapped out during an upgrade — the ControllerUnpublishVolume sent by the control plane may never get a clean response. So the VolumeAttachment stays stuck with its finalizer, and the second lock never releases.

For a verifiable version of this incident, I found a very similar public case: on a managed K8s cluster (K8s 1.32.6, disk CSI driver v1.33.2), after a node pool upgrade, many VolumeAttachment objects still pointed at old nodes, the driver could not converge state, and workloads ended up stuck in ContainerCreating for a long time (see the Microsoft Q&A in the references below). So this is not a one-off — it is a systemic seam between node lifecycle and the storage state machine.

There is an easily overlooked point here: deleting a node is not the same as unmounting its volumes. Deleting a cloud machine is fast, but the block device attached to it needs an explicit detach to really be released. Node replacement during upgrades, scale-down deletion, and Spot instance reclamation are all high-frequency triggers.

Three intuitions that led us astray

In the postmortem we listed the three intuitions that were wrong at the time. Writing them down saves the next person some time:

  1. “The disk is healthy, so storage is fine.” The cloud console reflects only the backend state, not the state machine between K8s and the backend. The backend can be perfectly fine while a VolumeAttachment is deadlocked.
  2. “Just restart the Pod and it’ll be fine.” Restarting only replays the same deadlock, and it washes away the scene (timestamps, logs, object state). For storage failures, the first step is always evidence-gathering, not restarting.
  3. “It must be the storage vendor’s problem.” This time, the cloud-disk backend never made a single mistake; it was purely a failure of K8s-side state convergence. Understand your own state machine first, then go looking elsewhere.

What we did, and the order I would use today

The firefight that day went like this: we located the VolumeAttachment whose nodeName pointed at the old node, confirmed the old node was truly down and no other writer was touching the disk, then stripped the finalizer and deleted the object, and restarted the corresponding CSI controller so a fresh attach would be issued. All three replicas recovered within ten minutes.

But looking back, the sequence had spots that could have been safer. A robust cleanup order should be:

  1. Freeze first: scale the affected StatefulSet to 0 or suspend it, so no new Pod is racing for the volume;
  2. Verify next: confirm the old node is truly terminated and the volume has no other live mount/writer on the storage backend;
  3. Preserve evidence: capture the VolumeAttachment, the node’s volumesAttached/volumesInUse, and the CSI driver logs for the incident report;
  4. Clean up last: delete the ghost VolumeAttachment, restart the CSI controller if needed, then bring the workload back up gradually.

That order buys you rollback room: if the volume turns out to still be written by the old node, you can stop — instead of discovering it only after the data has already been corrupted by a double-write.

3. The PV, PVC, StorageClass Trio and the StatefulSet Storage Template

After the incident, let’s backfill one layer of foundation. CSI is the “how to mount”; PV, PVC, and StorageClass are the “what to mount, how to request it, how it is provisioned.” The boundaries among these three are the shared premise for every decision that follows.

ObjectScopeOne-line roleWho creates it
StorageClassClusterThe “template” for storage: which driver, what parameters, what binding/reclaim policyAdmin
PersistentVolume (PV)ClusterA physically existing piece of storage (the actual volume)Admin (static) or provisioner (dynamic)
PersistentVolumeClaim (PVC)NamespaceThe application’s “order form” (how big, which access mode)App / developer

The relationship is one-directional: a PVC requests → matches or dynamically creates a PV → binds → the Pod gets the volume through the PVC. Applications only ever write a PVC, never a PV — that is the key to this design, keeping “what I want” separate from “how it is delivered,” so apps can move across environments.

In production, the most common setup is letting StatefulSet manage its own PVCs via volumeClaimTemplates. Each replica gets its own independent PVC whose lifecycle follows the replica (named like <template>-<statefulset>-<ordinal>):

apiVersion: apps/v1
kind: StatefulSet
metadata:
  name: order-db
spec:
  serviceName: order-db
  replicas: 3
  selector:
    matchLabels: { app: order-db }
  template:
    metadata:
      labels: { app: order-db }
    spec:
      containers:
        - name: mysql
          image: mysql:8.0
          volumeMounts:
            - name: data
              mountPath: /var/lib/mysql
  volumeClaimTemplates:                 # each replica gets its own PVC, never shared
    - metadata:
        name: data
      spec:
        accessModes: ["ReadWriteOnce"]  # block storage: read-write on a single node
        storageClassName: disk-ssd-wffc
        resources:
          requests:
            storage: 100Gi

Two things you must remember:

  • The PVCs created from volumeClaimTemplates are not reclaimed when the StatefulSet is deleted. You delete statefulset, and those three disks are still there. It is a safeguard, and it is also a trap — many “unclaimed disks sitting in the cluster” come from exactly this, and they quietly become an ongoing bill. To truly clean up, you must delete the PVCs explicitly.
  • Each Pod in a replica set uses its own volume. If you want them spread across different nodes (so a single-node failure doesn’t take down the whole replica set), pair this with podAntiAffinity. That ties directly into the RWO semantics below.

Static vs dynamic provisioning

One frequently confused distinction worth a sentence:

  • Dynamic provisioning (the overwhelming majority of production cases): no PV is pre-created. As soon as a PVC is submitted, external-provisioner calls CreateVolume to create one on the fly, then creates and binds the PV. Less toil, more elasticity, and expansion/snapshot capabilities are more complete.
  • Static provisioning: an admin pre-creates a PV and the PVC matches it. Good for “the disk already exists, I just need to attach it.” Such PVs often do not get conveniences like dynamic expansion, and the operational cost is higher.

In one sentence: dynamic provisioning is the default; static provisioning is a patch. Prefer dynamic, and don’t drag storage back into the manual era just for the feeling of “control.”

4. Decision 1: Start with kubelet on the Way In, Then Look Back at the Controller

After that incident, I locked in a debugging order: look at kubelet and VolumeAttachment first, then the events, and only then look back at the Pod.

The reasoning is simple: the Pod is just the final symptom; its state is decided upstream. Staring at the Pod, you will only ever see “it didn’t come up,” never “why it didn’t come up.” The VolumeAttachment and the control-plane logs are where the decisions actually happen.

I turned it into a “symptom → look here first” mapping table, so at night you can just type along:

Symptom (event keyword)Look here firstCommon root cause
FailedAttachVolumeVolumeAttachment, external-attacher logGhost VA stuck on finalizer, attach timeout, per-node volume limit exceeded
FailedMount / Volume not attachedThe specific node’s kubelet logNode missing driver/client, NodeStage failure, leftover mount point
Multi-Attach error for volumeVolumeAttachment nodeNameVolume attached to two nodes at once (an RWO volume contended by shared Pods)
PVC stuck Pendingexternal-provisioner log, StorageClassprovisioner mismatch, unsatisfiable topology constraint, quota/backend capacity
PV flips Bound → AvailablePV/PVC, the StorageClass reclaimPolicyVolume wrongly released, Retain needing manual reclamation

When debugging, three “skeleton keys” cover almost every storage failure:

# 1) Event stream — watch the recent timestamps, don't get misled by historical events
kubectl get events -A --sort-by=.lastTimestamp | tail -40

# 2) The binding and attach chain (PVC -> PV -> VolumeAttachment, one chain)
kubectl get pvc,pv -A -o wide
kubectl get volumeattachment -o wide

# 3) The specific node's kubelet (far more informative than describe pod)
journalctl -u kubelet -n 200 --no-pager | grep -i -E "attach|mount|volume|disk"

My take: do not reach for kubectl delete pod as a retry first thing. A retry just replays the same deadlock and messes up the scene. The first step in a storage failure is always evidence, never restart. A problem a restart fixes will usually come back at the next upgrade anyway.

A six-step debugging SOP you can type along with

Turn the reasoning into a fixed order, so you don’t have to improvise during an incident:

  1. Read the Pod events to pin down “which stage” plus “which object.”
    kubectl describe pod <pod> -n <ns> | sed -n '/Events/,$p'
    
    Keyword triage: Attach-related → control plane; Mount-related → node.
  2. List the relevant VolumeAttachment and find its nodeName.
    kubectl get volumeattachment -o wide | grep -i <pvc-or-pv>
    
  3. Check whether the node that nodeName points at still exists.
    kubectl get node <node> -o wide
    
  4. Read the control-plane sidecar log (external-attacher / external-provisioner).
    kubectl -n kube-system logs deploy/csi-<driver>-controller -c external-attacher --tail=200
    
  5. Read the node’s kubelet log (when the event is Mount-related).
    journalctl -u kubelet -n 200 --no-pager | grep -i -E "attach|mount|volume"
    
  6. Cross-check three states: the VolumeAttachment’s attached, the node’s volumesInUse, and the actual mount record on the storage backend. Only when all three agree is it truly normal.

The value of this order: the first two steps triage eighty percent of cases into “control plane” or “node”, and only the next two go dig into specific logs. Don’t open with the kubelet log — it is the most informative path, and also the slowest.

5. Decision 2: Spotting and Safely Cleaning a Ghost VolumeAttachment

As mentioned, deleting a ghost VolumeAttachment put out that fire. But this action is the most dangerous one in this article — delete the wrong one and you get a double-write and data corruption. So it deserves its own section.

How to recognize a “ghost”

A ghost VolumeAttachment has several typical tells; two or more together is usually conclusive:

  • spec.nodeName points at a node that no longer exists or is NotReady;
  • status.attached is stuck at false, and status.attachError mentions a timeout or that the node cannot be found;
  • The object carries a deletionTimestamp (it is being deleted) but cannot be removed because of finalizers;
  • The volume is actually already detached on the storage backend, but K8s has not synced to that.
# One-shot scan for suspects: node missing + has a finalizer
kubectl get volumeattachment -o json | python - <<'PY'
import json,subprocess,sys
data=json.load(sys.stdin)
nodes={n['metadata']['name'] for n in json.loads(subprocess.check_output(
    ["kubectl","get","nodes","-o","json"]))['items']}
for va in data['items']:
    name=va['metadata']['name']
    node=va.get('spec',{}).get('nodeName')
    fins=va['metadata'].get('finalizers',[])
    attached=va.get('status',{}).get('attached')
    if node not in nodes or (fins and va['metadata'].get('deletionTimestamp')):
        print(f"{name}\tnode={node}\tattached={attached}\tfinalizers={fins}")
PY

Why you cannot “just delete it”

Because a VolumeAttachment exists precisely so K8s can act as the gatekeeper against double-writes. Delete it and you bypass the gatekeeper. If the old node is in fact still writing to that disk (say it is only NotReady but its processes are still running, or a network partition leaves information and reality out of sync), once the new node gets the disk, you have two writers, and they will corrupt the filesystem.

This kind of damage is often irreversible: once filesystem metadata is overwritten, fsck may not save you.

The standard safe-cleanup procedure

So before cleaning up, confirm three things: the old node is truly no longer running, the storage backend confirms no live attachment, and no other Pod is contending for it. With all three in hand, go:

# 1) Freeze the workload to avoid new contention
kubectl -n <ns> scale statefulset <name> --replicas=0

# 2) Confirm the volume's attach/connection state from the storage backend side
#    (commands differ per vendor; for a cloud disk, check the console/CLI for any "attached/connecting" record)

# 3) Strip the finalizer and delete the ghost object
kubectl patch volumeattachment <va-name> --type=merge \
  -p '{"metadata":{"finalizers":[]}}'
kubectl delete volumeattachment <va-name> --wait=false

# 4) Let the CSI controller re-issue the attach (rollout-restart the controller)
kubectl -n kube-system rollout restart deploy/csi-<driver>-controller

# 5) Bring the workload back up gradually
kubectl -n <ns> scale statefulset <name> --replicas=3

My take: rather than fight the fire by hand every time, turn this cleanup into automation with safety checks (see section 12). The biggest risk in manual work is not slowness — it is that “at 3 AM, the hands move faster than the judgment.”

6. Decision 3: The Real Semantics of accessModes — RWO Is Not “Single Pod Read-Write”

You cannot govern storage without facing accessModes. I have seen far too many people read it as “how many Pods can use this volume,” and then step in a hole. The real semantics are entirely different.

accessModes constrains the node scope of the mount, not the Pod count. See the table:

accessModeReal meaningTypical backendCommon misuse
ReadWriteOnce (RWO)Read-write on a single node; multiple Pods on that node can share itCloud disk, local disk — block storageThinking “only one Pod can use it,” so requesting a separate disk for each co-located replica
ReadOnlyMany (ROX)Read-only on many nodesNFS/file storageWriting to a read-only volume; writes fail
ReadWriteMany (RWX)Read-write on many nodesNFS/CephFS and other file storageForcing block storage into RWX; it won’t mount
ReadWriteOncePod (RWOP)Read-write by a single Pod (in newer versions)Requires driver supportOlder clusters/drivers don’t support it; putting it in YAML just fails

There is a very easily overlooked consequence: if an RWO volume gets scheduled to two different nodes, it triggers a Multi-Attach error. Because a single block device physically cannot be attached to two machines at once.

# The typical error — see it and go check accessModes and the scheduling policy
# Multi-Attach error for volume "pvc-xxxx" Volume is already used by pod(s) ...

Only when you truly want “a single Pod exclusively” should you use RWOP; when you want “co-located replicas sharing one disk,” RWO is enough. And block storage can never give you cross-node RWX — that is a physical limit, not a configuration problem.

My recommendations:

  • For database-style stateful services: use RWO, and pair it with StatefulSet + podAntiAffinity to spread the Pods of one replica set across nodes, plus an application-level constraint that only one instance writes at a time;
  • For multi-node sharing (log archiving, shared cache, file upload): go straight to file storage with RWX; don’t force it onto block storage;
  • For strong consistency and Pod-level exclusivity: use RWOP, but confirm the driver and the cluster version both support it first.

One related note: the volume reclaim policy (reclaimPolicy) is also frequently overlooked. For production data I use Retain uniformly — I would rather have a messier deletion than have a single slip of a Delete wipe out the data volume together with the backend disk.

7. Decision 4: Topology Awareness and volumeBindingMode — Why Cross-AZ Volumes Won’t Bind

In a single-AZ small cluster, topology rarely bothers you. The moment you go multi-AZ, the “location” of storage starts to bite.

Block storage has a physical property: a cloud disk lives in exactly one availability zone. If the Pod is scheduled into zone B while its volume is in zone A, attach fails — not because the driver is broken, but because the volume cannot move.

K8s handles this with two things:

  • volumeBindingMode: WaitForFirstConsumer: wait until the Pod is scheduled and the node’s zone is known, then create/bind the volume so the volume and the Pod land in the same zone. This is nearly mandatory in a multi-AZ cluster.
  • allowedTopologies: further restrict the zones, so volumes don’t get created in zones you don’t want.
apiVersion: storage.k8s.io/v1
kind: StorageClass
metadata:
  name: disk-ssd-wffc
provisioner: disk.csi.example.com
volumeBindingMode: WaitForFirstConsumer   # key: delayed binding, follows the Pod's zone
allowVolumeExpansion: true                # allow online expansion
reclaimPolicy: Retain                      # retain production data, prevent accidental deletion
parameters:
  type: ssd
allowedTopologies:                          # configure per your actual zones
  - matchLabelExpressions:
      - key: topology.kubernetes.io/zone
        values:
          - cn-east-1a
          - cn-east-1b

There is also a hidden card: the number of volumes a node can attach is capped. That cap is reported by the driver via NodeGetInfo and stored in the CSINode object. Large instance types can take dozens; small ones may take only a few. The scheduler consults it when placing Pods, and once a node’s volume “slots” are full, new stateful Pods cannot be scheduled there.

# See a node's volume cap and usage
kubectl get csinode <node-name> -o yaml
# Look at allocatable and the driver-related capacity info under drivers[]

My take: Immediate binding is workable in a single-AZ cluster, but in a multi-AZ setup it is pure self-inflicted pain — switch to WaitForFirstConsumer across the board. Also, do not pile a heap of high-IO stateful services onto the same large node: volume slots and IO are shared resources, and when that node goes down, everything shakes with it.

For a more systematic view of “failure domains,” see Related: Service Dependency Mapping and Failure Domain Analysis: From Topology Discovery to Blast Radius Control — binding storage to a zone is, at its core, narrowing the blast radius.

8. Decision 5: What Online Expansion Can and Cannot Do

Running out of storage and needing to expand is the most everyday requirement, and also where the semantic traps pile up. First, be clear about the can and cannot.

Can do: online expansion of a PVC (most drivers supporting allowVolumeExpansion can do it without interrupting the workload).

Cannot do: shrink. K8s natively does not support making a PVC smaller. Once you expand to 200Gi and realize it was too much, the only option is to create a smaller PVC and migrate the data. I have seen a developer ask “can we shrink it back,” and the ops engineer spent ages before discovering it simply cannot be done — that is something to tell the business before expansion, not after.

The online-expansion path looks like this:

Edit the PVC spec.resources.requests.storage
   │
   ▼
external-resizer ──▶ CSI Controller: ControllerExpandVolume   (expand the backend disk first)
   │
   ▼
Filesystem expansion (done by kubelet / CSI Node at the right moment)
   │
   ▼
PVC.status.capacity updates to the new size

Three must-checks before you touch anything:

# 1) Confirm the PVC's current state and capacity
kubectl get pvc <name> -n <ns>
# 2) Confirm its StorageClass has allowVolumeExpansion on
kubectl get storageclass <sc> -o jsonpath='{.allowVolumeExpansion}'
# 3) Confirm the backend really supports online expansion (most often skipped, most often where it goes wrong)
#    Some file storage, some RWX volumes, and statically provisioned PVs may not support online expansion
# It must be explicitly enabled in the StorageClass, or editing the PVC will do nothing
apiVersion: storage.k8s.io/v1
kind: StorageClass
metadata:
  name: disk-ssd-wffc
provisioner: disk.csi.example.com
allowVolumeExpansion: true

A few places that really do get stuck (the kind of detail others rarely tell you):

  • Some drivers claim to support expansion but require the workload to be stopped and the mount broken before the filesystem can be grown — meaning a service interruption;
  • When expansion fails mid-way, the PVC can get stuck in an intermediate state, with capacity neither fully changed nor the volume usable. Do not keep re-editing requests.storage at that point; pull the failed ControllerExpandVolume log first;
  • The expansion behavior of RWX/file-storage volumes is different from that of block storage. Don’t blindly apply block-storage experience to them.

My take: with expansion, you only really understand it once you treat “expansion failure” as a scenario to be designed for. Suggestions:

  1. Monitor PVC usage; warn at 80%, expand automatically or manually by 90% — do not wait for no space left on device;
  2. Automate the expansion, but keep failure alerting; don’t make it a “click it and forget it” action;
  3. For production data, always set reclaimPolicy to Retain; expansion and reclamation are two switches that must be understood separately.

On the other side of data safety — backup and recovery — I wrote it up in detail in Related: Kubernetes Disaster Recovery: From etcd Backup to Velero. Expansion only answers “is there enough”; backup answers “what if it’s gone.” Neither substitutes for the other.

9. Decision 6: Build Your Own CSI or Use a Managed/Community Driver

This is the line I most want people to stay calm about. Since CSI decouples the driver from K8s, it is tempting to think: “since it is decoupled, I can write my own.” Technically, sure — but think through the cost first.

Look at how many boundaries a single volume operation crosses: the gRPC interface must stay stable, the sidecar versions must match, the driver must stay consistent with the kubelet’s CSI calling conventions, and it must pass the CSI conformance test — otherwise a K8s upgrade can trip over an interface change at any time. This is not a “implement a few functions” job.

I have built a self-developed Go ops platform (Gin + gRPC, a DAG scheduling engine), and my feelings about “reinventing the wheel” are complicated. Reinventing gives you control, but the maintenance cost compounds year after year. Storage drivers especially: they manage data directly, and the cost of a single incident far outweighs the small amount of customization you save day to day.

Here is a decision table that tries to be actionable:

ScenarioRecommendationReasoning
Using mainstream cloud disk/file storageUse the cloud vendor’s managed CSI driverVendor-maintained, tracks K8s versions, support when it breaks
Using open-source storage (Ceph, Longhorn, etc.)Use the community CSI driverActive community, conformance assured
You have a special in-house storage backendBuild your own, but pass conformance firstOne of the few cases that justifies it, provided the interface strictly follows the standard
You just “want deep control over mount behavior”Check whether driver options are enoughMost customization needs are covered by standard-interface config
Compliance requires you to own the driverBuild your own, but budget the headcountLong-term maintenance + version tracking + failure coverage all need people

My take: unless you have an in-house storage backend or a clear compliance requirement to own it, do not build your own CSI driver. Spend the effort on “using the managed driver correctly” and “governing the state machine” — the payoff is far larger. If you truly must build your own, pass conformance first, then talk about shipping.

10. Node Maintenance and Volume Detach: drain, Scale-Down, and Spot Reclamation Done Right

The trigger of the incident in section 2 was a “seemingly harmless” node pool upgrade. So the other side deserves its own treatment: how to keep active node operations from deadlocking the storage state machine. These are not mysteries — there are correct postures.

What a volume goes through when you drain a node

kubectl drain does two things: marks the node unschedulable (cordon), then evicts the Pods on it. For a stateful Pod, eviction means the volume must detach — the kubelet first does NodeUnpublishVolume and NodeUnstageVolume, then the control plane updates the VolumeAttachment accordingly. Only when this chain completes cleanly is the volume properly released.

The correct posture has a few parts:

# 1) Make sure a PDB protects the workload (every stateful app should have one)
kubectl get pdb -A

# 2) Drain gently, leaving room for graceful shutdown and volume detach
kubectl drain <node> --ignore-daemonsets --delete-emptydir-data --grace-period=120

# 3) After the drain completes, confirm no volume is still "in use" on the node
kubectl get node <node> -o jsonpath='{.status.volumesInUse}'
# The expected result is an empty array; if it is not, do not rush to reinstall/delete the node

That last step is the key one: a successful drain does not mean the volumes detached cleanly. If volumesInUse is still non-empty, a mount did not release — and if you then delete the node right away (especially in a scale-down), you are very likely manufacturing exactly the ghost VolumeAttachment from section 2.

Scale-down and Spot reclamation: the two biggest ghost-attach sources

  • Scale-down node deletion: the cloud platform generally deletes the instance directly without waiting for K8s. The node is gone in seconds, ControllerUnpublishVolume may never get a response, and a ghost VA is born. Do this: drain the target node first, confirm volumesInUse is empty, then delete.
  • Spot/preemptible instance reclamation: reclamation is “leave on the dot,” even less accommodating. Do this: do not run stateful workloads on Spot; if you must, use a reclamation flow with graceful shutdown and disk-detach confirmation, or simply restrict such workloads to data that can be rebuilt locally.

A checklist that can go straight into the on-call handbook:

Node actionPre-checkPost-check
drainPDB in place, replicas can migratevolumesInUse is empty
Scale-down node deletionDrained, volumes detachedVolumes attach cleanly on the new node
Spot reclamationAvoid stateful workloadsNo leftover VolumeAttachment
Node pool upgradeBatched, off peak hoursValidate stateful Pods recover batch by batch

My take: treat a “node action” as a process that needs sign-off, not a couple of commands. With batch actions like upgrades and scale-downs, the biggest cost is not the execution itself but cleaning up the ghost attachments afterward. Ten minutes of drain plus one glance at volumesInUse beforehand can save you two hours in the middle of the night.

11. Volume Snapshots and Cloning: The Other Leg of Backup

Expansion solves “not enough space”; snapshots solve “roll the data back.” In the CSI world these two travel different paths — snapshots are driven by external-snapshotter, the interface is CreateSnapshot/DeleteSnapshot, and the corresponding object is a CRD like VolumeSnapshot.

It is complementary to “regular full backups”:

  • Snapshot: seconds, incremental, space-efficient — good for “take a shot before a release, roll back easily if it fails,” but it depends on the underlying storage and cannot travel if you switch backends;
  • Backup: slow, space-hungry, but independent of the storage — the true last line of defense. Cross-cloud, cross-cluster, and ransomware resistance all come from backups, not snapshots.

A minimal snapshot declaration:

apiVersion: snapshot.storage.k8s.io/v1
kind: VolumeSnapshot
metadata:
  name: order-db-before-upgrade
  namespace: prod
spec:
  volumeSnapshotClassName: csi-example-snapshotclass
  source:
    persistentVolumeClaimName: data-order-db-0

A few points that genuinely matter in production:

  • A snapshot is not a backup. A snapshot and its source volume share the same underlying storage; lose the storage account or suffer an AZ-level failure and the snapshot goes with it. Do not treat “I took a snapshot” as “I have a backup.”
  • Snapshot capability depends on the driver. Not every CSI driver implements CreateSnapshot; confirm support before declaring one, or the CRD will sit Pending forever.
  • Validate restores from snapshots. Whether the restored volume mounts and the data is intact is best verified by an occasional drill — not by discovering, when it actually matters, that the recovery flow is broken. This is part of disaster-recovery drills too: when I did cross-datacenter DR on a mobility project, the slow part was never “designing the RPO/RTO” but “actually running the recovery flow and finding it far more fragile than expected.”

In one line: snapshots give you “fast,” backups give you “safe.” You need both, and neither replaces the other.

12. Making Storage Failures Self-Healing

The previous chapters are all about “how to dig and fix after it breaks.” But what really separates SRE from ordinary ops is how to make failures surface on their own, and even recover on their own.

The biggest lesson from that incident was not “we can’t debug,” but “we were woken by the business, not by monitoring.” The out-of-sync storage state machine is entirely visible in advance.

Which signals to capture

SignalWhat to look atAlert suggestion
Abnormal VolumeAttachmentattached=false and age > N minutes; nodeName pointing at a NotReady/missing nodeAlert if not converged within 5 minutes
CSI controller healthexternal-attacher/external-provisioner error counts and restart countsAlert on > 2 restarts/hour
Volume space watermarkPVC usageWarn at 80%, critical at 90%, trigger the expansion flow
Volume attach latencyThe attach/mount latency distributionAlert when P99 exceeds threshold (slowing mounts often precede a state-machine drift)
Node volume slotsCSINode used/limitWarn near the limit, to avoid stateful Pods failing to schedule

An example alert expression that can actually be used (the idea; adjust metric names per driver):

# Ghost VolumeAttachment: an object that has been un-attached for over 5 minutes (kube-state-metrics schema)
max_over_time(
  kube_volumeattachment_status_attached{attached="false"}[5m]
) == 1

Note: kube-state-metrics exposes “which VAs exist and what state they are in” — it does not tell you whether the node in nodeName still exists. That requires you to correlate VolumeAttachment.nodeName against the node list with your own query. This is exactly why “ghost attachments” need dedicated governance rather than being covered by a generic metric.

The boundaries of self-healing

Self-healing sounds lovely, but with storage you must be restrained. My principle: auto-retry what can be safely retried; anything irreversible goes through human confirmation.

  • Safe to automate: bounded retries after attach/mount failure (K8s already does this); expansion requests triggered by a usage watermark; cleaning up expired VolumeAttachments for which “the old node is confirmed terminated and the backend has no mount.”
  • Never automate: deleting a VolumeAttachment without confirming the old node’s state (double-write risk); auto-deleting PVCs/PVs; auto-reclaiming volumes.
  • The graduated approach: a cleanup script first produces a “to-clean list” and alerts; a human confirms before execution; once it runs smoothly long enough and the data is sufficient, consider auto-cleanup for objects that meet strict preconditions.

A report-only inspection skeleton

# Put it in cron, run once a day; only outputs the suspect VA list for the on-call to judge, never auto-deletes
kubectl get volumeattachment -o json | python - <<'PY'
import json,subprocess
vas=json.loads(subprocess.check_output(["kubectl","get","volumeattachment","-o","json"]))['items']
nodes={n['metadata']['name'] for n in json.loads(subprocess.check_output(
    ["kubectl","get","nodes","-o","json"]))['items']}
for va in vas:
    node=va.get('spec',{}).get('nodeName')
    if node not in nodes:
        print("SUSPECT:", va['metadata']['name'], "->", node)
PY

Wire it into a daily report or an alert, and you turn “woken by the business” into “seeing a list a day ahead.”

Core principle: monitoring is responsible for “seeing it,” automation for “retries and invariant checks,” and any operation with irreversible data impact always keeps a human gate.

13. Common Failure Cheat Sheet

Compress everything above into one table and stick it in the on-call doc:

SymptomMost likely root causeKey debugging command
Pod stuck ContainerCreating, event FailedAttachVolumeGhost VolumeAttachment, attach timeoutkubectl get volumeattachment -o wide, look at nodeName
Event Multi-Attach errorAn RWO volume contended by two nodesCheck accessModes and scheduling policy; look at the VA’s nodeName
Event FailedMount / Volume not attachedThe specific node missing driver/client, leftover mountjournalctl -u kubelet, ls /var/lib/kubelet/plugins
PVC stuck Pendingprovisioner mismatch, unsatisfiable topology, insufficient capacityexternal-provisioner log, kubectl get sc -o yaml
Cross-AZ volume won’t attachvolumeBindingMode: Immediate puts the volume in the wrong zoneCheck the StorageClass volumeBindingMode and allowedTopologies
Expansion has no effectallowVolumeExpansion off, or backend doesn’t support online expansionkubectl get sc -o jsonpath='{.allowVolumeExpansion}'
Node volume slots full, Pod won’t schedulePer-node volume limitkubectl get csinode <node> -o yaml
Data “mysteriously gone”Written to the container writable layer/emptyDir, or a wrong Delete policyCheck volumes/volumeMounts, check reclaimPolicy
Snapshot CRD stuck PendingDriver doesn’t implement CreateSnapshotCheck the driver docs and the external-snapshotter log
Unclaimed disks piling up in the clustervolumeClaimTemplates PVCs not cleaned with the workloadkubectl get pvc -A, reconcile against the bill

Summary

Back to that 2:40 AM incident. We fixed it in the end, but the real value is the lessons from the postmortem — and that is what this article wants to leave you with:

First, hold the responsibility boundaries tightly. CSI’s three stages — provision, attach, mount — map to different objects and different owners. Determine which stage is stuck first, then decide whose door to knock on. Ninety percent of storage failures are answered in VolumeAttachment and the kubelet log, not in the Pod’s describe output.

Second, treat “state-machine drift” as a first-class citizen. Ghost VolumeAttachments, volumesAttached and volumesInUse disagreeing, a detach that never gets a response — these are the seams between K8s and storage. A node being deleted is not the same as its volume being unmounted; whenever node lifecycle changes, watch the storage state machine closely.

Third, dig the semantics all the way down, not just to the surface. RWO constrains the node, not the Pod; WaitForFirstConsumer is basically mandatory in multi-AZ; PVCs can only grow, never shrink; RWX is a physical limit block storage cannot deliver; a snapshot is not a backup. These holes are rarely a knowledge gap — they are “I thought I understood.”

Fourth, everyday node actions also need a process and sign-off. drain, scale-down, Spot reclamation, node pool upgrades — all are high-frequency sources of ghost attachments. drain first, check volumesInUse, then delete. Fix the order, so that at 3 AM — when hands move faster than the brain — you still don’t create a disaster.

Fifth, pull failures back from “woken by the business” to “woken by monitoring.” The storage state-machine drift is entirely visible in advance. Capture VolumeAttachment anomalies, driver health, volume watermarks, and attach latency, and let monitoring speak first. Keep self-healing restrained — auto-retry what can be retried, and always keep a human gate on the irreversible.

And last, stay humble about “building your own.” CSI decoupling makes self-development technically feasible, but not automatically worthwhile. Unless you have an in-house storage backend or a hard compliance constraint, using a managed driver and governing it well is the easier and safer path.

Storage is the module that “has no presence normally, and is a big deal when it breaks.” It is worth spending a little more time on it — get the state machine, the semantics, and the gates right, once.

References & Acknowledgments

This article drew on the following materials during writing; thanks to the original authors for their contributions:

  1. Volumes — Kubernetes official documentation, CSI volume model and usage
  2. Container Storage Interface (CSI) Specification — CSI community, the csi.proto interface definition and architecture
  3. Sidecar Containers — Kubernetes CSI project, responsibilities of external-provisioner/attacher/resizer/snapshotter sidecars
  4. Persistent Volumes - Expanding Persistent Volume Claims — Kubernetes official documentation, online PVC expansion mechanism and limits
  5. Create and manage persistent volumes (PVs) with Azure Disks in Azure Kubernetes Service (AKS) — Microsoft, managed-cluster disk volumes and per-node volume limits
  6. AKS Node Pool Upgrade - Disk Attach Failure — Microsoft Q&A, a real case of ghost VolumeAttachments and recovery after a node pool upgrade
  7. Volume Expansion | Google Kubernetes Engine (GKE) — Google Cloud, prerequisites and ordering for volume expansion
  8. Uncovering a Kubernetes attach/detach controller logic bug that broke pod startup — Tencent Cloud Native team, the attach/detach controller state machine and a real-world case analysis

Thanks to the Cloud Native Computing Foundation for advancing the CSI standard, to the Kubernetes Storage SIG and the maintainers of the various vendor CSI drivers for their long-term work, and to Brendan Gregg and the Google SRE body of work for their troubleshooting methodology.