Kubernetes Scheduling: nodeSelector, Affinity and Anti-Affinity
Kubernetes scheduling decides which node runs each Pod. This lesson explains nodeSelector, node affinity, and Pod affinity and anti-affinity through the kube-scheduler filter and score model, then shows required and preferred rules, topologyKey choices, production patterns, and the first checks when placement rules leave a Pod Pending.
Introduction: Kubernetes scheduling in one decision
Kubernetes scheduling is the control plane decision that assigns each unscheduled Pod to one node. nodeSelector and required affinity act as hard filters, preferred affinity changes node scores, and Pod anti-affinity keeps replicas apart. When no node passes every filter, the Pod stays Pending and the scheduler reports why.
Consider an illustrative composite, not a named outage. A checkout service runs three replicas and passes every health check, so the team calls it highly available. During a node drain, all three replicas turn out to sit on the same node, because nothing in the Deployment ever asked for separation. The drain evicts the first replica, the replacement schedules back onto the same busy node, and a routine maintenance window becomes a latency incident. The replicas were real. The placement was an accident.
The mirror-image failure is just as common. An engineer adds a required anti-affinity rule so no two replicas share a node, then scales the service from three replicas to five on a four-node cluster. Two Pods sit Pending for an hour while the team checks images, quotas, and network policy. The scheduler event said the answer from the first minute: no node could satisfy the rule. Both failures come from treating placement as a default instead of a decision with failure modes.
This is lesson 14 of the Kubernetes roadmap, in Module 7 on scheduling. The previous lesson, Kubernetes QoS classes and eviction order, covered what happens when a node runs short of memory after Pods start. This lesson covers the earlier decision: which node a Pod is allowed to start on at all. Taints and tolerations come next in the module, and they work from the node side. Here the rules sit on the Pod side and match labels.
The 5-minute takeaway
Kubernetes scheduling runs in two phases: filter, then score. Required rules remove nodes from consideration, preferred rules only change scores, and anti-affinity spreads replicas across a domain named by topologyKey. Use the softest rule that protects the workload, because every hard rule is a new way for a Pod to stay Pending during a scale-up, a drain, or a zone failure.
1. Kubernetes scheduling: kube-scheduler filters, then scores
Kubernetes scheduling starts when a Pod has no node assigned. The kube-scheduler takes the Pod from its queue, removes every node that cannot run it, scores the survivors, and binds the Pod to the highest-scoring node. Filters are pass or fail, scores are a ranking, and that split explains every affinity rule.
Filtering asks one binary question per node: could this Pod run here? A node fails if its allocatable CPU or memory cannot cover the Pod requests, if a volume cannot attach there, if the node is cordoned or not Ready, or if a required placement rule does not match. One failed check removes the node. There is no partial credit and no appeal inside the same scheduling attempt, which is why a single wrong label can empty the candidate list.
Scoring asks a different question about the nodes that survived: which one fits best? Score plugins rate each feasible node, the ratings are weighted and combined, and the scheduler binds the Pod to the winner. Default scoring favours nodes with more free capacity, nodes that already hold the container image, and nodes that keep replicas spread. Preferred affinity rules feed this phase, so they bend the ranking without ever blocking placement.
Two limits of the model matter in production. First, the scheduler reasons over requests and allocatable capacity, not live usage. A Pod that requests two CPUs and uses a tenth of one still looks like a two-CPU Pod to every filter and score. Second, the decision happens once, at scheduling time. If node labels change later, running Pods stay where they are, because the affinity fields are ignored during execution. Placement is a snapshot decision, not a continuous rebalance. The control plane components behind this loop are mapped in Kubernetes architecture and workload orchestration.
2. Kubernetes scheduling with nodeSelector: exact label matches
Kubernetes scheduling with nodeSelector is the simplest placement rule: name node labels, and the Pod can only land on nodes carrying every one of them. It is an exact-match filter with no operators and no soft form, so use it for plain hardware or pool selection and nothing subtler.
Nodes carry labels just like Pods. Some arrive with the node, such as kubernetes.io/hostname, kubernetes.io/arch, and in cloud clusters topology.kubernetes.io/zone and topology.kubernetes.io/region. Others are yours to apply, such as a disk type, a GPU model, or a node pool name. The nodeSelector field in the Pod spec is a map of label keys to values, and every pair must match. Extra labels on the node are fine.
This Deployment only schedules onto nodes labelled disktype=ssd. If no node carries that label, both replicas stay Pending and the scheduler event reports that nodes did not match the Pod node affinity or selector. That bluntness is the trade: nodeSelector is easy to read in review and easy to audit with one kubectl command, but it cannot express "ssd if available, anything otherwise" or "zone a or zone b but not arm64". Those sentences need node affinity.
One operational habit prevents most nodeSelector incidents. Treat node labels as an API between the platform team and workload teams. Apply pool labels through node provisioning, not by hand on individual nodes, so a replacement node joins with the same labels the old one had. A hand-labelled node that gets replaced by an unlabelled one silently shrinks the eligible pool, and the next scale-up discovers the gap at the worst time.
3. Kubernetes scheduling with required node affinity
Kubernetes scheduling with required node affinity is nodeSelector with operators and alternatives. The rule must match or the Pod does not schedule, which makes it right for hard limits such as CPU architecture, licensed hardware, or a data-residency zone, and wrong for mere preferences.
The field name carries the contract: requiredDuringSchedulingIgnoredDuringExecution. Required during scheduling means the filter phase enforces it. Ignored during execution means a later label change never evicts a running Pod. Inside the rule, nodeSelectorTerms is a list of alternatives. Terms are combined with OR, so matching any one term passes. Expressions inside a term are combined with AND, so every expression in that term must hold.
Operators widen what a term can say. In and NotIn test membership in a value list. Exists and DoesNotExist test whether a key is present at all. Gt and Lt compare integer label values, which suits labels such as a hardware generation number. There is no separate node anti-affinity field; NotIn and DoesNotExist express the same idea from the Pod side.
Read the example as two sentences. The Pod must land in zone-a or zone-b on a node that is not arm64. Among nodes that pass, ssd nodes score higher. If you set both nodeSelector and node affinity on the same Pod, both must be satisfied, because each one filters independently. Teams often add a nodeSelector during a migration and forget it is still narrowing the pool after affinity takes over.
Required rules deserve the same review standard as resource requests, because they define the smallest pool the workload can ever use. Before shipping one, count the nodes that match today, then ask what happens when one of those nodes is drained, replaced, or lost with its zone. If the honest answer is "the service cannot scale", the rule is either a deliberate capacity contract with the platform team or a preference wearing a hard rule costume.
4. Kubernetes scheduling with preferred node affinity and weights
Kubernetes scheduling with preferred node affinity never blocks a Pod. Each preference carries a weight from 1 to 100, matching nodes gain score, and the Pod still schedules elsewhere when no preferred node is free. Use preferred rules for cost, locality, and hardware wishes that should bend under pressure.
The field is preferredDuringSchedulingIgnoredDuringExecution, and it holds a list of weighted preferences. A node that matches a preference gains points in proportion to the weight, and several preferences can stack on the same node. The final ranking still mixes in every other score plugin, such as free capacity and image locality, so a weight of 100 is a strong vote, not a guarantee. That is the correct behaviour for a preference: it should win ties and close calls, then step aside when capacity is tight.
Preferred rules fit three recurring production wishes. Cost: prefer spot or lower-cost node pools for batch work that can restart. Locality: prefer nodes in the zone closest to a data store when cross-zone traffic is priced or slow. Hardware: prefer SSD or a newer CPU generation for a service that runs acceptably, if slower, on older nodes. In each case the workload keeps running during a pool shortage, which is exactly when hard rules turn a capacity dip into an outage.
The failure mode of preferred rules is silence. A Pod that lands on a non-preferred node looks identical in kubectl get pods to one that landed correctly, so a team can believe its cost or locality policy holds while the scheduler quietly places Pods elsewhere. If the preference matters, measure it: list Pods with their nodes, join against node labels, and alert when the share on preferred nodes drops. A preference you never verify is a comment, not a policy.
Weights also need restraint. Stacking five preferences at weight 100 each produces a ranking nobody can explain during an incident. Keep one or two preferences per workload, state the reason in a manifest comment or design note, and let the default scoring handle the rest. When a placement outcome surprises you, fewer moving parts make the scheduler event and the node list readable.
5. Kubernetes scheduling with Pod affinity: co-locate on purpose
Kubernetes scheduling with Pod affinity places a Pod near other Pods that carry chosen labels, inside a domain named by topologyKey. Use it when two workloads talk constantly and distance costs latency or money, and prefer the soft form so a missing partner never blocks startup.
Node affinity reads node labels. Pod affinity reads Pod labels: the rule names a label selector and a topologyKey, and the scheduler looks for domains where matching Pods already run. With topologyKey set to kubernetes.io/hostname, the domain is one node, so the Pod tries to share a node with the matching Pod. With topologyKey set to topology.kubernetes.io/zone, the domain is a zone, so the Pod tries to share a zone. Same rule shape, different blast radius.
The classic case is a service beside its cache. Co-locating on one node removes a network hop, but it also couples failures: one node loss takes both. Co-locating in one zone keeps most of the latency win while surviving a single node failure, which is why zone-level affinity is usually the better production default. Required Pod affinity is sharper still. If no matching Pod exists yet, the new Pod waits, which can deadlock a cold start where each side waits for the other.
Two details decide whether the rule works at all. First, the selector must match the partner Pod labels exactly, including the labels the partner Deployment template actually sets. A selector written against a service name or a namespace label matches nothing and the preference silently does nothing. Second, by default the selector only considers Pods in the same namespace as the new Pod. Cross-namespace co-location needs the namespaces field on the term, and it deserves a deliberate decision, because it couples two teams release schedules.
Ask whether co-location earns its coupling before adding the rule. Measure the traffic between the pair, check whether the hop is node-local, zone-local, or cross-zone today, and price the difference. Many pairs that feel chatty move little data, and a zone-level preference captures most of the gain with none of the shared-node risk. Pod affinity is a latency tool. When the real goal is balanced spread, anti-affinity and the later topology lesson are the right tools.
6. Kubernetes scheduling with Pod anti-affinity: spread replicas
Kubernetes scheduling with Pod anti-affinity keeps a Pod out of domains that already hold matching Pods. It is the standard way to stop replicas sharing one node or one zone, and its required form caps the replica count at the number of domains, which is the trap to plan around.
The rule mirrors Pod affinity with the sign flipped. A label selector names the Pods to avoid, topologyKey names the domain, and the scheduler refuses or discourages domains that already contain a match. Point the selector at the workload own labels and the rule spreads its replicas: hostname as the key gives one replica per node, zone as the key gives one replica per zone. The selector must match the Pod own template labels, or every replica looks like the first one and nothing spreads.
Required anti-affinity is a hard filter with arithmetic consequences. One replica per node means a five-replica Deployment on four eligible nodes leaves one Pod Pending until a fifth node appears. One replica per zone means a fourth replica in a three-zone cluster can never schedule. Rollouts feel this too: a rolling update that wants a new Pod before removing an old one needs a free domain, so tight required rules can stall deploys exactly when a fix is urgent.
Preferred anti-affinity trades the guarantee for availability. Replicas spread when domains are free and pack when they are not, so scale-ups and rollouts proceed under pressure. For stateless services behind a load balancer, that trade is usually correct: a temporarily packed replica still serves traffic, while a Pending replica serves nothing. Reserve required anti-affinity for workloads where co-location is worse than not running, such as quorum members that must not share a failure domain, and size the node pool for the replica ceiling the rule creates. The autoscaling side of that sizing decision is compared in Karpenter vs Cluster Autoscaler.
7. Kubernetes scheduling topologyKey choices and failure domains
Kubernetes scheduling topologyKey choices decide what "together" and "apart" mean. The key names a node label, nodes sharing one value form a domain, and the two keys that matter most are kubernetes.io/hostname for node-level domains and topology.kubernetes.io/zone for zone-level domains.
Pick the key from the failure you are buying protection against. Hostname domains protect against one node dying, being drained, or being replaced. Zone domains protect against a zone outage, at the price of coarser placement: a zone rule cannot distinguish two nodes inside the same zone. A service that needs both protections needs both rules, typically a zone-level rule for the outage case and a hostname-level rule for the node case, with strengths chosen so the pair stays satisfiable at peak replicas.
The label behind the key must exist on the nodes. Nodes that lack the topology key label are skipped for that rule: Pods with the rule are not placed there, and Pods already there are not counted. Cloud node pools normally carry zone labels, but self-managed pools and local test clusters often do not, which is why a rule that works in production can behave oddly in a lab. Check the labels before blaming the rule.
Anti-affinity answers a yes-or-no question per domain: is a matching Pod already here? It cannot express "keep the counts within one of each other", which is the job of topology spread constraints with maxSkew. That mechanism, plus Pod priority and preemption, is the third lesson of this module, and it builds on the domain idea defined here. Use anti-affinity when separation itself is the requirement, and reach for spread constraints when balanced counts across domains are the requirement. Placement vocabulary beyond this lesson is summarised in Kubernetes concepts explained.
8. Kubernetes scheduling placement decision table
Kubernetes scheduling placement choices reduce to four questions: must the Pod run on specific nodes, should it prefer some nodes, must it sit near other Pods, or must it stay away from them? The table maps each answer to a mechanism, a strength, and the failure you accept.
| Placement need | Mechanism | Strength | Failure you accept |
|---|---|---|---|
| Only SSD or GPU nodes can run it | nodeSelector or required node affinity | Hard filter | Pod stays Pending when the pool is empty |
| SSD nodes are better, others still work | Preferred node affinity | Score only | Pod may land on slower nodes silently |
| Stay in two named zones for data rules | Required node affinity on zone label | Hard filter | Zone loss shrinks the pool to one zone |
| Sit near a cache in the same zone | Preferred Pod affinity, zone key | Score only | Extra hop when the cache zone is full |
| Never share a node with a replica | Required Pod anti-affinity, hostname key | Hard filter | Replicas capped at eligible node count |
| Spread replicas when capacity allows | Preferred Pod anti-affinity, hostname key | Score only | Replicas may pack during shortages |
| Keep zone counts balanced within one | Topology spread constraints, later lesson | Configurable | Needs the spread mechanism, not anti-affinity |
Read the last column before the first. Every hard rule converts a capacity shortage into Pending Pods, and every soft rule converts it into a quiet quality drop. Neither is free, so the decision is which failure the service tolerates better at 3 a.m. A payment API usually tolerates a packed replica better than a missing one. A quorum member usually tolerates waiting better than sharing a node with its peer.
The table also shows why stacking rules needs care. A required zone rule plus required hostname anti-affinity multiplies constraints: the eligible pool becomes matching nodes inside allowed zones, minus nodes already holding a replica. Each rule looks reasonable alone, and together they can leave zero candidates during a drain. Test the combination against the real node list, with one node removed, before the rule reaches production. That habit is part of the placement discipline in Kubernetes best practices.
9. Kubernetes scheduling patterns for production services
Kubernetes scheduling patterns that survive production share one trait: the hard rules protect correctness, and everything else is a preference. Pin what must be pinned, spread what must survive a failure, and let the scheduler absorb shortages by bending preferences instead of dropping Pods.
Pattern one is the hardware pool. A workload that needs a GPU, a fast disk, or a specific CPU generation gets a required node affinity rule against a pool label the platform team owns. The contract runs both ways: the workload team states the minimum pool size it needs, and the platform team keeps that many labelled nodes available through drains and replacements. Without the pool-size half of the contract, the rule is a Pending generator waiting for its first node loss.
Pattern two is the stateless service spread. Replicas get preferred anti-affinity on hostname at a high weight, plus a preferred zone-level rule when the cluster spans zones. During normal operation replicas land apart. During a node shortage they pack and keep serving, and the packing is visible in one kubectl get pods -o wide call, so the team can watch it heal as capacity returns. Add a required rule only when sharing a node breaks correctness, not merely when it feels untidy.
Pattern three is the latency pair. A service and its cache get preferred Pod affinity on the zone key, so traffic stays zone-local without chaining both to one node. Keep the weight moderate, because a cache that itself is spread across zones makes a strong affinity rule chase a moving target. Pattern four is the batch pool: preferred affinity toward spot or low-cost nodes, honest resource requests, and no hard rules, so batch work soaks up cheap capacity and yields gracefully when the pool shrinks.
Notice what none of these patterns do. None of them repel Pods from a node, because that direction belongs to taints, the next lesson in this module: a taint marks a node as refusing Pods that lack a matching toleration. Affinity rules attract or separate from the Pod side. Keeping the two directions separate in your head prevents the common design error of stacking affinity rules to imitate a dedicated node pool, which taints express directly.
10. Kubernetes scheduling profiles and schedulerName
Kubernetes scheduling profiles let one kube-scheduler run several plugin configurations, and a Pod picks one through spec.schedulerName. Most clusters should stay on the default profile, because a custom profile is control plane surface area that must be tested, upgraded, and debugged like any other component.
The scheduler is a plugin framework. Each stage of the pipeline, from queue ordering through filter and score to bind, is an extension point, and plugins implement the behaviour at each point. A scheduling profile, declared in a KubeSchedulerConfiguration file, selects which plugins run and with what weights. One scheduler process can run several profiles side by side, each with its own schedulerName, and a Pod that names no scheduler uses default-scheduler.
A second profile earns its place when a workload class needs genuinely different placement physics. Batch systems sometimes disable spread scoring to pack nodes tightly. Specialised hardware fleets sometimes add a scoring plugin for device locality. In each case the profile exists because the default ranking is wrong for that class in a measurable way, not because a team wants its own scheduler as a badge.
The risks are concrete. A Pod whose schedulerName matches no running profile waits forever with no FailedScheduling event to read, because no scheduler ever picks it up. A profile that disables a filter plugin can place Pods onto nodes that cannot actually run them, moving the failure from Pending to a kubelet error. And every profile multiplies the upgrade test matrix. Managed Kubernetes services usually fix the scheduler configuration for you, which settles the question: express placement through Pod rules, and treat profiles as platform-team territory on clusters you operate yourself.
11. Kubernetes scheduling Pending diagnosis: read the event first
Kubernetes scheduling Pending diagnosis starts with the FailedScheduling event, because the scheduler already counted every node and grouped the reasons. Read that count before changing anything, match each reason to a rule or a capacity fact, and fix the smallest thing the evidence names.
The event reads like an audit: zero of six nodes are available, two had insufficient CPU, two did not match the Pod node affinity or selector, two did not match Pod anti-affinity rules. Each clause maps to a check. Selector and node affinity clauses send you to the node label list. Anti-affinity clauses send you to the replica placement list and the domain count. Insufficient resource clauses send you to requests and allocatable capacity, which is a different problem from placement rules and should not be fixed by editing them. The command patterns behind these checks are covered in the kubectl master guide.
| Event clause | Likely cause | First check | Fix direction |
|---|---|---|---|
| Did not match Pod node affinity or selector | Label missing, renamed, or pool empty | Node labels against the rule | Relabel the pool or correct the rule |
| Did not match Pod anti-affinity rules | Replicas outnumber free domains | Replica count against node or zone count | Add capacity, cut replicas, or soften the rule |
| Did not match Pod affinity rules | Partner Pod absent or selector wrong | Partner Pods and their labels | Fix the selector or soften to preferred |
| Insufficient cpu or memory | Requests exceed free allocatable capacity | Requests against node allocatable | Resize requests or add nodes |
| No event at all | schedulerName matches no profile | Pod schedulerName value | Correct the name or remove it |
Work the matrix top to bottom and change one thing at a time. The two fixes that resolve most affinity Pending cases are softening a required rule to preferred, and repairing a label or selector that drifted from reality. Resist the urge to delete rules wholesale during an incident: a rule that blocks scheduling today may be the only thing keeping replicas apart tomorrow, so soften it, record why, and revisit after capacity returns.
This section covers only the affinity slice of Pending diagnosis. Pods also wait on volumes, quotas, image pulls, and node faults, and the full triage order across all of those causes is the subject of a later runbook lesson in Module 13 of this roadmap. The habit transfers directly: the scheduler event and the Pod spec, read together, name the blocker before any fix is attempted.
12. Kubernetes scheduling checklist before you ship placement rules
Kubernetes scheduling rules ship safely when the pool math, the failure trade, and the verification step are written down before the manifest merges. This checklist turns the lesson into a review gate for any Deployment that gains a selector, an affinity rule, or an anti-affinity rule.
| Check | Done when |
|---|---|
| Rule strength chosen | Each rule is required for correctness or preferred for quality, with the reason stated |
| Pool counted | Nodes matching the rule are counted today, and again with one node removed |
| Replica ceiling known | Required anti-affinity ceiling is compared with peak replicas and rollout surge |
| Labels owned | Pool labels come from provisioning, not hand edits on single nodes |
| Selectors verified | Pod affinity selectors match the partner template labels and namespace scope |
| Topology key checked | Every node carries the label behind each topologyKey in use |
| Pending path rehearsed | The team can read a FailedScheduling event and name the fix for each clause |
| Preference measured | Soft rules have a placement check that shows whether they hold in practice |
Before merging, work through the list:
- State why each rule is required for correctness or preferred for quality.
- Count the nodes matching each rule today, then recount with one node removed.
- Compare any required anti-affinity ceiling with peak replicas plus rollout surge.
- Confirm pool labels come from provisioning, not hand edits on single nodes.
- Verify Pod affinity selectors against the partner template labels and namespace scope.
- Check that every node carries the label behind each topologyKey in use.
- Rehearse reading a FailedScheduling event and naming the fix for each clause.
- Add a placement check that shows whether each preferred rule holds in practice.
Run the checklist against the real cluster, not against the manifest alone. Count matching nodes with kubectl, list current replica placement, and simulate the drain case by asking where each replica would go if its node vanished. Rules that only work when every node is healthy are rules that fail during the exact events they were written for.
Placement is one decision in a longer module. The next lesson covers taints and tolerations, where nodes repel Pods that lack a toleration, which is the direct way to build dedicated pools. Continue through Module 7 of the Kubernetes roadmap, and keep this lesson rule in view: hard rules for correctness, soft rules for quality, and evidence before edits.
Frequently Asked Questions
What is Kubernetes scheduling in plain terms?
Kubernetes scheduling is the decision that assigns each unscheduled Pod to one node. The kube-scheduler filters out nodes that cannot run the Pod, scores the nodes that remain, and binds the Pod to the best-scoring node. Placement rules you write feed the filter phase, the score phase, or both.
How does Kubernetes scheduling differ between nodeSelector and node affinity?
Kubernetes scheduling treats nodeSelector as an exact label match with no operators and no soft form. Node affinity adds operators such as In, NotIn, and Exists, alternatives through nodeSelectorTerms, and a preferred form that only changes scores. Both are hard filters in their required forms, and both must pass when a Pod sets both.
Can Kubernetes scheduling leave a Pod Pending because of a preferred rule?
Kubernetes scheduling never leaves a Pod Pending because of a preferred rule alone. Preferred rules only add score to matching nodes, so the Pod still schedules on a non-matching node when no preferred node is available. A Pending Pod points at a required rule, a resource shortage, or another filter, and the FailedScheduling event names which.
Why does Kubernetes scheduling ignore affinity after a Pod starts?
Kubernetes scheduling evaluates affinity at placement time only, which is what IgnoredDuringExecution in the field names means. If node labels change after a Pod starts, the Pod keeps running on its node. The rule applies again when a replacement Pod is created, so label changes affect new placements, not running ones.
Which topologyKey should Kubernetes scheduling anti-affinity use?
Kubernetes scheduling anti-affinity should use kubernetes.io/hostname to keep replicas on separate nodes and topology.kubernetes.io/zone to keep them in separate zones. Hostname protects against node loss and drains. Zone protects against a zone outage. Required rules on either key cap replicas at the number of domains, so check the ceiling before shipping.
How do I debug Kubernetes scheduling when a Pod is Pending?
Kubernetes scheduling debugging starts with kubectl describe pod and the FailedScheduling event, which counts nodes per rejection reason. Match each reason to a check: node labels for selector clauses, replica placement for anti-affinity clauses, requests for resource clauses. Then fix the smallest named cause, often by softening a required rule or repairing a drifted label.
When does Kubernetes scheduling need a custom scheduler profile?
Kubernetes scheduling needs a custom profile only when a workload class needs different plugin behaviour, such as packing batch Pods without spread scoring. A Pod selects a profile through spec.schedulerName, and a name that matches no profile leaves the Pod waiting with no event. Most teams should keep the default profile and express placement through Pod rules.
Preparing for Senior Platform & SRE Interviews
Practice real-world cluster triage, RBAC debugging, and pod scheduling scenarios in our Kubernetes scenario interview questions hub.
Explore Interview Scenarios →