tezvyn:

Kubernetes StatefulSet: Pods with Stable Identity

AI-drafted, machine-checkedSource: kubernetes.iointermediate
Kubernetes StatefulSet: Pods with Stable Identity

A StatefulSet gives Kubernetes pods a stable identity and dedicated storage, like assigning a permanent desk and locker to an employee. Use it for databases or clustered apps where nodes need to find each other and retain data across restarts.

WHY IT EXISTS By default, Kubernetes treats pods as ephemeral and interchangeable, like cattle. This is great for stateless web servers but fails for applications like databases, which need a stable identity and persistent data. StatefulSets were created to manage these applications, providing guarantees that a standard Deployment cannot.

THE MENTAL MODEL A StatefulSet is like a Deployment, but for applications that need to remember who they are. Imagine a team where each member has a specific name tag (network ID) and a personal locker (storage volume). If a member leaves and is replaced, the new person gets the exact same name tag and locker key, ensuring continuity. This is what a StatefulSet does for pods.

HOW IT WORKS A StatefulSet provides two main guarantees. First, stable, unique network identifiers. A pod in a StatefulSet named 'db' with 3 replicas will be named db-0, db-1, and db-2. If db-1 fails, its replacement will also be named db-1. Second, stable, persistent storage. Each pod gets its own PersistentVolume. When db-1 is replaced, the new pod re-attaches to the exact same storage volume, preserving its state. It also enforces ordered operations: scaling up creates pod 0, then 1, then 2. Scaling down removes pod 2, then 1, then 0.

WHEN TO USE IT Use StatefulSets for any application that requires stable identifiers or persistent state per replica. This is common for distributed databases like Cassandra or etcd, message queues like Kafka or RabbitMQ, and any clustered software where nodes need to discover and communicate with specific peers.

WHEN NOT TO USE IT Do not use a StatefulSet for stateless applications, such as web frontends, API gateways, or simple processing workers. A Deployment is the correct tool for these use cases. It is simpler, more flexible, and allows for faster, non-ordered scaling. Using a StatefulSet where it's not needed adds unnecessary complexity and slows down deployments.

ONE CANONICAL EXAMPLE Running a ZooKeeper ensemble. Each ZooKeeper node needs a unique, static ID (myid) and its own data directory. A StatefulSet can manage a 3-node cluster named 'zk'. It creates pods zk-0, zk-1, and zk-2. Each pod gets a stable hostname and its own PersistentVolume. If the pod running zk-1 crashes, Kubernetes will create a new pod, also named zk-1, and attach it to the same storage, allowing it to rejoin the cluster seamlessly.

Read the original → kubernetes.io

Get five bites like this every day.

Tezvyn delivers a daily feed of 60-second tech bites with quizzes to lock in what you learn.