Running databases on Kubernetes with StatefulSets

A StatefulSet gives each database pod a stable name and its own volume, but it does not back up, fail over or upgrade the database for you. This page covers when to use it, how to configure it and when an operator or external database is the better choice.

On this page

Running databases on Kubernetes with StatefulSets: what it gives you and what it does not

A StatefulSet gives each database pod a stable identity, ordered start and stop, and its own persistent volume claim, but it leaves replication logic, failover, backups and upgrades to the database software and to your team. That split is the core of the decision. Teams reach this question when a self-managed cluster already hosts their applications and someone proposes moving a database onto it, usually to standardize tooling, reduce separate hosting, or keep data in the same infrastructure as the workloads. The StatefulSet answers only the question of where a pod runs and which volume follows it. It does not know whether a replica is in sync, whether a primary is healthy, or whether a backup can be restored.

Because of that split, the decision belongs to the team that will be paged for the database, usually the data platform or database administration group, with the platform team consulted on storage and node layout. Ask who will own replica promotion, backup verification, minor and major version upgrades, and restore drills before anyone writes a manifest. If the answer for any of these is "the StatefulSet handles it," the design is not ready. Confirm with the database vendor which replication and failover mechanisms it supports in a cluster you operate, and whether it publishes a tested Kubernetes deployment path. Also confirm what your storage backend guarantees when a node fails, since that determines how much the StatefulSet can protect you from a host outage.

A database operator, such as one for PostgreSQL or Kafka, adds the logic a StatefulSet lacks: controlled promotion, scheduled backups, certificate handling and version-aware rollouts. The alternative is an external managed or dedicated database outside the cluster, which moves those duties to a provider or a separate team but adds network latency and a second system to secure. Choose a plain StatefulSet mainly when the database software already has well-understood clustering that you can operate, when you are comfortable scripting its lifecycle, or when the workload is small and non-critical. Otherwise, an operator is usually the safer starting point. Each path has a different effort profile, and the quote you request should state which duties the partner takes on and which stay with your staff.

Configuration options and when each one fits

This table compares the StatefulSet settings that most affect a database: pod management, update strategy, storage templates and shutdown time. Read each row as a decision: when the setting suits a database, what it risks, and what to test in a non-production cluster before you rely on it.

SettingWhen it fits a databaseRisk to plan forTest before production
podManagementPolicy: OrderedReadyClustered databases where each member joins or replicates from a predecessor and startup order matters, such as a primary that must exist before replicas startA single unhealthy pod blocks creation or scaling of all later ordinals until it becomes ReadyKill the first pod and confirm the cluster recovers without manual steps, and time how long scale-out takes
podManagementPolicy: ParallelMembers that can start independently and discover peers through the cluster's own membership protocolMembers may bootstrap at the same time, so a badly written entrypoint can form split clusters or race on initializationScale from zero and from N to N+2, then confirm membership and data are consistent on every member
updateStrategy: RollingUpdate with partitionStaged rollouts where you update high ordinals first, check replication health, then lower the partition value step by stepPods below the partition keep the old revision, so version drift can persist if nobody lowers the partitionSet a partition, change the image, and confirm replication lag and client errors stay within your thresholds before each step
updateStrategy: OnDeleteDatabases where an operator or runbook must control each restart, such as a manual failover before the old primary goes downNothing rolls automatically, so forgotten pods can run old versions for months and skip security patchesDocument the delete-and-wait sequence per pod and rehearse it, including the case where a pod fails to come back
volumeClaimTemplatesPer-pod persistent volumes that stay bound to the same ordinal across restarts, which database data directories needClaims are not removed when the StatefulSet is deleted or scaled down, and changing the template later does not resize existing claimsConfirm the StorageClass, reclaim policy and expansion support, then delete and recreate a pod to verify its data follows it
terminationGracePeriodSecondsDatabases that need time to flush writes, step down as leader or close connections cleanly during a pod stopToo short a value risks unclean shutdown and recovery work; too long delays node drains and rolloutsMeasure real shutdown duration under load with your engine's own tooling and set the value above that measured time

Setup sequence for a database StatefulSet

