Kubernetes Networking and Stateful Workloads

Pods come and go. A Deployment replaces a failed Pod with a new one that has a new name and a new IP address, possibly on a different node. That is the property that makes stateless services easy to operate, and it is also the property that breaks two assumptions an application usually makes: that a peer can be found at an address it learned earlier, and that a file written yesterday will still be there today.

This post follows those two problems through Kubernetes. The first half covers how clients find Pods: Services, Ingress, and cluster DNS. The second half covers how data outlives Pods: persistent volumes, StatefulSets, backup, and the order in which to diagnose failures. The running example is an illustrative service called orders and an illustrative database that stores its data on a volume. Neither is a real system, and the names, ports, and numbers are assumptions chosen to make the mechanics visible.

What this post assumes

The post builds on Kubernetes controllers and workloads. From that post it assumes you can read a Pod, Deployment, and ReplicaSet manifest, know that labels and selectors connect objects, and understand that a controller reconciles observed state toward declared state. Everything about Services, DNS, volumes, and StatefulSets is explained here and does not depend on that post to carry the argument. General networking knowledge is also assumed: IP addresses, ports, TCP connections, DNS records, and the idea of a load balancer.

A note on evidence. No Kubernetes cluster was available while this post was written, so none of the kubectl commands or manifests below were applied to a cluster. Manifests were checked only for YAML syntax, and one small Python script reproduces the documented DNS search-list rule. The Python blocks are short calculation aids that make a documented rule or an assumed number concrete. They are excerpts: the output shown came from fuller local versions that also print headers and extra rows. Where the text states behavior, it comes from the Kubernetes documentation listed in the references. Where the text infers behavior from general networking or storage principles, it says so.

Services: a stable name and address in front of changing Pods

A Pod IP is a poor identifier. It is assigned when the Pod is created and disappears when the Pod does. A Service gives a set of Pods one stable virtual IP address and one DNS name, and it keeps the list of backing Pods up to date. The Kubernetes documentation describes the Pods behind a Service as usually chosen by a label selector, with a controller that continuously scans for matching Pods and updates the Service’s EndpointSlices.

Selector, EndpointSlices, and readiness

Three objects cooperate. The Service holds the selector and ports. The control plane creates EndpointSlice objects, labeled kubernetes.io/service-name: <service>, that list the addresses of the matching Pods. Each endpoint in a slice carries conditions. According to the EndpointSlice documentation, serving corresponds to the Pod’s Ready condition, terminating is set once the Pod has a deletion timestamp, and ready is a shortcut for serving and not terminating. The documentation notes that a slice holds at most 100 endpoints by default, so a Service with many backends is spread over several slices.

The practical consequence is that readiness decides whether traffic arrives. A Pod can be running and matched by the selector yet receive no Service traffic because its readiness probe fails. This is intended: a database that is still replaying its log, or an application still warming caches, should not receive requests. It also means that a wrong readiness probe produces a Service with zero usable endpoints even though kubectl get pods shows every container running. The docs describe publishNotReadyAddresses as a way to include not-ready endpoints; it exists for cases such as peer discovery during cluster bootstrap, and it should not be turned on to hide a failing probe.

How a virtual IP reaches a Pod

A Service’s cluster IP is not assigned to any network interface. According to the documentation on virtual IPs and service proxies, kube-proxy on each node watches Services and EndpointSlices and programs the kernel’s forwarding rules so that packets sent to the virtual IP are rewritten to the address of one ready backend. On Linux the supported modes are iptables, ipvs, and nftables; the documentation states the default is iptables at the version it describes and warns that the default is expected to change, so it recommends configuring the mode explicitly rather than relying on the default across upgrades. In iptables mode the backend is chosen randomly. Distribution is therefore not guaranteed to be even for a small number of requests.

Two properties follow that matter when you debug. First, a Service is a packet-level construct. The rewrite applies to TCP, UDP, and SCTP connections, so a Service does not understand HTTP and cannot route by URL path; that is the job of Ingress, covered below. Second, the choice of backend is made when a connection is created. We infer, from how destination rewriting works on connection-oriented traffic, that a long-lived connection stays with the backend it started on while rules change for new connections. If a client holds one HTTP/2 or database connection open for hours, adding replicas will not shift that connection. This inference is general networking behavior rather than a statement from the Kubernetes page, so verify it with your proxy mode and client before depending on it. The documentation does explain why Kubernetes uses proxy rules instead of DNS round-robin: clients often cache DNS answers longer than the advertised time to live, and many applications resolve a name once and keep the result.

