The Analogy: The Front-Desk Extension and the Shift Supervisor
A large hotel publishes one front-desk extension: dial 0 from any room and you reach the desk. Behind that single number is a rotating cast of people. Clerks come on and off shift around the clock, take breaks, and go home sick, but the guest never dials a specific clerk. They dial the role, and whoever is staffing the desk right now, wearing the front-desk badge, answers. The extension is stable and public; the individuals behind it are constantly changing, and that separation is the entire point -- guests should never need to know who is on duty.
Two separate jobs keep this working, and they are genuinely separate. A shift supervisor owns staffing: the desk should always have, say, three clerks on it, and if one goes home the supervisor calls in a replacement so the count is restored to three. That is one responsibility, concerned only with how many warm bodies are present. A completely separate switchboard owns routing: when dial-0 rings, it rings every phone whose holder is currently badged for the front desk, and splits incoming calls among them. The supervisor manages the people; the switchboard manages the calls; the one and only thing linking the two is the badge.
Shift changes are done gradually, so the desk is never dark. The supervisor does not send all three clerks home at once and then bring in three strangers to an empty counter. They bring on one fresh clerk, let them settle in, send one tired clerk home, and repeat, so that through the entire handover the desk always has enough people to answer the phones. Bring up the new before retiring the old, one at a time, staying within a margin that never drops below a safe minimum staffing nor overshoots the physical space at the counter.
Here is the silent catastrophe. The switchboard routes purely on the badge, and nothing forces the incoming clerks to actually hold one. Suppose a batch of new hires is rostered onto the desk -- the supervisor's headcount reads a healthy three -- but through a clerical slip none of them were ever issued a front-desk badge. The switchboard, dutifully ringing every front-desk badge it can find, now finds none, and dial-0 rings out into dead air. Guests get silence, the supervisor's roster says fully staffed, and no alarm sounds anywhere, because each half is doing its own job correctly against its own records. That is exactly the failure in the tool at the end of this lesson, which reports a healthy count of running pods while the Service that routes traffic to them, matching on a label the new pods happen to lack, sends every request into a black hole.
Syntax or Core Structure
Two objects divide the work. A Deployment keeps a desired number of pods alive, replacing any that die. A Service gives those pods one stable address and load-balances across them -- but it does not know about the Deployment at all. It finds its targets by label selector: it routes to every pod whose labels match, and to nothing else. A Service manifest names only that selector and the ports:
apiVersion: v1
kind: Service
metadata:
name: web
spec:
selector:
app: web
ports:
- protocol: TCP
port: 80
targetPort: 8080
The set of pods this Service sends traffic to -- its endpoints -- is computed by matching that selector against every pod's labels. A pod carrying app: web is in; a pod without it is out, no matter who created it. Model the match:
def matches(labels, selector):
return all(labels.get(k) == v for k, v in selector.items())
SELECTOR = {'app': 'web'}
PODS = [
('web-1', {'app': 'web'}),
('web-2', {'app': 'web'}),
('api-1', {'app': 'api'}),
]
print('selector: app=web')
eps = []
for name, labels in PODS:
hit = matches(labels, SELECTOR)
if hit:
eps.append(name)
lab = ','.join('%s=%s' % (k, v) for k, v in sorted(labels.items()))
print('%-6s labels=%-8s -> %s' % (name, lab, 'endpoint' if hit else 'excluded'))
print('endpoints=%d: %s' % (len(eps), ', '.join(eps)))
Output:
selector: app=web
web-1 labels=app=web -> endpoint
web-2 labels=app=web -> endpoint
api-1 labels=app=api -> excluded
endpoints=2: web-1, web-2
The Service picks up the two web pods and ignores api-1, purely on the label. Nothing else is consulted -- not the pod's name, not which Deployment owns it. The switchboard rings the badges that match and no others, and the badge is the label.
Technical Depth: The Object Chain and the Rollout Envelope
Four objects, each owning the next
A Deployment does not manage pods directly. It owns a ReplicaSet, which owns the pods; a Service sits off to the side and finds pods by label. Knowing the chain tells you which object to inspect when something is wrong.
| Object | Owns / targets | Responsible for |
|---|---|---|
| Deployment | ReplicaSets | rollout strategy and version history |
| ReplicaSet | Pods | keeping a fixed replica count alive |
| Pod | containers | running one instance of the workload |
| Service | pods by label | one stable address, load-balancing endpoints |
The subtle point is that Deployment and Service are not connected to each other. The Deployment produces pods and stamps labels on them; the Service selects pods by label. They meet only at the pod's labels, which is powerful -- one Service can front pods from several Deployments, and you can swap the Deployment behind a stable Service -- but also means nothing enforces that they agree.
A rolling update stays inside a capacity envelope
When a Deployment changes, it creates a new ReplicaSet and shifts pods from old to new gradually. Two knobs bound the shift: maxSurge (how far above the desired count the total may go) and maxUnavailable (how far below it the present count may drop). Model the shift for four replicas with both set to one:
REPLICAS, SURGE, UNAVAIL = 4, 1, 1
def rollout():
old, new = REPLICAS, 0
rows = [('start', old, new)]
turn = 'surge'
while old > 0 or new < REPLICAS:
if turn == 'surge' and new < REPLICAS and old + new < REPLICAS + SURGE:
new += 1; rows.append(('surge', old, new)); turn = 'down'
elif old > 0 and (old + new - 1) >= REPLICAS - UNAVAIL:
old -= 1; rows.append(('scale-down', old, new)); turn = 'surge'
elif new < REPLICAS and old + new < REPLICAS + SURGE:
new += 1; rows.append(('surge', old, new)); turn = 'down'
else:
old -= 1; rows.append(('scale-down', old, new))
return rows
rows = rollout()
print('%-11s %-4s %-4s %s' % ('step', 'old', 'new', 'present'))
present = []
for step, old, new in rows:
p = old + new
present.append(p)
print('%-11s %-4d %-4d %d' % (step, old, new, p))
print('min-present=%d (floor %d) max-present=%d (ceil %d)' % (min(present), REPLICAS - UNAVAIL, max(present), REPLICAS + SURGE))
Output:
step old new present
start 4 0 4
surge 4 1 5
scale-down 3 1 4
surge 3 2 5
scale-down 2 2 4
surge 2 3 5
scale-down 1 3 4
surge 1 4 5
scale-down 0 4 4
min-present=4 (floor 3) max-present=5 (ceil 5)
The rollout always surges one new pod before retiring one old pod, so the count present never falls below four and never rises above five. The floor of three (REPLICAS - maxUnavailable) is never even approached because this ordering is conservative; the ceiling of five (REPLICAS + maxSurge) is touched on every surge. Set maxUnavailable to the full replica count and that floor drops to zero -- the Deployment would be free to kill every old pod before a single new one is ready, which is precisely how a "rolling" update becomes an outage. The knobs are the safe-staffing minimum and the counter's physical size, and honoring them is what keeps the desk answered through the handover.
Real World Example: The Healthy Deployment Serving Nothing
A capacity tool answers a simple question -- how many endpoints is this Service serving? -- by reading the Deployment's ready replica count, on the reasonable-sounding assumption that the Deployment's pods and the Service's endpoints are the same set. Then a rollout ships a new ReplicaSet whose pod template dropped the app: web label, a one-word slip in a YAML edit. The Deployment reports four of four pods healthy. The tool, and the on-call engineer reading it, conclude the Service is fine:
def matches(labels, selector):
return all(labels.get(k) == v for k, v in selector.items())
SEL = {'app': 'web'}
# rollout finished: all pods are from a new ReplicaSet whose template forgot app: web
NEWPODS = [
('web-v2-1', {'version': 'v2'}),
('web-v2-2', {'version': 'v2'}),
('web-v2-3', {'version': 'v2'}),
('web-v2-4', {'version': 'v2'}),
]
def naive_endpoints(pods):
return len(pods) # assumes every running pod serves
def real_endpoints(pods, selector):
return [n for n, l in pods if matches(l, selector)]
running = len(NEWPODS)
naive = naive_endpoints(NEWPODS)
real = real_endpoints(NEWPODS, SEL)
print('running pods=%d (Deployment reports healthy)' % running)
print('naive endpoint estimate=%d' % naive)
print('real endpoints=%d: %s' % (len(real), ', '.join(real) if real else '(none)'))
print('black-hole=%s miss=%d' % (len(real) == 0, naive - len(real)))
Output:
running pods=4 (Deployment reports healthy)
naive endpoint estimate=4
real endpoints=0: (none)
black-hole=True miss=4
Four pods are running and the Deployment is genuinely healthy, but the Service selects on app: web and every new pod carries only version: v2, so the endpoint set is empty. Every request to the Service returns a connection error while the dashboards stay green, because each object is correct about its own job: the Deployment kept four pods alive, and the Service routed to every pod matching its selector -- of which there are now none. The naive_endpoints function returns len(pods), the Deployment's count, and never consults the selector, so it confidently reports four endpoints for a Service serving zero. The gap of four is the whole outage.
The fix is real_endpoints, which filters by the selector and turns the reported four into the true zero, but it is worth being honest that even this is a partial model. It checks label match only, not readiness: real Kubernetes also requires a pod to pass its readiness probe before it becomes an endpoint, so a matching-but-not-ready pod is counted here and would not be by the cluster. It handles only equality selectors, not the set-based operators (In, NotIn, exists) that real selectors allow, so it silently mis-answers for those. And the deeper point is that the decoupling of Service from Deployment through labels is deliberate and useful -- it is what lets one Service front several Deployments, or a Deployment be swapped behind a stable address -- but the same decoupling means a label typo yields a silent black hole with both sides reporting healthy. The real safeguard is not a smarter estimator; it is readiness probes plus an alert that fires when a Service's endpoint count hits zero, because nothing in the platform will raise that alarm for you.
Common Mistakes
- Creating naked pods instead of a Deployment. A standalone pod that dies stays dead. Running workloads through a Deployment gives them a ReplicaSet that revives failed pods, which is the whole reason self-healing works.
- A Service selector that matches no pod labels. The Service then routes to zero endpoints and every request fails, with no error raised anywhere -- running pods, dead-air traffic, green dashboards.
- Assuming the Deployment and Service are wired together. Their only link is the pod label. A label change on either side breaks routing while both objects continue to report healthy.
- Setting
maxUnavailabletoo high. At 100% the rollout may terminate every old pod before a new one is ready, turning a "rolling" update into a full outage during the deploy.
- Shipping without a readiness probe. The rollout then treats a pod as available the moment it starts, shifting traffic to pods that are up but not yet serving, and users see errors mid-deploy.
- Editing a pod directly instead of the Deployment. The owning ReplicaSet reverts your change on the next reconcile. Durable changes go in the Deployment's pod template, which rolls out a new ReplicaSet.
- Changing a Deployment's selector. The selector is effectively immutable and is what distinguishes old from new ReplicaSets. Changing it orphans existing pods and confuses ownership.
- Confusing
portwithtargetPort. The Service listens onportand forwards to the container'stargetPort; if the container listens elsewhere thantargetPortnames, connections are refused despite a correct selector.
- Using the wrong Service type for the audience. A
ClusterIPis internal only. Expecting outside traffic to reach it without aNodePort,LoadBalancer, or Ingress leaves the workload unreachable from beyond the cluster.
Best Practices
- Run every workload through a Deployment rather than as a naked pod, so a failed pod is replaced automatically by its ReplicaSet.
- Keep the Service selector and the Deployment's pod-template labels in exact agreement, and treat that label as a contract between two objects that are otherwise independent.
- Give pods readiness probes so a rolling update shifts traffic only to pods that can actually serve and the endpoint set reflects true readiness.
- Set
maxSurgeandmaxUnavailableto preserve a safe minimum during rollouts -- surge one, unavailable zero for a strict zero-downtime deploy.
- Alert when a Service's endpoint count falls to zero, because a selector black hole leaves every other signal green and the platform raises no alarm of its own.
- Change workloads by editing the Deployment, which rolls out a new ReplicaSet, rather than patching live pods that the controller will revert.
- Treat the Deployment selector as immutable; when labels genuinely must change, create a new Deployment instead of mutating the selector.
- Pick the Service type for the actual audience --
ClusterIPfor internal callers, an Ingress orLoadBalancerfor external traffic -- instead of exposing pods ad hoc.
Practice Exercises
- Extend the endpoint matcher with a pod carrying extra labels (
app: web,tier: frontend) and confirm it still matches theapp: webselector, then a pod missingappentirely and confirm it is excluded.
- Re-run the rollout model with
maxUnavailableof two andmaxSurgeof zero. Show that the present count now dips to two and explain the user-facing consequence of the lower floor.
- Fix
real_endpointsto also require a pod be ready, then construct a case with a label-matching but not-ready pod and show the label-only version over-counts it.
- Model two Deployments,
v1andv2, both labeledapp: webbehind one Service. Compute the combined endpoint set and explain how this arrangement enables a blue-green or canary traffic split.