This sequence turns a database idea into a StatefulSet that has been checked for replication, placement, disruption tolerance and recoverability before it carries production data. Each step closes with a test the team can run and record.

  1. Confirm the database handles its own replication

    Before writing any manifest, confirm that the database supports replication and clustering at the application level, with its own leader election, failover and data sync. A StatefulSet gives stable names and storage, but it does not replicate data between pods. The database team or the vendor documentation should answer how a replica is added, how a failed primary is replaced and whose data wins after a split. Done means a written answer for each question, plus a three-node test cluster that survives the loss of one pod without data loss. Confirm the exact behavior with the vendor for your version.

  2. Choose the StorageClass and reclaim policy

    Select a StorageClass whose provisioner matches the storage your platform offers, and check that it supports the access mode the database needs, usually ReadWriteOnce for a single pod per volume. Use WaitForFirstConsumer binding so volumes are created in the zone where the pod is scheduled. Set the reclaim policy deliberately: Retain is the usual choice for production data so a deleted claim does not delete the volume. Done means a test PVC binds in the intended zone, and a deleted test claim leaves the volume in the state you chose. Ask your storage team which expansion and snapshot features the driver supports.

  3. Create the headless Service

    Create a headless Service, with clusterIP set to None, that selects the database pods and is named in the StatefulSet's serviceName field. This gives each pod a stable DNS name, such as one based on the pod ordinal, which replication configuration depends on. Create a separate client-facing Service for applications so that clients do not need to know which pod is primary. Done means a debug pod can resolve each member's stable name and the database members can reach each other by those names. Confirm the DNS suffix and naming format against your cluster's DNS configuration.

  4. Spread pods across nodes and zones

    Define pod anti-affinity or topology spread constraints so that no two replicas share a node and, where your cluster has multiple zones, replicas are distributed across zones. Use required rules for the node spread if your replica count can be satisfied, and check that the scheduler will not leave pods pending during a drain. Done means that cordoning one node and draining it moves only one replica at a time, and that the replicas list the zones you expected. Record the node and zone labels the rules depend on, because a missing label silently disables the rule.

  5. Configure probes and update strategy

    Set readiness and liveness probes that reflect real database health, such as a query against the database rather than a process check, and set a startup probe if initialization or recovery is slow. Choose the StatefulSet update strategy and pod management policy deliberately: OrderedReady is the default and updates one pod at a time from the highest ordinal, while a partitioned RollingUpdate lets you stage changes. Done means a rolling update in a test namespace replaces one replica at a time, waits for readiness, and leaves the cluster healthy at each step.

  6. Add a PodDisruptionBudget

    Create a PodDisruptionBudget that allows at most one replica to be voluntarily disrupted at a time for a cluster that needs a quorum, and check that the value matches the quorum your database requires. Node maintenance, cluster autoscaling and upgrades all respect this budget. Done means a node drain in a test cluster is blocked when it would drop the database below quorum, and proceeds one replica at a time when it is allowed. Confirm with the database owner how many members can be lost before service stops.

  7. Prove failover and restore before production load

    Run a scheduled backup job to object storage or another location outside the cluster, then restore it into a scratch namespace and confirm the data matches the source. Also test a failover by deleting the primary pod and timing how long clients take to reconnect, and check that no acknowledged writes disappear. Done means a written test record showing the backup, the restore, the failover result and who approved the production load. Repeat these tests after each database version upgrade.

Spreading replicas across nodes and zones

Database replicas only protect you if the scheduler puts them on separate failure domains. The cards below cover the placement choices that decide whether one node or zone failure takes down several members at once, and the trade-off each choice carries. Confirm zone labels, node capacity and drain behavior in your own cluster before you fix any rule.

Required versus preferred anti-affinity

Required pod anti-affinity refuses to schedule a second replica onto a node that already runs one, so the scheduler never co-locates members. Preferred anti-affinity only expresses a weighted intent and may co-locate replicas when capacity is tight. For a database, required rules protect data but can leave the last replica Pending during scale-up or after a node loss, so check that spare nodes exist before you choose the strict form.

Pod placement docs

Topology spread constraints