Service types

The Service type controls how far the virtual IP is reachable.

TypeWhat it createsReachable fromUse it when
ClusterIP (default)A cluster-internal virtual IP and DNS nameInside the clusterService-to-service traffic, and the base of every other type
NodePortA ClusterIP plus a static port on every node’s IPAnything that can reach a node IPSimple external access, or as a building block for an external load balancer
LoadBalancerNodePort and ClusterIP, plus a request to the cloud provider for an external load balancerThe load balancer’s addressL4 external access, including non-HTTP protocols
ExternalNameA DNS CNAME to the value of externalName; no proxyingInside the clusterGiving an external hostname an in-cluster name
Headless (clusterIP: None)No virtual IP; DNS returns the Pod addressesInside the clusterClients that must address individual Pods, such as database members

The descriptions follow the Service documentation. The default NodePort range is not stated in the part of the Service page read for this post. The commonly used range is 30000 to 32767, but confirm it for your cluster’s API server configuration before opening firewall rules. A LoadBalancer Service depends on a cloud controller or an equivalent component to provision the load balancer. On a cluster without one, the Service is created and the external address stays pending. That is a symptom of a missing integration rather than a faulty manifest.

Ports, target ports, and named ports

A Service port list has three fields that are easy to confuse. port is the port the Service listens on. targetPort is the port on the Pod that traffic is delivered to, and defaults to port when omitted. A targetPort may also be a name that refers to a named containerPort in the Pod, so a Service can keep working when different versions of the Pod listen on different numbers. The next manifest is the illustrative orders Service and the Pod template fragment it depends on.

apiVersion: v1
kind: Service
metadata:
  name: orders
  namespace: shop
spec:
  selector:
    app.kubernetes.io/name: orders
  ports:
    - name: http
      port: 80
      targetPort: http      # refers to the named containerPort below
---
# Fragment of the Pod template in the orders Deployment
# spec.template.metadata.labels must include app.kubernetes.io/name: orders
#   containers:
#     - name: orders
#       image: registry.example.com/orders:1.0   # placeholder image
#       ports:
#         - name: http
#           containerPort: 8080
#       readinessProbe:
#         httpGet: { path: /healthz, port: http }

This manifest is an illustrative example written for this post and was syntax-checked only. Three independent mistakes each produce the same symptom, a Service that accepts connections and then fails: a selector that does not match the Pod labels (the Service has no endpoints), a targetPort that does not match the port the process listens on (endpoints exist but connections are refused), and a readiness probe that never succeeds (endpoints exist but are not ready). The debugging order later in this post separates them.

Source IPs and traffic policy

For traffic that enters through a NodePort or LoadBalancer, externalTrafficPolicy chooses between two behaviors, per the documentation on virtual IPs. With Cluster (the default) traffic may be forwarded to a backend on another node, and the client address is rewritten. With Local traffic goes only to backends on the receiving node and the client address is preserved. The trade is balance and availability against source visibility: Local keeps the client IP for logging or allow-lists, but a node with no local ready backend cannot serve the traffic, so the load balancer’s health checks matter. A separate setting, sessionAffinity: ClientIP, pins a client address to a backend for a configurable time, which can mask a load-distribution problem rather than fix it.

Ingress and the Gateway API: HTTP routing at the edge

A Service can expose a port. It cannot choose a backend by hostname or URL path, terminate TLS for several hostnames, or act on HTTP headers. Ingress is the Kubernetes API object for HTTP and HTTPS routing into the cluster. The Ingress documentation describes it as exposing HTTP and HTTPS routes from outside the cluster to Services inside it, based on rules you define, with capabilities such as load balancing, TLS termination, name-based virtual hosting, and path-based routing.

The controller is the implementation

An Ingress object is only a declaration. The documentation is explicit that you must have an Ingress controller installed, and that creating an Ingress without a controller has no effect. Different controllers implement it differently, and the ingressClassName field selects which controller handles a given object. If the field is omitted, a default IngressClass is used if the cluster defines one. Several controllers can coexist, each claimed by its own class. This is the same pattern as network policies, which also have no effect without an implementing component: the API server accepts the object whether or not anything enforces it, so acceptance is not evidence of behavior.

apiVersion: networking.k8s.io/v1
kind: Ingress
metadata:
  name: orders
  namespace: shop
