I am trying to deploy a MongoDB database on my Kubernetes cluster. I used a standard Deployment, but every time a pod restarts, it gets a new hostname and loses its connection to the persistent volume. I keep seeing people mention StatefulSets. What is the fundamental difference, and why is it necessary for databases or message brokers like Kafka?
3 answers
The key difference is "Identity." In a Deployment, pods are interchangeable and have random names like web-7fh2l. When one dies, it's replaced by a completely new one with no memory of the old one. StatefulSets provide a stable network ID (like mongo-0, mongo-1) and a stable storage link. When mongo-0 restarts, it will always be named mongo-0 and it will automatically re-attach to the exact same Persistent Volume it had before. This is vital for databases because they need to know exactly which data shard they are responsible for to maintain cluster consensus.
Does using StatefulSets make the scaling process slower since it has to create pods one by one in order?
Managing databases on K8s is hard. If you can, use a Managed Service (like RDS) and keep your Kubernetes cluster strictly for stateless apps.
I second that, Sandra! Unless you have a dedicated DBA team, the overhead of managing stateful K8s nodes is often not worth the cost savings.
Yes, Kenneth, that is by design. By default, StatefulSets use an "OrderedReady" strategy. It waits for pod 0 to be completely healthy before starting pod 1. This prevents "Split-Brain" scenarios in databases where multiple nodes might try to claim leadership at the same time. If your specific application doesn't care about the order, you can set the podManagementPolicy to "Parallel" to speed things up, but for most databases, the slow, ordered approach is exactly what keeps your data safe from corruption during scaling.