Topology spread constraints set a maximum skew of pods across a topology key such as the hostname or zone label, and can hold a pod pending or let it schedule anyway depending on the whenUnsatisfiable setting. They suit StatefulSets that must balance across zones without forcing a hard rule on every node. Verify that the topology.kubernetes.io/zone label exists and matches the zones where your storage can actually attach.

Zone-aware volume binding

A StatefulSet's volumes are bound to the zone where the first pod lands unless binding waits for the consumer. Using a StorageClass with WaitForFirstConsumer lets the scheduler choose a node first and then provision the volume in that zone. Without this, a replica can be scheduled in a zone where its volume cannot be created, which leaves the pod stuck. Confirm that your CSI driver honors topology before you rely on it.

Dedicated node pools

Labeling and tainting a node pool for database workloads keeps noisy neighbors off the nodes that hold replicas and gives you a known capacity to schedule against. The cost is idle capacity and a second pool to patch and upgrade. Ask your team how many nodes per zone the pool needs so that losing one node still leaves room to reschedule a replica.

Behavior during node drains

A drain evicts pods one by one, and a PodDisruptionBudget can stop it when removing another replica would break quorum. Without a budget, operators may drain two members of the same database at once. Test a drain in a non-production cluster and confirm that the StatefulSet recreates pods on nodes that satisfy your placement rules, rather than waiting on capacity that is not there.

etcd operations docs

Strict placement against co-location risk

Strict placement protects quorum but makes the scheduler a source of outages when capacity is short, while loose placement keeps pods running and can quietly place two replicas in one failure domain. Decide which failure is worse for each database, document the choice, and alert on pods that remain Pending or on replicas sharing a zone. Confirm this trade-off with the database vendor's replication guidance for your version.

When an operator or an external database is the better choice

A raw StatefulSet gives a database stable pod names, ordered start-up and a volumeClaimTemplates block that creates one PersistentVolumeClaim per replica. It does not know how to promote a replica, take a consistent backup, or sequence a major version upgrade. Those tasks stay with your team, written as runbooks and scripts. An operator moves that logic into a controller that watches a custom resource and acts on it. The choice is therefore less about whether Kubernetes can run the database and more about who will own the failover, backup and upgrade behavior when something goes wrong at 2 a.m.

Operator routes make the most sense when your platform team wants database lifecycle handled in code and reviewed like any other manifest. For PostgreSQL, the CloudNativePG sibling page covers primary and replica clusters, failover, backups and point-in-time recovery. For Kafka, the Strimzi page covers broker, listener and certificate management. Read those pages for their operating models and confirm each operator's support matrix against your Kubernetes version before you commit. An external database fits better when ownership must sit outside the cluster team, when data volumes are large enough that you want dedicated storage hardware or a managed service, or when no one on the team has run that database engine in production before.

Decide before you write any StatefulSet manifest. Ask who will be paged for a failed replica, who approves a major version upgrade, where backups are stored and who tests restores. If the answers point to a database team outside the platform group, or to a cloud-managed service that already meets your data residency and audit requirements, an external database is usually the simpler path. If the answers point to your platform team with strong GitOps practice, an operator is the middle ground. A raw StatefulSet is the right choice only when you have the database expertise to write and test that lifecycle logic yourself.

Security and operational considerations for stateful pods

A StatefulSet holds data that outlives any single pod, so the controls around it matter as much as the manifest. The cards below cover the credentials, namespace policy, network paths, backup access and cluster upgrade order that protect a database running on Kubernetes. Check each one against your own design before the first production load.

Database credentials in Secrets

Database passwords, replication users and TLS keys usually live in Kubernetes Secrets, and Secrets are stored unencrypted in etcd by default. Confirm that encryption at rest is enabled for Secrets on your control plane, and check which key management the cluster uses for it. Mount credentials as files where the database supports it, and review whether an external store through the Secrets Store CSI Driver fits your secrets policy.

Secrets good practices

Least-privilege access to Secrets

Anyone who can list or watch Secrets in a namespace can read every database password stored there. Scope RBAC so that operators, CI pipelines and application service accounts each get only the verbs and resource names they need. Review the bindings for the StatefulSet's namespace regularly, since broad cluster-wide roles often grant this access without anyone noticing.