spec:
  ingressClassName: example-class        # placeholder; must match an installed IngressClass
  tls:
    - hosts: ["orders.example.com"]
      secretName: orders-tls             # placeholder Secret holding the certificate
  rules:
    - host: orders.example.com
      http:
        paths:
          - path: /
            pathType: Prefix
            backend:
              service:
                name: orders
                port:
                  name: http

Each rule pairs an optional host with paths, and each path has a pathType: Exact matches the path string exactly, Prefix matches by path prefix, and ImplementationSpecific leaves the matching to the controller. Ingress only carries HTTP and HTTPS. For other protocols and ports, the documentation points to a Service of type NodePort or LoadBalancer.

Ingress is frozen; Gateway API is the recommended direction

The Ingress page states that the API is frozen: it is stable and will remain in Kubernetes, but no further development is planned, and the project recommends the Gateway API for new work. The Service page describes Gateway API as providing capabilities beyond Ingress and Service, implemented through custom resources. For a platform team this matters in two ways. Existing Ingress objects keep working and do not need an urgent rewrite. And routing features that Ingress never standardized, such as header matching or traffic splitting, have historically been expressed as controller-specific annotations. Annotations are not portable between controllers, so an Ingress that relies on them is tied to one implementation. Gateway API resource details were not read in depth for this post, so this post makes no claims about its resource model beyond the documentation’s recommendation.

How an HTTP request reaches a Pod

Putting the layers together, a request to https://orders.example.com/ passes through these stages, and each can fail independently.

  1. DNS resolves orders.example.com to the address of the external load balancer or node, outside the cluster’s DNS.
  2. The load balancer forwards to the Ingress controller Pods, which are ordinary Pods exposed by a LoadBalancer or NodePort Service.
  3. The controller terminates TLS using the referenced Secret, matches host and path, and chooses the backend Service named in the rule.
  4. The controller sends the request to a Pod address taken from the Service’s endpoints, or to the Service’s virtual IP, depending on the implementation.
  5. If it uses the virtual IP, the node’s proxy rules rewrite the destination to one ready Pod.

A 404 usually means the request reached a controller that had no matching host or path rule. A 502 or 503 usually means a rule matched but the backend had no ready endpoints or refused the connection. These status codes are produced by the controller and their exact meaning is controller-specific, so treat them as hints and check the controller’s logs.

DNS: names, search paths, and a hidden multiplier

Applications almost never use cluster IPs directly. They use names, and Kubernetes runs a DNS service for the cluster (CoreDNS in most clusters, discovered via the k8s-app=kube-dns label in the debugging guide) that creates records from Service and EndpointSlice objects.

The names Kubernetes creates

According to the DNS documentation, a normal Service named orders in namespace shop gets the name orders.shop.svc.cluster.local, which resolves to its cluster IP. A headless Service resolves the same name to the addresses of all its ready Pods. A Pod can be reached at a name derived from its IP address, for example 172-17-0-3.default.pod.cluster.local, and a Pod whose spec.hostname and spec.subdomain are set, with a subdomain matching a headless Service, gets a stable name of the form hostname.subdomain.namespace.svc.cluster.local. StatefulSet Pods use this mechanism, which is why they can have stable DNS names. Services with named ports also get SRV records of the form _port-name._port-protocol.my-svc.my-namespace.svc.cluster.local.

A query for the bare name orders works from a Pod in shop but not from another namespace. The documentation explains that queries without a namespace are scoped to the Pod’s own namespace, and that you use orders.shop to cross namespaces. That behavior is not a special lookup feature. It comes from the resolver’s search list.

Search lists and ndots

The resolver configuration inside a Pod looks like this in the documentation’s example: a nameserver address, a search line listing the namespace, service, and cluster suffixes, and options ndots:5. The Linux resolv.conf manual page defines the rule: a name with fewer than ndots dots is tried against each search-list entry in turn before being tried as an absolute name, and a name with at least ndots dots is tried as absolute first. The system default for ndots is 1, but Kubernetes sets it to 5.

This has a cost that is easy to miss. A short in-cluster name resolves on the first try. Any name with fewer than five dots that is not in the cluster, such as an external API hostname with two dots, is tried with every search suffix first. Each failed attempt is a separate query to the cluster DNS service, and the answer is typically negative. The next script models that rule using the namespace shop and five assumed names. It is a model of the documented rule, not a resolver, and it counts queries per record type. A real client typically asks for address records of both IP families, which would multiply the counts.

