TExcelTAD
Home › Kubernetes › ReplicaSets

ReplicaSets

A ReplicaSet keeps a fixed number of identical Pods running. You give it three things:

  1. replicas: how many Pods you want,
  2. a selector: which Pods count as "mine",
  3. a Pod template: what to create when there are too few.
yaml
apiVersion: apps/v1
kind: ReplicaSet
metadata:
  name: web
spec:
  replicas: 3
  selector:
    matchLabels:
      app: web
  template:                # a Pod manifest without apiVersion/kind
    metadata:
      labels:
        app: web           # must satisfy the selector
    spec:
      containers:
        - name: nginx
          image: nginx:1.27

In practice you almost never create ReplicaSets yourself: a Deployment creates and manages them for you (next lesson). Understanding them explains everything a Deployment does.

The reconcile loop

The ReplicaSet controller repeats one simple calculation:

text
diff = len(matching, non-terminating Pods) - spec.replicas
diff < 0  -> create |diff| Pods from the template
diff > 0  -> delete diff Pods (preferring the "least valuable" ones)
diff == 0 -> nothing to do

Here is that loop as a runnable model. We start empty, survive a deleted Pod, then scale up and down:

python · try it yourself
import itertools

counter = itertools.count(1)
pods = []

def reconcile(rs):
    mine = [p for p in pods if p["labels"].get("app") == rs["selector"]["app"]]
    diff = len(mine) - rs["replicas"]
    if diff < 0:
        for _ in range(-diff):
            pod = {"name": f"{rs['name']}-{next(counter):03d}", "labels": dict(rs["template_labels"])}
            pods.append(pod)
            print("  create", pod["name"])
    elif diff > 0:
        for pod in mine[-diff:]:          # newest first, for simplicity
            pods.remove(pod)
            print("  delete", pod["name"])
    names = [p["name"] for p in pods if p["labels"].get("app") == rs["selector"]["app"]]
    print(f"  -> {len(names)}/{rs['replicas']}: {names}")

rs = {"name": "web", "replicas": 3, "selector": {"app": "web"}, "template_labels": {"app": "web"}}
print("initial:"); reconcile(rs)
pods.pop(1)
print("a Pod was deleted:"); reconcile(rs)
rs["replicas"] = 5
print("scaled to 5:"); reconcile(rs)
rs["replicas"] = 2
print("scaled to 2:"); reconcile(rs)
initial:
  create web-001
  create web-002
  create web-003
  -> 3/3: ['web-001', 'web-002', 'web-003']
a Pod was deleted:
  create web-004
  -> 3/3: ['web-001', 'web-003', 'web-004']
scaled to 5:
  create web-005
  create web-006
  -> 5/5: ['web-001', 'web-003', 'web-004', 'web-005', 'web-006']
scaled to 2:
  delete web-004
  delete web-005
  delete web-006
  -> 2/2: ['web-001', 'web-003']

Which Pods are deleted when scaling down?

The real controller doesn't pick randomly. It ranks candidates and deletes from the top of this list:

  1. Pods not yet scheduled to a node,
  2. Pods that are Pending before Running,
  3. Pods that aren't Ready before Ready ones,
  4. Pods on nodes with more replicas of this ReplicaSet (spreading the survivors),
  5. more recently created (younger) Pods before older ones.

(You can also influence it with the controller.kubernetes.io/pod-deletion-cost annotation.)

python · try it yourself
pods = [
    {"name": "web-a", "node": "n1", "phase": "Running", "ready": True,  "age": 300},
    {"name": "web-b", "node": "n1", "phase": "Running", "ready": True,  "age": 120},
    {"name": "web-c", "node": "n2", "phase": "Running", "ready": True,  "age": 500},
    {"name": "web-d", "node": "n1", "phase": "Running", "ready": False, "age": 60},
    {"name": "web-e", "node": None, "phase": "Pending", "ready": False, "age": 5},
]
per_node = {}
for p in pods:
    per_node[p["node"]] = per_node.get(p["node"], 0) + 1

def deletion_rank(p):
    return (
        p["node"] is not None,          # unscheduled first
        p["phase"] == "Running",        # pending before running
        p["ready"],                     # not-ready before ready
        -per_node[p["node"]],           # crowded nodes first
        p["age"],                       # younger first
    )

order = sorted(pods, key=deletion_rank)
print("deletion order:", [p["name"] for p in order])
print("scale 5 -> 2 deletes:", [p["name"] for p in order[:3]])
deletion order: ['web-e', 'web-d', 'web-b', 'web-a', 'web-c']
scale 5 -> 2 deletes: ['web-e', 'web-d', 'web-b']

Ownership and orphans

When a ReplicaSet creates a Pod, it sets metadata.ownerReferences on it. That link powers garbage collection: delete the ReplicaSet and its Pods are deleted too.

bash
kubectl get pod web-001 -o jsonpath='{.metadata.ownerReferences[0].kind}/{.metadata.ownerReferences[0].name}'
kubectl delete rs web                       # Pods are garbage-collected
kubectl delete rs web --cascade=orphan      # keep the Pods running, unowned

Warning: A ReplicaSet adopts any Pod whose labels match its selector, even one you created by hand. If you start a bare Pod with app: web next to a ReplicaSet wanting 3, the controller sees 4 and deletes one.

ReplicaSet vs ReplicationController

The older ReplicationController does the same job with equality-only selectors. It is legacy: use Deployments (which use ReplicaSets).

Test yourself

A ReplicaSet wants 3 Pods and sees 5 matching Pods. What does it do?

  1. Creates 3 more
  2. Deletes 2
  3. Does nothing
  4. Deletes all and recreates 3

When scaling down, which Pod does the controller prefer to delete first?

  1. The oldest Ready Pod
  2. An unscheduled, Pending Pod
  3. The Pod with the most restarts
  4. A random Pod

Which field links a Pod to the ReplicaSet that created it?

  1. metadata.labels
  2. metadata.ownerReferences
  3. spec.nodeName
  4. status.phase