Pod Security Standards for the namespace

Kubernetes defines three Pod Security Standards, Privileged, Baseline and Restricted, and the built-in Pod Security Admission controller enforces them per namespace. Database pods rarely need host paths, privileged mode or host networking, so a Restricted or Baseline label on the namespace is a reasonable starting point. Test the database image against the level you choose, because some images expect to run as root or write to unusual paths.

Pod Security Standards

Network policies around database ports

A database port should accept traffic only from the application pods, backup jobs and monitoring agents that use it. Write NetworkPolicy rules that name those sources by label, and deny other ingress to the StatefulSet's namespace by default. Confirm that your CNI plugin enforces NetworkPolicy, because a policy object without enforcement protects nothing. Replication traffic between members also needs its own allowed path.

Snapshot and backup credentials

Backup jobs and volume snapshot workflows need credentials for object storage or the storage backend, and those credentials are a high-value target because they can read a full copy of the data. Store them in a dedicated Secret, grant them only write access to the backup bucket where possible, and rotate them on a schedule your security team sets. Ask who can trigger a restore, since restore access is often broader than backup access.

Upgrade order for the cluster

When the cluster itself moves between minor versions, kube-apiserver must be upgraded first, one minor version at a time, followed by kube-controller-manager, kube-scheduler and kubelets. Kubelets may be up to three minor versions older than kube-apiserver. Plan a database maintenance window around these node upgrades, and confirm that the StatefulSet's update strategy and PodDisruptionBudget will hold the database at quorum while nodes drain.

Version skew policy

Questions teams ask before running a database on Kubernetes

Is a StatefulSet enough to run a database on Kubernetes, or do I need an operator?

A StatefulSet gives each pod a stable name, a stable network identity and its own persistent volume claim, which is the foundation a database needs. It does not know how to bootstrap replicas, promote a new primary after failure, take consistent backups or perform a major version upgrade. For a simple single-instance workload or a system that replicates itself with well-understood procedures, a StatefulSet plus careful runbooks can be enough. When failover, backup and point-in-time recovery must run without someone typing commands at 3 a.m., a purpose-built operator usually earns its place. Choose based on which of those tasks your team will own and how often they will be exercised.

What drives the effort and cost of running a database on Kubernetes?

The main drivers are the number of database instances and environments, how much failover and recovery automation you require, the storage backend and its performance needs, the depth of backup and restore testing, and how many systems must integrate with identity, monitoring and secrets. Cost is split between one-time work (design, build, runbooks, restore drills) and recurring work (upgrades, patching, capacity changes, on-call and periodic restore tests). Ask any partner to separate these in a quote and to state which items the client's staff must perform. The same database often costs far more to operate when recovery was never rehearsed, so ask how testing is scoped.

How long does a database on Kubernetes project usually take?

Duration depends on scope rather than on the database name alone. A single development instance with a basic backup target is a much smaller piece of work than a highly available production cluster with tested point-in-time recovery, monitoring, access control and an upgrade plan. Time is also consumed by decisions your organization has not made yet, such as storage class selection, backup retention and who receives alerts. Ask for a timeline that lists each phase, the dependencies on your storage and network teams, and the review points where your staff sign off. Any figure should come from the written scope, not from a general estimate.

What must our team provide before a database goes onto the cluster?

Most of the inputs sit inside your own infrastructure. You will typically need:

  • A Kubernetes cluster with nodes spread across the failure domains you intend to use, plus the CSI storage backend that backs the volumes
  • Storage capacity and performance that match the database's write and IOPS profile, and a StorageClass your team approves
  • A backup target, such as object storage or a backup repository, with credentials and retention rules agreed with the data owners
  • Named staff who will be on call, own alerts and approve changes after go-live
  • Identity, secrets and network access decisions, including who can reach the database and from which namespaces

Confirm each item with your platform and security teams before the build starts, since missing inputs are a common cause of delays.

Can our internal team run a database on Kubernetes without outside help?