SEARCH = ["shop.svc.cluster.local", "svc.cluster.local", "cluster.local"]
NDOTS = 5

def candidates(name, search=SEARCH, ndots=NDOTS):
    if name.endswith("."):               # a trailing dot marks an absolute name
        return [name]
    suffixed = [f"{name}.{s}" for s in search]
    return [name] + suffixed if name.count(".") >= ndots else suffixed + [name]

EXISTS = {"orders.shop.svc.cluster.local",
          "payments.billing.svc.cluster.local",
          "api.example.com"}

def queries_until_answer(name):
    for i, c in enumerate(candidates(name), 1):
        if c.rstrip(".") in EXISTS:
            return i

A fuller version of this script, which also prints a header and the dot count of each name, was run on these names. The counts it printed are reproduced here.

orders                                       1
payments.billing                             2
payments.billing.svc                         3
payments.billing.svc.cluster.local           4
payments.billing.svc.cluster.local.          1
api.example.com                              4
api.example.com.                             1

The numbers are queries until an answer under the model’s assumptions. The fully qualified in-cluster name without a trailing dot has four dots, which is fewer than five, so it first goes through all three suffixes and fails before the absolute form succeeds. Adding the trailing dot removes the extra queries, as does lowering ndots for a Pod through the dnsConfig field of the Pod spec, which the documentation shows setting ndots as a resolver option (the DNS page’s example uses a value of 2). Whether the extra queries matter depends on query rate and on the cluster DNS capacity, which this script does not measure. The right use of the table is to explain why DNS query volume from a busy client can be several times its request volume, and to know where to look first when name resolution is slow.

DNS in the failure path

DNS problems often present as application errors, not network errors. The Kubernetes DNS debugging guide gives an ordered procedure: run a test Pod with DNS tools and query kubernetes.default; read the Pod’s /etc/resolv.conf and check the search list and ndots; confirm the CoreDNS Pods are running by label; read their logs; check that the kube-dns Service exists and exposes port 53 over UDP and TCP; and check that its EndpointSlices are populated. If even kubernetes.default fails, the cluster DNS path is broken. If it works but your Service name fails, the problem is the Service, the namespace, or the name you typed.

A default-deny network policy introduces a particularly confusing case. The NetworkPolicy documentation warns that a default deny-all egress policy also blocks DNS traffic, so workloads need a separate policy allowing egress to the cluster’s DNS service. After the policy is applied, name resolution fails and clients report connection errors for hosts they cannot resolve. Policies are additive and unordered, so the fix is a new allow rule rather than editing the deny rule. A refused connection is also not proof of a policy, because DNS, routing, a missing listener, or another firewall can look the same, so test with a control connection that should succeed.

Persistent storage: volumes, claims, and classes

Container filesystems are discarded with the container, and a Pod’s emptyDir volume lives only as long as the Pod. For data that must survive Pod replacement, Kubernetes separates the request for storage from the storage itself.

Three objects and one driver interface

The PersistentVolume documentation describes the split. A PersistentVolume (PV) is a piece of storage in the cluster, provisioned by an administrator or dynamically. A PersistentVolumeClaim (PVC) is a request for storage with a size and access mode. A StorageClass describes a kind of storage and the provisioner that creates it. The glossary entry on PersistentVolumeClaims covers the binding and reclaim behavior in short form, and this section explains the same mechanics with the reasons.

A claim goes through four phases in the documentation: provisioning (static, where an administrator creates PVs, or dynamic, where a StorageClass provisioner creates one for a claim), binding (a control loop matches a claim to one PV, one-to-one, with references in both directions), using (a Pod names the claim in its volumes), and reclaiming (what happens to the PV after the claim is deleted). A PV reports a phase of Available, Bound, Released, or Failed. Most real clusters use dynamic provisioning through a driver that implements the Container Storage Interface, and the same CSI driver typically supplies attach, mount, expansion, and snapshot support. Which of those features exist depends on the specific driver, not on Kubernetes alone.

Storage objects have different scopes. A PVC belongs to a namespace; a PV is cluster-scoped. A claim cannot be renamed or moved to another namespace, so changing ownership means a planned data transition. The documentation also describes a protection finalizer, kubernetes.io/pvc-protection, which keeps a claim that is in use by a Pod from being removed until it is no longer used.

Binding mode and topology

