Best-Fit GPU Pod Placement and Node Drain Check
Medium · Coding & Algorithms · Software Engineer · Technical Screen
Problem Statement
Design an allocator that assigns multi-GPU jobs ("pods") onto physical servers ("nodes") in an accelerator cluster. Every server starts with a fixed total GPU count, and every incoming pod asks for an integer quantity gpus_needed that must reside wholly on a single server (splitting one pod across two servers is disallowed).
Implement GPUClusterManager together with the replay function run_gpu_cluster_manager(nodes, operations, arguments):
GPUClusterManager(nodes: Dict[str, int]): Sets up the cluster wherenodes[node_id]gives the initial GPU capacity of servernode_id(all GPUs start unallocated).schedule_pod(pod_id: str, gpus_needed: int) -> Optional[str]: Placespod_idonto one qualifying server (free_gpus >= gpus_needed) under a deterministic Best-Fit rule:- Prefer the qualifying server with the smallest number of currently free GPUs (so exact-capacity matches win immediately).
- Break ties by picking the
node_idthat comes first in lexicographical (ASCII string) order. When a server qualifies, subtractgpus_neededfrom its free pool, recordpod_idon that server, and returnnode_id. When no server has at leastgpus_neededfree GPUs, leave cluster state untouched and returnNone.
can_drain(node_id: str) -> bool: Runs a read-only simulation testing whethernode_idcould be emptied for maintenance. Every pod currently hosted onnode_idmust fit onto the remaining servers (nodesexcludingnode_id) without moving or evicting pods already placed on those other servers. Simulate migration deterministically by orderingnode_id's current pods by descendinggpus_needed(breaking ties by ascending lexicographicalpod_id) and placing them one after another onto the remaining servers using the same Best-Fit rule. ReturnTrueif all pods onnode_idland successfully, orFalseif any pod fails to fit. Real cluster state must not change.run_gpu_cluster_manager(nodes: Dict[str, int], operations: List[str], arguments: List[List]) -> List: CreatesGPUClusterManager(nodes), runs each"schedule_pod"([pod_id, gpus_needed]) or"can_drain"([node_id]) call in order, and returns the list of outputs.
Examples
Example 1
Input:
nodes = {"srv-a": 16, "srv-b": 16, "srv-c": 8}
operations = [
"schedule_pod", "schedule_pod", "schedule_pod",
"can_drain", "can_drain", "schedule_pod"
]
arguments = [
["w1", 8], ["w2", 6], ["w3", 12],
["srv-a"], ["srv-c"], ["w4", 4]
]
Output: ["srv-c", "srv-a", "srv-b", False, True, "srv-b"]
Walk-through:
- "w1" (8 GPUs) fits all three servers; "srv-c" has the fewest free GPUs (8), leaving srv-a: 16, srv-b: 16, srv-c: 0.
- "w2" (6 GPUs) ties at 16 between "srv-a" and "srv-b", so "srv-a" wins alphabetically, leaving srv-a: 10, srv-b: 16, srv-c: 0.
- "w3" (12 GPUs) only fits on "srv-b", leaving srv-a: 10, srv-b: 4, srv-c: 0.
- can_drain("srv-a") tries moving "w2" (6 GPUs) into {srv-b: 4, srv-c: 0}, which fails (False).
- can_drain("srv-c") tries moving "w1" (8 GPUs) into {srv-a: 10, srv-b: 4}, fitting on "srv-a" (True) while keeping real free counts unchanged.
- "w4" (4 GPUs) then picks "srv-b" (4 free beats 10 free on "srv-a").
Example 2
Input:
nodes = {"host1": 6, "host2": 5, "host3": 5}
operations = [
"schedule_pod", "schedule_pod", "schedule_pod",
"schedule_pod", "schedule_pod", "can_drain"
]
arguments = [
["j1", 2], ["j2", 3], ["j3", 3],
["j4", 8], ["j5", 3], ["host2"]
]
Output: ["host2", "host2", "host3", None, "host1", True]
Walk-through: "j1" (2) chooses "host2" (5 < 6, tie broken over "host3"), and "j2" (3) fills "host2"'s remaining 3 GPUs. "j3" (3) goes to "host3" (2 free left). "j4" (8) exceeds every server's free GPUs and returns None. "j5" (3) lands on "host1" (3 free left). Finally, can_drain("host2") sorts host2's pods largest-first ("j2" of size 3, then "j1" of size 2), placing "j2" onto "host1" (3 free) and "j1" onto "host3" (2 free) -> True.
Constraints
1 <= len(nodes) <= 500- Initial GPU capacity per server:
1 <= capacity <= 64 1 <= gpus_needed <= 64node_idandpod_idare non-empty ASCII strings, and allpod_idstrings passed toschedule_podare distinct.
Step-by-step walkthrough
Understand the goal and rules
We are building
GPUClusterManagerto place GPU workloads ("pods") onto worker machines ("nodes"). Each node starts with a fixed total number of GPUs, and each pod asks for an integer number of GPUs that must fit entirely on one node (we cannot split a 4-GPU pod into 2 GPUs on one machine and 2 on another).We need to support two operations:
schedule_pod(pod_id, gpus_needed): Find an eligible node (available >= gpus_needed) using the Best-Fit rule — pick the node with the fewest available GPUs so we pack tight spaces first and save big nodes for big pods. Break ties by choosing the smallestnode_idin lexicographical order (dictionary string order, character by character). If a node is found, subtractgpus_needed, record the pod, and returnnode_id; if no node fits, change nothing and returnNone.can_drain(node_id): Perform a dry run (a read-only check that never changes the real cluster) to see if we could takenode_idoffline for maintenance. Take all pods currently running onnode_id, sort them from largest GPU request to smallest (breaking ties bypod_id), and try placing them one by one onto the other nodes using Best-Fit without moving any pods already on those other nodes. ReturnTrueif every pod fits, orFalseotherwise.
The judge tests our class through
run_gpu_cluster_manager(nodes, operations, arguments), which initializes oneGPUClusterManager(nodes)and collects the return value of each operation in order.Design the cluster state
What does the manager need to remember at any moment? Only two dictionaries:
self.free_gpus: how many GPUs are currently unused on each node.self.node_pods: which pods are currently running on each node, and how many GPUs each pod uses (socan_drainknows what needs to be moved).
Example 1 state after scheduling w1(8) on srv-c, w2(6) on srv-a, w3(12) on srv-b: self.free_gpus = { "srv-a": 10, "srv-b": 4, "srv-c": 0, } self.node_pods = { "srv-a": {"w2": 6}, "srv-b": {"w3": 12}, "srv-c": {"w1": 8}, }Do we need a fancy tree or heap to find the Best-Fit node? Look at the constraints: there are at most
N <= 500nodes, and each node holds at most 64 GPUs. Scanning 500 dictionary entries takes microseconds in Python. Even better, a plain min-heap would not work directly anyway because the node with the fewest free GPUs overall might have0or4GPUs when we need8. A clean linear scan is fast, exact, and bug-free.Pick a node with the Best-Fit helper
Why does minimizing
availablegive the same result as minimizing the leftoveravailable - gpus_needed? Becausegpus_neededis the same constant for every candidate node in a singleschedule_podcall — subtracting the same number from every candidate never changes which one is smallest:Need 8 GPUs: srv-a has 16 available -> 16 - 8 = 8 leftover srv-c has 8 available -> 8 - 8 = 0 leftover (exact fit, smallest available!)To handle both the Best-Fit rule and the tie-breaker cleanly, we compare 2-element tuples
(available, node_id). Python compares tuples from left to right: it comparesavailablefirst, and only if two nodes have the exact sameavailablecount does it comparenode_idas strings ("srv-a" < "srv-b", and"srv-10" < "srv-2"because'1'comes before'2').Notice that we pass
free_gpusin as a parameter instead of readingself.free_gpusdirectly. That letsschedule_podpass the real dictionary andcan_drainpass a scratch copy!def find_best_fit_node(free_gpus: Dict[str, int], gpus_needed: int) -> Optional[str]: """Return the eligible node with the fewest free GPUs; break ties by smallest node_id.""" best_node: Optional[str] = None # best_key stores (available_gpus, node_id) for the tightest eligible node seen so far. best_key: Optional[Tuple[int, str]] = None for node_id, available in free_gpus.items(): # Skip nodes that cannot fit the entire pod on this single machine. if available < gpus_needed: continue # Comparing (available, node_id) prefers fewer free GPUs first, then lexicographically # smaller node_id on ties (e.g. "srv-a" < "srv-b", and "srv-10" < "srv-2"). candidate_key = (available, node_id) if best_key is None or candidate_key < best_key: best_key = candidate_key best_node = node_id return best_nodeImplement initialization and pod scheduling
In
__init__, we copynodeswithdict(nodes)so modifyingself.free_gpusnever alters the caller's dictionary, and we create an empty{}pod dictionary for each node.In
schedule_pod, we callfind_best_fit_node. If it returnsNone, we returnNoneright away before touching any state. Otherwise, we deductgpus_neededfrom that node's free GPUs and record the pod.class GPUClusterManager: def __init__(self, nodes: Dict[str, int]): # self.free_gpus: {"srv-a": 16, ...} mapping node_id -> currently available GPUs. # Copy the input dictionary so we never mutate the caller's data. self.free_gpus: Dict[str, int] = dict(nodes) # self.node_pods: {"srv-a": {"w2": 6}, ...} mapping node_id -> {pod_id: gpus_needed}. self.node_pods: Dict[str, Dict[str, int]] = {} for node_id in nodes: self.node_pods[node_id] = {} def schedule_pod(self, pod_id: str, gpus_needed: int) -> Optional[str]: chosen_node = find_best_fit_node(self.free_gpus, gpus_needed) # If no node has enough free GPUs, leave the cluster state completely unchanged. if chosen_node is None: return None self.free_gpus[chosen_node] -= gpus_needed self.node_pods[chosen_node][pod_id] = gpus_needed return chosen_nodeSimulate draining a node safely
can_drain(node_id)has three critical steps:- Copy
self.free_gpusand removenode_id.simulated_free = dict(self.free_gpus)creates a brand-new dictionary so simulated placements never changeself.free_gpus. Deletingsimulated_free[node_id]ensures we never accidentally "migrate" a pod back onto the node we are trying to drain! - Sort pods largest-first, breaking ties by
pod_id. Why does order matter? Supposenode-dholds pods of sizes2, 2, 3and the other nodes have4and3free GPUs:- Moving
3first puts3onto the3-GPU node (exact fit!), leaving the4-GPU node to hold2 + 2-> succeeds (True). - Moving
2first puts2onto the3-GPU node (Best-Fit!), leaving free counts[4, 1], which leaves nowhere for3-> wait:3could fit on4leaving[1, 1], which then strands the second2(False)! Storing(-gpus_needed, pod_id)lets standard ascending.sort()put largergpus_neededfirst (since-6 < -4) while still sortingpod_idalphabetically on ties.
- Moving
- Place each pod with
find_best_fit_nodeonsimulated_free. Subtract GPUs fromsimulated_freeas each pod lands. If any pod getsNone, returnFalseimmediately; if the loop finishes, every pod found a home (including the trivial case wherenode_idhad zero pods), so returnTrue.
def can_drain(self, node_id: str) -> bool: # Phase 1: Build a scratch copy of free GPUs on all OTHER nodes so the dry run # never mutates self.free_gpus and never places pods back onto the drained node. simulated_free = dict(self.free_gpus) del simulated_free[node_id] # Phase 2: Sort the drained node's pods by descending GPU size, then ascending pod_id. # Negating gpus_needed lets Python's ascending tuple sort handle both rules at once. pods_to_move: List[Tuple[int, str]] = [] for pod_id, gpus_needed in self.node_pods[node_id].items(): pods_to_move.append((-gpus_needed, pod_id)) pods_to_move.sort() # Phase 3: Greedily place each pod onto the remaining nodes using Best-Fit. for neg_gpus, pod_id in pods_to_move: gpus_needed = -neg_gpus target_node = find_best_fit_node(simulated_free, gpus_needed) if target_node is None: return False simulated_free[target_node] -= gpus_needed return TrueFinally,
run_gpu_cluster_managerinstantiatesGPUClusterManager(nodes)and replays each operation in order:def run_gpu_cluster_manager( nodes: Dict[str, int], operations: List[str], arguments: List[List], ) -> List: # Replay each method call against a single GPUClusterManager instance and collect outputs. manager = GPUClusterManager(nodes) results = [] for op, args in zip(operations, arguments): if op == "schedule_pod": pod_id, gpus_needed = args[0], args[1] results.append(manager.schedule_pod(pod_id, gpus_needed)) elif op == "can_drain": node_id = args[0] results.append(manager.can_drain(node_id)) else: raise ValueError(f"Unknown operation: {op}") return results- Copy
Trace Example 1 step by step
Let's trace Example 1 from start to finish on
{"srv-a": 16, "srv-b": 16, "srv-c": 8}:Initial free GPUs: srv-a: 16, srv-b: 16, srv-c: 8 1. schedule_pod("w1", 8) Eligible (>= 8): srv-a (16), srv-b (16), srv-c (8) Smallest free is srv-c (8) -> returns "srv-c" Real free: srv-a: 16, srv-b: 16, srv-c: 0 | pods on srv-c: {w1: 8} 2. schedule_pod("w2", 6) Eligible (>= 6): srv-a (16), srv-b (16) Tie at 16 broken by "srv-a" < "srv-b" -> returns "srv-a" Real free: srv-a: 10, srv-b: 16, srv-c: 0 | pods on srv-a: {w2: 6} 3. schedule_pod("w3", 12) Eligible (>= 12): srv-b (16) -> returns "srv-b" Real free: srv-a: 10, srv-b: 4, srv-c: 0 | pods on srv-b: {w3: 12} 4. can_drain("srv-a") Scratch copy without srv-a: {srv-b: 4, srv-c: 0} Pods on srv-a sorted: [(-6, "w2")] -> need 6 GPUs No node in scratch copy has >= 6 -> returns False Real free is UNCHANGED: srv-a: 10, srv-b: 4, srv-c: 0 5. can_drain("srv-c") Scratch copy without srv-c: {srv-a: 10, srv-b: 4} Pods on srv-c sorted: [(-8, "w1")] -> need 8 GPUs Fits on srv-a (10 >= 8) -> scratch becomes {srv-a: 2, srv-b: 4} -> returns True Real free is UNCHANGED: srv-a: 10, srv-b: 4, srv-c: 0 6. schedule_pod("w4", 4) Eligible (>= 4): srv-a (10), srv-b (4) Smallest free is srv-b (4) -> returns "srv-b" Real free: srv-a: 10, srv-b: 0, srv-c: 0 | pods on srv-b: {w3: 12, w4: 4}Collected outputs:
["srv-c", "srv-a", "srv-b", False, True, "srv-b"].Complete solution
Putting the helper,
GPUClusterManager, and the judge driverrun_gpu_cluster_managertogether gives the complete solution:from typing import Any, Dict, List, Optional, Set, Tuple def find_best_fit_node(free_gpus: Dict[str, int], gpus_needed: int) -> Optional[str]: """Return the eligible node with the fewest free GPUs; break ties by smallest node_id.""" best_node: Optional[str] = None # best_key stores (available_gpus, node_id) for the tightest eligible node seen so far. best_key: Optional[Tuple[int, str]] = None for node_id, available in free_gpus.items(): # Skip nodes that cannot fit the entire pod on this single machine. if available < gpus_needed: continue # Comparing (available, node_id) prefers fewer free GPUs first, then lexicographically # smaller node_id on ties (e.g. "srv-a" < "srv-b", and "srv-10" < "srv-2"). candidate_key = (available, node_id) if best_key is None or candidate_key < best_key: best_key = candidate_key best_node = node_id return best_node class GPUClusterManager: def __init__(self, nodes: Dict[str, int]): # self.free_gpus: {"srv-a": 16, ...} mapping node_id -> currently available GPUs. # Copy the input dictionary so we never mutate the caller's data. self.free_gpus: Dict[str, int] = dict(nodes) # self.node_pods: {"srv-a": {"w2": 6}, ...} mapping node_id -> {pod_id: gpus_needed}. self.node_pods: Dict[str, Dict[str, int]] = {} for node_id in nodes: self.node_pods[node_id] = {} def schedule_pod(self, pod_id: str, gpus_needed: int) -> Optional[str]: chosen_node = find_best_fit_node(self.free_gpus, gpus_needed) # If no node has enough free GPUs, leave the cluster state completely unchanged. if chosen_node is None: return None self.free_gpus[chosen_node] -= gpus_needed self.node_pods[chosen_node][pod_id] = gpus_needed return chosen_node def can_drain(self, node_id: str) -> bool: # Phase 1: Build a scratch copy of free GPUs on all OTHER nodes so the dry run # never mutates self.free_gpus and never places pods back onto the drained node. simulated_free = dict(self.free_gpus) del simulated_free[node_id] # Phase 2: Sort the drained node's pods by descending GPU size, then ascending pod_id. # Negating gpus_needed lets Python's ascending tuple sort handle both rules at once. pods_to_move: List[Tuple[int, str]] = [] for pod_id, gpus_needed in self.node_pods[node_id].items(): pods_to_move.append((-gpus_needed, pod_id)) pods_to_move.sort() # Phase 3: Greedily place each pod onto the remaining nodes using Best-Fit. for neg_gpus, pod_id in pods_to_move: gpus_needed = -neg_gpus target_node = find_best_fit_node(simulated_free, gpus_needed) if target_node is None: return False simulated_free[target_node] -= gpus_needed return True def run_gpu_cluster_manager( nodes: Dict[str, int], operations: List[str], arguments: List[List], ) -> List: # Replay each method call against a single GPUClusterManager instance and collect outputs. manager = GPUClusterManager(nodes) results = [] for op, args in zip(operations, arguments): if op == "schedule_pod": pod_id, gpus_needed = args[0], args[1] results.append(manager.schedule_pod(pod_id, gpus_needed)) elif op == "can_drain": node_id = args[0] results.append(manager.can_drain(node_id)) else: raise ValueError(f"Unknown operation: {op}") return results✅ Submit now — all tests should pass.
Intuition & how it works
Think of GPU scheduling like seating groups of diners at restaurant tables where each party must sit together at a single table. If a party of 8 walks in and you have both an 8-seat table and an empty 16-seat table, seating them at the 8-seat table preserves the 16-seat table for a party of 12 arriving five minutes later. That strategy is called Best-Fit (choosing the smallest available container that can still hold the item, breaking ties by lexicographical order, meaning alphabetical/character-by-character string order like "srv-a" < "srv-b"). Similarly, can_drain is like checking on scratch paper whether everyone sitting in a section that wants to close early can move into empty seats at other tables without asking anyone already seated elsewhere to move — a dry run (a read-only simulation performed on a temporary copy of state so the real cluster stays untouched).
Why do simpler approaches fail? If you pick the first node that fits in dictionary order (First-Fit) or the node with the most free GPUs (Worst-Fit), small pods chew up big nodes and leave fragmented leftovers too small for later multi-GPU pods. During can_drain, if you forget to copy self.free_gpus (or forget to delete the drained node from the copy), you either corrupt future schedule_pod calls or mistakenly "migrate" pods right back onto the node being drained. And if you move pods in arrival order instead of largest-first, small pods can occupy tight slots needed by larger pods.
Here is a mini trace on {"srv-a": 16, "srv-c": 8}:
1. schedule_pod("w1", 8) -> Both fit, but srv-c has 8 free vs 16 free -> "srv-c"
State: free = {"srv-a": 16, "srv-c": 0}, pods on srv-c = {"w1": 8}
2. schedule_pod("w3", 12) -> Only srv-a (16 >= 12) fits -> "srv-a"
State: free = {"srv-a": 4, "srv-c": 0}, pods on srv-a = {"w3": 12}
3. can_drain("srv-c") -> Scratch copy without srv-c is {"srv-a": 4}.
"w1" needs 8 GPUs, 4 < 8 -> returns False (real state unchanged).
Complexity
Let N be the number of nodes (N <= 500), P be the number of pods currently on the node being drained (P <= 64 since each pod needs at least 1 GPU and a node has at most 64 GPUs), and M be the total number of scheduled pods across the cluster.
__init__:- Time:
O(N), because we copyNentries intoself.free_gpusand initializeNempty dictionaries inself.node_pods. - Space:
O(N)for those two per-node dictionaries.
- Time:
schedule_pod:- Time:
O(N), becausefind_best_fit_nodescans allNnodes once doingO(1)tuple comparisons, followed byO(1)dictionary updates. - Space:
O(1)extra per call (O(N + M)total across the lifetime of the cluster to store all placed pods).
- Time:
can_drain:- Time:
O(N + P log P + P * N), because copyingself.free_gpustakesO(N), sorting thePpods on the drained node takesO(P log P), and each of thePpods runs oneO(N)Best-Fit scan. SinceP <= 64andN <= 500, a drain does at most64 * 500 = 32,000lightweight checks. - Space:
O(N + P)temporary, to holdsimulated_free(N - 1entries) andpods_to_move(Ptuples), both discarded whencan_drainreturns.
- Time:
Edge cases
- No node has enough free GPUs:
schedule_podreturnsNoneand leavesself.free_gpusandself.node_podsuntouched so later smaller pods can still fit. - String tie-breaking (
"srv-10"vs"srv-2"): Lexicographical order compares character by character ('1' < '2'), so"srv-10"wins over"srv-2"regardless of dictionary insertion order. - Exact-fit nodes (
available == gpus_needed): Eligible (>=) and guaranteed to have0leftover GPUs, the tightest possible fit. - Draining an empty node:
pods_to_moveis empty, socan_drainreturnsTrueimmediately — even in a single-node cluster. - Draining the only node when it holds a pod: Removing
node_idleavessimulated_freeempty ({}), so the first pod fails to find a target andcan_drainreturnsFalse. - Ignoring free space on the drained node itself: Even if
srv-ahas 10 free GPUs and one 6-GPU pod,del simulated_free["srv-a"]preventssrv-afrom serving as its own migration target. - Greedy vs. exact packing:
can_drainspecifies a deterministic Best-Fit Decreasing simulation, not exact bin packing. For example, pods[3, 2, 2, 2]could theoretically pack into free capacities[4, 5]as(2 + 2)and(3 + 2), but greedy Best-Fit puts3onto the4-GPU node first (4 < 5), leaving[1, 5]and stranding the last2-GPU pod (False).
Common mistakes
- Mutating
self.free_gpusduringcan_drain: Writingsimulated_free = self.free_gpuscopies only the dictionary reference, not the dictionary itself, silently corrupting subsequentschedule_podcalls. Always make a shallow copy withdict(self.free_gpus). - Forgetting
del simulated_free[node_id]: Leaving the drained node insidesimulated_freelets pods land right back on the node being drained. - Draining pods in insertion order or ascending order: Moving small pods first can consume tight slots needed by big pods (e.g., pods
[2, 2, 3]into free[4, 3]succeeds only when3moves first). - Relying on dictionary iteration order for ties: Python dictionaries preserve insertion order, which is not sorted order; always include
node_idin the comparison key(available, node_id).
Alternative approaches
- 65 size buckets (
0..64): Since node capacity is at most64, you could group node IDs into 65 buckets indexed by current free GPU count (each bucket holding a min-heap or sorted set ofnode_idstrings). Best-Fit then checks bucketsgpus_needed .. 64and takes the smallestnode_idin the first non-empty bucket inO(65 + log N)time, at the cost of much heavier bookkeeping to copy duringcan_drain. - Sorted list of
(available, node_id): Usingbisect(binary search — repeatedly halving a sorted array to find an insertion point inO(log N)time) finds the Best-Fit node inO(log N), though removing and re-inserting updated tuples still takesO(N)list shifts unless backed by a balanced search tree.
Follow-up questions
- Because Best-Fit Decreasing is a heuristic, it can reject a node whose pods actually do pack into the cluster. How would you implement an exact feasibility check for
can_drain, and for what pod counts is exact search practical? Exact feasibility is variable-sized bin packing (fitting items of given sizes into fixed-capacity containers without exceeding any container's limit), which is NP-hard (no known algorithm runs in polynomial time for all inputs). First, run the fast greedy check: if it returnsTrue, the placement is valid and we are done! Otherwise, for up toP <= 15–20pods, backtracking search with symmetry pruning (placing largest pods first and trying at most one node per distinct free-GPU count so symmetric nodes are never explored twice) or bitmask dynamic programming (representing each subset of placed pods as aP-bit integer inO(2^P * P)time) solves exact feasibility in milliseconds. When a 64-GPU node holds up toP = 64small pods, group pods by GPU size (1..64) and hand the count-based formulation to an integer linear programming (ILP) solver with a short timeout. - If hundreds of callers invoke
schedule_podsimultaneously, how would you ensure thread safety while keeping scheduling throughput high? Start by measuring: scanning 500 integers under a single mutex lock (a mutual-exclusion lock allowing one thread at a time) takes only a few microseconds, handling tens of thousands of placements per second while preserving strict Best-Fit determinism. If lock contention ever becomes real (for instance, when binding a pod involves slow network RPCs to worker nodes), decouple the fast in-memory reservation from the slow network bind, or use optimistic concurrency (read a lock-free snapshot of free counts, pick a candidate node, and atomically reserve GPUs on that node with a compare-and-swap / CAS check — retrying only if another thread modified that exact node first). For massive clusters, you can also shard (partition) nodes into independent scheduling pools, trading strict global Best-Fit for parallel throughput. - Real GPU servers partition accelerators across CPU sockets and high-speed interconnect islands (such as NVLink groups). How would you model hardware topology instead of storing a single free-GPU count per node? Replace the single integer per node with a hierarchical structure or bitmask (a 64-bit integer where bit
iis1if physical GPUiis free) grouped by hardware domain, such as two NUMA sockets (CPU memory domains where GPUs on the same socket communicate faster) or 4-GPU/8-GPU NVLink islands (high-bandwidth GPU-to-GPU interconnect groups). When a multi-GPU training pod requests locality, eligibility checks each island or socket before falling back to cross-socket placement, preferring the smallest island that fits the whole pod so intact 8-GPU islands remain free for 8-GPU jobs.
Follow-up questions
- Because Best-Fit Decreasing is a heuristic, it can reject a node whose pods actually do pack into the cluster. How would you implement an exact feasibility check for `can_drain`, and for what pod counts is exact search practical?
- If hundreds of callers invoke `schedule_pod` simultaneously, how would you ensure thread safety while keeping scheduling throughput high?
- Real GPU servers partition accelerators across CPU sockets and high-speed interconnect islands (such as NVLink groups). How would you model hardware topology instead of storing a single free-GPU count per node?
Similar questions
- Single-Edge Cycle Removal in Pod Dependencies
- Versioned Key-Value Store Queries
- Balance Whole Lines Across Chunked Text
- GPU-Aware Cluster Manager and Pod Scheduler
- Tracing Linux CPU Bottlenecks from Host to Code
- Isolating Low Network Bandwidth Across Hosts and Containers
More Together AI interview questions
- GPU-Aware Cluster Manager and Pod Scheduler Hard
- Single-Edge Cycle Removal in Pod Dependencies Medium
- Tracing Linux CPU Bottlenecks from Host to Code Easy Pro
- Isolating Low Network Bandwidth Across Hosts and Containers Easy Pro
- Pinpointing Storage Bottlenecks and Competing Disk Workloads Easy Pro
- Versioned Key-Value Store Queries Medium Pro
- Triage and Prevention of Logging-Induced Host Overload Easy Pro
- Balance Whole Lines Across Chunked Text Easy Pro