StatefulSets
StatefulSets are a stable resource in the apps/v1
API group. Their use cases include stateful components for your application, such as Pods that are not intended to be ephemeral and need more order than is provided by something like a Deployment.
Stateful components of a microservices application are usually the hardest to implement, and platforms like Kubernetes have been somewhat slow to implement features to handle them. StatefulSets are a step towards improving this.
In many ways, StatefulSets are like Deployments. For example, we define them in a YAML file that we POST
to the API server as the desired state. A controller implements the work on the cluster, and a background watch loop makes sure the current state matches the desired state. However, there are several significant differences. These include:
- StatefulSets give Pods deterministic meaningful names. Deployments do not.
- StatefulSets always start and delete Pods in a specific order. Deployments do not.
- Pods deployed via StatefulSet are not interchangeable. Pods deployed by Deployments are interchangeable.
Let’s quickly look at each point a bit closer.
When a Pod is created by a Deployment, its name is a combination of the name of the Deployment plus a hash. When a Pod is created by a StatefulSet, its name is a combination of the name of the StatefulSet plus an integer. The first Pod deployed by a StatefulSet gets integer 1, the second gets integer 2, and so on. This effectively names Pods according to the order they were created. Scaling up a StatefulSet will cause the new Pod to get the next integer in the list, and scaling down a StatefulSet will start by deleting the highest-numbered Pod. Finally, when a Pod managed by a StatefulSet fails, it is replaced by another Pod with the same name, ID, and IP address.
Potential use cases for StatefulSets are any services in your application that maintain state. These can include:
- Pods that require access to specific named volumes.
- Pods that require a persistent network identity.
- Pods that must come online in a particular order.
A StatefulSet guarantees all of these will be maintained across Pod failures and subsequent rescheduling operations.
Due to the more complex nature of stateful applications, StatefulSets can be complex to configure.
In summary, StatefulSets ensure a deterministic order for Pod creation and deletion based on the meaningful name of each managed Pod.
Get hands-on with 1200+ tech skills courses.