A StorageClass has a volumeBindingMode. With Immediate, which is the default, a PV is bound and provisioned as soon as the claim is created. With WaitForFirstConsumer, binding waits until a Pod using the claim is created, so the scheduler can take the Pod’s placement into account. The documentation recommends WaitForFirstConsumer for topology-aware provisioning such as zone-specific storage. Here is the failure it prevents, as an inference from the documented behavior: if a volume were created in one zone before the Pod was scheduled, a node-attached volume could be in a different zone from every node the Pod is allowed to run on, and the Pod would be unschedulable. A claim that stays Pending is not necessarily broken, either: under WaitForFirstConsumer it is expected to stay pending until a consumer exists. Check events on both the claim and the Pod.

Access modes

An access mode describes how a volume may be mounted, and the four modes are easy to misread.

ModeMeaning in the documentationCommon misreading
ReadWriteOnceRead-write by a single node; multiple Pods on that node can use itAssuming only one Pod can write
ReadOnlyManyRead-only by many nodesAssuming writes are impossible
ReadWriteManyRead-write by many nodes, where the driver supports itAssuming any storage class provides it
ReadWriteOncePodRead-write by exactly one Pod in the clusterAssuming it works with any driver

The StatefulSet documentation recommends ReadWriteOncePod for production, which prevents two Pods from mounting the same claim. That recommendation is useful for databases that must not have two writers. Whether a driver supports it must be checked per driver, because the documentation ties it to CSI. An access mode participates in claim matching and attach decisions. It is not an application-level lock, and it does not by itself make concurrent use safe.

Reclaim policy and the deletion chain

When a claim is deleted, the PV’s reclaim policy decides what happens next. Retain keeps the PV and the data and moves the PV to Released for manual handling. Delete removes both the PV object and the backing storage asset where the plugin supports it. Recycle is deprecated. The documentation states that a dynamically provisioned volume inherits the reclaim policy of its StorageClass, and that this defaults to Delete.

That default makes a dangerous chain: dynamic provisioning is the convenient route, the provisioned PV inherits the class policy, and the policy defaults to Delete. Deleting a claim, or the namespace that contains it, can therefore delete the underlying disk. For data you cannot regenerate, set Retain on the class, or change a specific PV with a patch as the documentation shows, and keep independent backups. Retain protects against an accidental claim deletion. It does not protect against corruption or against someone deleting the backing storage asset directly.

The next manifest shows a StorageClass written for that purpose. The provisioner name is a placeholder.

apiVersion: storage.k8s.io/v1
kind: StorageClass
metadata:
  name: db-retain
provisioner: csi.example.com            # placeholder CSI driver name
reclaimPolicy: Retain
volumeBindingMode: WaitForFirstConsumer
allowVolumeExpansion: true

Expansion deserves its own comment. allowVolumeExpansion: true lets you increase a claim’s requested size by editing it; the Storage Classes page lists CSI volume expansion as supported. Plan for growth only: the documentation read for this post describes increasing a claim, not shrinking one, so this post does not cover reducing a volume. Whether the filesystem is resized while mounted or at the next mount depends on the driver, so check its documentation before relying on online expansion.

Stateful workloads: identity and storage that survive replacement

A stateless Deployment treats Pods as interchangeable. Replicas share a Service, and killing one changes nothing the others depend on. The glossary entry on a stateless service describes the underlying property: later requests do not need to recover a particular instance’s previous local state. A database cluster, a message broker, or a consensus system violates this on purpose. Each member has its own data, its own identity in the group’s membership list, and rules about who may start first. A Deployment cannot give a replacement Pod its predecessor’s name or its predecessor’s disk.

What a StatefulSet guarantees

The StatefulSet documentation lists four properties: stable, unique network identifiers; stable, persistent storage; ordered, graceful deployment and scaling; and ordered, automated rolling updates. Each depends on specific fields.

  • Stable names. Pods are named with an ordinal suffix, web-0, web-1, and so on, and keep that name when they are replaced. The controller also labels each Pod with its name (statefulset.kubernetes.io/pod-name) and its ordinal (apps.kubernetes.io/pod-index).
  • Stable DNS through a headless Service. The StatefulSet’s serviceName refers to a headless Service, and each Pod is reachable at pod-name.service-name.namespace.svc.cluster.local. The documentation requires the headless Service to exist.
  • Per-Pod storage. When volumeClaimTemplates is set, each Pod gets its own PVC created from the template, and a replacement Pod reattaches to the same claim.
  • Ordering. The default podManagementPolicy, OrderedReady, creates Pods one at a time and waits for each to be ready; Parallel starts and deletes them without waiting.