Yes, many internal platform teams do, provided they have engineers who understand Kubernetes scheduling and storage, the database engine's replication and recovery model, and the backup tooling. The risk is usually not the first deployment but the first real incident, the first major version upgrade and the first restore under time pressure. Assess your team by asking whether it has practiced failover and restore, whether someone owns each runbook, and whether there is capacity for on-call rotation. A partner can cover part of the work, such as design review, the initial build, or restore testing, while your staff keep operational ownership.

How do I ask a partner for a fixed-scope quote for this work?

Send the partner a written description of the databases, environments, availability target, backup and recovery expectations, integrations and the systems you already run. Ask for a scope document that lists deliverables, what your staff must provide, assumptions about the storage and network, acceptance tests and exclusions. DeployOpen plans most engagements as fixed-scope, with scope, deliverables and timelines agreed in writing before work starts, and a quote follows from that written scope. Ask how restore testing, upgrades and ongoing support are priced separately, and whether any retainer is needed after handover.

What goes wrong most often when databases run on Kubernetes?

Common problems include pods of the same replica set landing on one node or one zone, so a single failure removes several members; storage classes that do not match the database's replication model; and scaling or rolling updates that restart the primary before replicas are healthy. Backups are often configured but never restored, so recovery steps are unknown until an incident. Check anti-affinity and zone spread, confirm update policies, and schedule restore tests with the people who will run them. Confirm the exact behavior of your chosen operator or StatefulSet settings in the vendor documentation for your versions.

Does running a database on Kubernetes change our security and compliance scope?

It can. Secrets used by the database are stored unencrypted in etcd by default, so encryption at rest for the API server, least-privilege RBAC and a decision about an external secrets store should be settled before go-live. Pod security settings, network policies and audit logging also affect how the database is reviewed. DeployOpen prepares systems, controls and evidence for compliance assessments, but independent auditors issue any audit report or certification. Ask your assessor early which controls they will test and which evidence they expect from the cluster.

How the parts of a database StatefulSet fit together

The diagram starts at the StatefulSet, which creates ordered pods with stable names such as db-0. Each pod is bound through a volumeClaimTemplate to its own PersistentVolumeClaim, provisioned by the StorageClass on the CSI driver. A headless Service gives each pod a stable DNS identity for peer discovery. Pods are spread across nodes and zones by anti-affinity, and a PodDisruptionBudget limits voluntary evictions. Backups leave the cluster for a target outside the database namespace. Check that the storage backend, zone labels and backup credentials match what your design assumes.

Pods, per-pod claims, shared services and the off-cluster backup target.

How DeployOpen scopes and delivers database StatefulSet work

DeployOpen plans and implements database StatefulSets inside your own infrastructure, whether that is your cloud accounts, data centers or air-gapped network. Before any build starts, scope, deliverables and timelines are agreed in writing. For a StatefulSet engagement, that agreement usually names the database engine and version, the StorageClass and CSI driver behind the volumes, the replica count and how replicas are spread across nodes and zones, the update policy, the backup target and the failover and restore tests that count as acceptance. Most engagements are fixed-scope, so the written scope is the basis for the quote. DeployOpen does not publish a price list. The quote follows from that scope, and the items most likely to move it are the number of database clusters, the number of zones, whether the engine needs an operator, and how much backup and restore testing is included.

Testing comes before handover. DeployOpen runs planned node drains, pod deletions and zone-level disruptions against the cluster to confirm that the database fails over as the design expects, and it performs a restore from the backup target into a separate namespace to confirm the data comes back intact. The results, along with the runbooks for failover, restore and scaling, are delivered with the cluster. Ongoing support, upgrades and continuous testing are available as a retainer, which covers database minor-version updates, Kubernetes upgrades that touch the StatefulSet, and periodic restore drills. Ask any partner, DeployOpen included, to show the written acceptance tests and to state which parts of operations remain with your team after handover.

Sources and further reading

Talk to our team.

Tell us what you're working on, whether it's a deployment, an audit, a security test or a cyber range. You'll speak with an engineer who can help you scope it.

  • 30-minute call: free, with no obligation.
  • NDA on request: we can sign before you share details.
  • Clear next steps: a scope and plan after the call.