A Pod is an execution attempt boundary, not a durable record, as the glossary entry puts it, and a StatefulSet is what attaches the durable part (identity and volume) to that attempt. The next manifest is an illustrative three-member set, with a placeholder image that stands for any database that stores files under one directory.

apiVersion: v1
kind: Service
metadata:
  name: orders-db
  namespace: shop
spec:
  clusterIP: None                 # headless: DNS returns Pod addresses
  selector:
    app.kubernetes.io/name: orders-db
  ports:
    - name: db
      port: 5432
---
apiVersion: apps/v1
kind: StatefulSet
metadata:
  name: orders-db
  namespace: shop
spec:
  serviceName: orders-db
  replicas: 3
  podManagementPolicy: OrderedReady
  minReadySeconds: 10
  persistentVolumeClaimRetentionPolicy:
    whenDeleted: Retain
    whenScaled: Retain
  updateStrategy:
    type: RollingUpdate
    rollingUpdate:
      partition: 0
  selector:
    matchLabels:
      app.kubernetes.io/name: orders-db
  template:
    metadata:
      labels:
        app.kubernetes.io/name: orders-db
    spec:
      terminationGracePeriodSeconds: 60
      containers:
        - name: db
          image: registry.example.com/orders-db:1.0   # placeholder image
          ports:
            - name: db
              containerPort: 5432
          readinessProbe:
            tcpSocket:
              port: db
          volumeMounts:
            - name: data
              mountPath: /var/lib/db
  volumeClaimTemplates:
    - metadata:
        name: data
      spec:
        accessModes: ["ReadWriteOncePod"]
        storageClassName: db-retain
        resources:
          requests:
            storage: 20Gi

The manifest is an illustrative example and has not been applied to a cluster. Read it as a set of decisions. serviceName ties the Pods to the headless Service so that orders-db-0.orders-db.shop.svc.cluster.local is a stable address. ReadWriteOncePod and the Retain class together express that each member owns one disk and that deleting the object must not delete the data. minReadySeconds delays treating a new Pod as available during a rolling update, which gives a crashing member a chance to fail before the controller moves on. A TCP readiness probe only proves that a port accepts connections. A database may accept connections before it is consistent, so a real probe should reflect the application’s own definition of ready.

Retention, scale-down, and the at-most-one rule

Three behaviors are about what the StatefulSet does not delete or do for you.

First, volumes. The documentation says scaling down or deleting a StatefulSet does not by default delete the PVCs created from its templates, which favors data safety. The persistentVolumeClaimRetentionPolicy field, with separate whenDeleted and whenScaled settings of Retain or Delete, changes that, and Retain is the default. Check the feature state for your cluster version before relying on the field, because the documentation described it behind a feature gate in the page text read for this post. After a claim is deleted, the PV follows its own reclaim policy, so two separate settings decide whether the data survives.

Second, termination. The documentation states that deleting a StatefulSet gives no guarantee that its Pods terminate, and recommends scaling to zero first for ordered shutdown. This matters because StatefulSets promise at most one Pod with a given identity at a time. The page on force-deleting StatefulSet Pods explains the risk: when a node is unreachable, a Pod can stay in Terminating or Unknown state because the kubelet cannot confirm that the process stopped. A force delete removes the API object and frees the name immediately, and the controller can start a replacement while the original process may still be running on the unreachable node. For a database with a fixed member identity this can mean two writers, which the page describes as a risk of duplication and data loss. Force deletion is a statement that you know the old process will never contact its peers again, and it should follow confirmation from the node, the cloud provider, or fencing, not the API.

Third, application behavior. The StatefulSet gives identity and storage. It does not replicate data, elect a leader, or fail over. The Kubernetes tutorial on replicated MySQL shows how those jobs are done by the application’s own mechanisms: an init container derives a role from the ordinal (ordinal 0 is the primary), replicas clone data from the primary, and replication is configured through the database’s own commands. The tutorial states that its configuration is not production-grade. Operators, which are controllers that encode an application’s operational knowledge, usually carry that logic in practice, and choosing one is a separate decision.

Updates that can wedge

Scale-down and deletion proceed in reverse order, from the highest ordinal to the lowest, with every successor fully shut down before a Pod is terminated. For updates, the partition field restricts a rolling update to Pods with an ordinal at or above the partition value, which supports staged, canary-style updates. With OrderedReady, the documentation warns that an update can reach a broken state that needs manual intervention: if the new template never produces a Running and Ready Pod, the controller stops the rollout and waits. In that state, restoring a good template is not by itself enough, because the Pod that was already replaced with the bad configuration also has to be repaired or deleted. Treat a StatefulSet update as one that needs a health check meaningful to the application and a way to stop between members. That is also why many teams prefer a managed database service for the storage layer when the application’s availability does not depend on running the database inside the cluster. A later post in this series weighs managed services against running the platform yourself.

Backup, restore, and what each layer protects

A backup that has never been restored is an assumption. Kubernetes holds three different kinds of state, and each needs a separate protection and a separate restore test.

StateWhere it livesTypical protectionWhat it does not cover
Cluster objects (Deployments, Services, PVC definitions)etcdDeclarative manifests in version control; an etcd snapshotData on volumes
Volume contentsThe storage backend behind each PVCSI volume snapshots, backend backups, application-level dumps or replicationCluster object definitions; application consistency by itself
Application meaning (a consistent database)The application’s files and logsThe application’s own backup tooling and replicationAnything outside that application

etcd snapshots restore cluster state, not data

The Kubernetes documentation on etcd shows etcdctl snapshot save for a point-in-time snapshot and etcdutl snapshot restore for recovery. It states that the restore recovers only the cluster state stored in etcd and does not restore PersistentVolume data or anything stored outside etcd. After an etcd restore, objects that reference volumes reappear. The volume contents are whatever the storage backend holds at that moment. For a managed Kubernetes service, the provider normally operates etcd and you may have no snapshot access, so the first question is what the provider offers and what the shared-responsibility terms say.

Volume snapshots

Kubernetes models snapshots with three custom resource types, as the VolumeSnapshot documentation describes: VolumeSnapshot (the user’s request, analogous to a PVC), VolumeSnapshotContent (the snapshot in the storage system, analogous to a PV), and VolumeSnapshotClass (driver parameters and a deletion policy of Delete or Retain). They work only with CSI drivers that support snapshots, and installation of the snapshot CRDs and controller is the responsibility of the cluster distribution. A snapshot can be restored by creating a PVC whose dataSource refers to it.

apiVersion: snapshot.storage.k8s.io/v1
kind: VolumeSnapshot
metadata:
  name: orders-db-0-pre-upgrade
  namespace: shop
spec:
  volumeSnapshotClassName: example-snapclass       # placeholder class
  source:
    persistentVolumeClaimName: data-orders-db-0    # PVC created from the StatefulSet template
---
apiVersion: v1
kind: PersistentVolumeClaim
metadata:
  name: data-orders-db-0-restored
  namespace: shop
spec:
  accessModes: ["ReadWriteOncePod"]
  storageClassName: db-retain
  resources:
    requests:
      storage: 20Gi
  dataSource:
    name: orders-db-0-pre-upgrade
    kind: VolumeSnapshot
    apiGroup: snapshot.storage.k8s.io

The PVC name data-orders-db-0 follows the pattern of template name, StatefulSet name, and ordinal, which is the convention for claims created from volumeClaimTemplates. This manifest has not been applied to a cluster. The glossary entry on snapshots makes the key distinction for any copy taken while writes continue: a copy over time is not automatically one consistent state. A volume snapshot captures the block device at a point in time. We infer, from that principle, that whether the files in a snapshot form a database state the application can start from depends on how the application writes: a database that journals its writes can usually recover from a snapshot taken while it runs, and one that keeps unflushed state in memory may not. The Kubernetes page does not promise application consistency, so check the driver’s and the application’s documentation, and quiesce or flush the application if recovery depends on it.

Backup objectives and a restore test

Two numbers define what a backup design must achieve: how much recent data you can afford to lose (the recovery point objective), and how long you can afford to be down (the recovery time objective). They come from the business owner of the data, not from the platform. A snapshot schedule of once a day implies a recovery point of up to a day, plus whatever time the restore takes. To know the real recovery time, restore into an empty namespace on a regular schedule and measure it: create the claim from the snapshot, start the application, run a consistency check, and compare a row count or checksum against an agreed source. An untested backup should be reported as unverified rather than as protection. The post on incident recovery validation extends this to rehearsing recovery as an exercise.

Putting independent copies outside the failure domain

A snapshot stored in the same storage system as its source shares the fate of that system. Account compromise, a deleted storage project, or backend corruption can remove both. The reclaim policy and snapshot deletion policy are the settings that decide whether an accidental delete in Kubernetes cascades to the backend. Keep at least one copy that a Kubernetes delete cannot reach and that credentials used by the cluster cannot erase. That requirement is a design principle, not a Kubernetes feature, and the right form (cross-region copy, logical dump to object storage with separate credentials, replication to a standby) depends on the objectives above.

Diagnosing failures in order

The most efficient way to diagnose a networking or storage failure is to follow the path a request or a byte takes and test one layer at a time. The Kubernetes guide for debugging Services follows the same idea: does the Service exist, does it resolve, is it defined correctly, does it have EndpointSlices, do the Pods respond directly, and is the proxy working. The commands below are the ones that guide and the DNS guide name; they were not executed for this post.

# 1. Does the Service exist and is it defined as intended?
kubectl get svc orders -n shop -o yaml
# 2. Does it have endpoints? An empty list means selector or readiness.
kubectl get endpointslices -n shop -l kubernetes.io/service-name=orders
# 3. Do the Pods match the selector and report Ready?
kubectl get pods -n shop -l app.kubernetes.io/name=orders -o wide
# 4. Test the Pod directly, then the Service name, from a test Pod in the same namespace
kubectl run -it --rm --restart=Never dbg -n shop --image=registry.example.com/dns-tools:1.0 -- sh
#    inside: nslookup orders ; nslookup kubernetes.default ; cat /etc/resolv.conf
# 5. Storage: claim state, bound volume, and events
kubectl get pvc -n shop
kubectl describe pvc data-orders-db-0 -n shop
kubectl get pv

The debug image is a placeholder for any image that contains nslookup and a client such as wget; the Kubernetes guide uses its own published test images. The table maps common symptoms to the first check.

SymptomFirst checkCommon causes
Service name does not resolvenslookup kubernetes.default from a PodCluster DNS down; wrong namespace in the name; default-deny egress without a DNS allow rule
Name resolves, connection refusedEndpoints exist and targetPort matches the processWrong targetPort; process bound to localhost only
Name resolves, connection times outEndpointSlices and readiness; network policyNo ready endpoints; policy blocking one side of the connection
Ingress returns 404Controller logs and the IngressClassNo controller for the class; host or path rule mismatch
Ingress returns 502 or 503The backing Service’s endpointsNo ready backend; wrong Service port
PVC stays PendingEvents on the claim and the Pod; the StorageClassWaitForFirstConsumer with no Pod yet; no default class; driver unhealthy
Pod stuck in ContainerCreating with a volumePod eventsVolume attach or mount failure; zone or node mismatch
StatefulSet Pod stuck TerminatingNode status and kubelet reachabilityNode unreachable; do not force delete before fencing
Data missing after a redeployReclaim policy, PVC retention policy, and PVC nameClaim deleted with Delete policy; template renamed so new claims were created

Two entries deserve a closing comment. A policy that blocks traffic from either side blocks the connection, since both the source’s egress and the destination’s ingress must allow it. And renaming a volumeClaimTemplate in a StatefulSet creates new claims on the next scale-up or replacement, and the old claims, with the data, remain unattached. We infer this from the naming convention, so confirm it in a test namespace before relying on it.

Choosing what to run inside the cluster

Kubernetes provides the machinery to run databases, but providing the machinery is different from providing the operational competence. In-cluster stateful workloads add duties that a team must own: volume sizing and expansion, snapshot and restore testing, upgrade sequencing, node maintenance that respects replica quorum, and recovery from a stuck Terminating Pod. A managed database service moves some of those duties to a provider and introduces its own constraints, such as supported versions and extensions, and a dependence on the provider’s recovery model. The comparison needs the same workload, the same objectives, and an honest estimate of staffing. The approach in the series continues with operating shared clusters, where node maintenance, quotas, and upgrades interact with the stateful behavior described here.

A practical rule follows from the evidence above. Run state inside the cluster when you can name who owns each of these duties and have tested the restore. Otherwise, treat stateful workloads as the part of the platform that deserves a managed service or a dedicated operator with an owner.

References


Discover more from Insightful Data Lab

Subscribe to get the latest posts sent to your email.

Similar Posts

Questions, corrections, or additional insights?

This site uses Akismet to reduce spam. Learn how your comment data is processed.