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 where nodes[node_id] gives the initial GPU capacity of server node_id (all GPUs start unallocated).
  • schedule_pod(pod_id: str, gpus_needed: int) -> Optional[str]: Places pod_id onto one qualifying server (free_gpus >= gpus_needed) under a deterministic Best-Fit rule:
    1. Prefer the qualifying server with the smallest number of currently free GPUs (so exact-capacity matches win immediately).
    2. Break ties by picking the node_id that comes first in lexicographical (ASCII string) order. When a server qualifies, subtract gpus_needed from its free pool, record pod_id on that server, and return node_id. When no server has at least gpus_needed free GPUs, leave cluster state untouched and return None.
  • can_drain(node_id: str) -> bool: Runs a read-only simulation testing whether node_id could be emptied for maintenance. Every pod currently hosted on node_id must fit onto the remaining servers (nodes excluding node_id) without moving or evicting pods already placed on those other servers. Simulate migration deterministically by ordering node_id's current pods by descending gpus_needed (breaking ties by ascending lexicographical pod_id) and placing them one after another onto the remaining servers using the same Best-Fit rule. Return True if all pods on node_id land successfully, or False if 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: Creates GPUClusterManager(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 <= 64
  • node_id and pod_id are non-empty ASCII strings, and all pod_id strings passed to schedule_pod are distinct.

Step-by-step walkthrough

  1. Understand the goal and rules

    We are building GPUClusterManager to 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 smallest node_id in lexicographical order (dictionary string order, character by character). If a node is found, subtract gpus_needed, record the pod, and return node_id; if no node fits, change nothing and return None.
    • can_drain(node_id): Perform a dry run (a read-only check that never changes the real cluster) to see if we could take node_id offline for maintenance. Take all pods currently running on node_id, sort them from largest GPU request to smallest (breaking ties by pod_id), and try placing them one by one onto the other nodes using Best-Fit without moving any pods already on those other nodes. Return True if every pod fits, or False otherwise.

    The judge tests our class through run_gpu_cluster_manager(nodes, operations, arguments), which initializes one GPUClusterManager(nodes) and collects the return value of each operation in order.

  2. Design the cluster state

    What does the manager need to remember at any moment? Only two dictionaries:

    1. self.free_gpus: how many GPUs are currently unused on each node.
    2. self.node_pods: which pods are currently running on each node, and how many GPUs each pod uses (so can_drain knows 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 <= 500 nodes, 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 have 0 or 4 GPUs when we need 8. A clean linear scan is fast, exact, and bug-free.

  3. Pick a node with the Best-Fit helper

    Why does minimizing available give the same result as minimizing the leftover available - gpus_needed? Because gpus_needed is the same constant for every candidate node in a single schedule_pod call — 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 compares available first, and only if two nodes have the exact same available count does it compare node_id as strings ("srv-a" < "srv-b", and "srv-10" < "srv-2" because '1' comes before '2').

    Notice that we pass free_gpus in as a parameter instead of reading self.free_gpus directly. That lets schedule_pod pass the real dictionary and can_drain pass 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_node
    
  4. Implement initialization and pod scheduling

    In __init__, we copy nodes with dict(nodes) so modifying self.free_gpus never alters the caller's dictionary, and we create an empty {} pod dictionary for each node.

    In schedule_pod, we call find_best_fit_node. If it returns None, we return None right away before touching any state. Otherwise, we deduct gpus_needed from 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_node
    
  5. Simulate draining a node safely

    can_drain(node_id) has three critical steps:

    1. Copy self.free_gpus and remove node_id. simulated_free = dict(self.free_gpus) creates a brand-new dictionary so simulated placements never change self.free_gpus. Deleting simulated_free[node_id] ensures we never accidentally "migrate" a pod back onto the node we are trying to drain!
    2. Sort pods largest-first, breaking ties by pod_id. Why does order matter? Suppose node-d holds pods of sizes 2, 2, 3 and the other nodes have 4 and 3 free GPUs:
      • Moving 3 first puts 3 onto the 3-GPU node (exact fit!), leaving the 4-GPU node to hold 2 + 2 -> succeeds (True).
      • Moving 2 first puts 2 onto the 3-GPU node (Best-Fit!), leaving free counts [4, 1], which leaves nowhere for 3 -> wait: 3 could fit on 4 leaving [1, 1], which then strands the second 2 (False)! Storing (-gpus_needed, pod_id) lets standard ascending .sort() put larger gpus_needed first (since -6 < -4) while still sorting pod_id alphabetically on ties.
    3. Place each pod with find_best_fit_node on simulated_free. Subtract GPUs from simulated_free as each pod lands. If any pod gets None, return False immediately; if the loop finishes, every pod found a home (including the trivial case where node_id had zero pods), so return True.
        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
    

    Finally, run_gpu_cluster_manager instantiates GPUClusterManager(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
    
  6. 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"].

  7. Complete solution

    Putting the helper, GPUClusterManager, and the judge driver run_gpu_cluster_manager together 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 copy N entries into self.free_gpus and initialize N empty dictionaries in self.node_pods.
    • Space: O(N) for those two per-node dictionaries.
  • schedule_pod:
    • Time: O(N), because find_best_fit_node scans all N nodes once doing O(1) tuple comparisons, followed by O(1) dictionary updates.
    • Space: O(1) extra per call (O(N + M) total across the lifetime of the cluster to store all placed pods).
  • can_drain:
    • Time: O(N + P log P + P * N), because copying self.free_gpus takes O(N), sorting the P pods on the drained node takes O(P log P), and each of the P pods runs one O(N) Best-Fit scan. Since P <= 64 and N <= 500, a drain does at most 64 * 500 = 32,000 lightweight checks.
    • Space: O(N + P) temporary, to hold simulated_free (N - 1 entries) and pods_to_move (P tuples), both discarded when can_drain returns.

Edge cases

  • No node has enough free GPUs: schedule_pod returns None and leaves self.free_gpus and self.node_pods untouched 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 have 0 leftover GPUs, the tightest possible fit.
  • Draining an empty node: pods_to_move is empty, so can_drain returns True immediately — even in a single-node cluster.
  • Draining the only node when it holds a pod: Removing node_id leaves simulated_free empty ({}), so the first pod fails to find a target and can_drain returns False.
  • Ignoring free space on the drained node itself: Even if srv-a has 10 free GPUs and one 6-GPU pod, del simulated_free["srv-a"] prevents srv-a from serving as its own migration target.
  • Greedy vs. exact packing: can_drain specifies 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 puts 3 onto the 4-GPU node first (4 < 5), leaving [1, 5] and stranding the last 2-GPU pod (False).

Common mistakes

  • Mutating self.free_gpus during can_drain: Writing simulated_free = self.free_gpus copies only the dictionary reference, not the dictionary itself, silently corrupting subsequent schedule_pod calls. Always make a shallow copy with dict(self.free_gpus).
  • Forgetting del simulated_free[node_id]: Leaving the drained node inside simulated_free lets 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 when 3 moves first).
  • Relying on dictionary iteration order for ties: Python dictionaries preserve insertion order, which is not sorted order; always include node_id in the comparison key (available, node_id).

Alternative approaches

  • 65 size buckets (0..64): Since node capacity is at most 64, you could group node IDs into 65 buckets indexed by current free GPU count (each bucket holding a min-heap or sorted set of node_id strings). Best-Fit then checks buckets gpus_needed .. 64 and takes the smallest node_id in the first non-empty bucket in O(65 + log N) time, at the cost of much heavier bookkeeping to copy during can_drain.
  • Sorted list of (available, node_id): Using bisect (binary search — repeatedly halving a sorted array to find an insertion point in O(log N) time) finds the Best-Fit node in O(log N), though removing and re-inserting updated tuples still takes O(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 returns True, the placement is valid and we are done! Otherwise, for up to P <= 15–20 pods, 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 a P-bit integer in O(2^P * P) time) solves exact feasibility in milliseconds. When a 64-GPU node holds up to P = 64 small 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_pod simultaneously, 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 i is 1 if physical GPU i is 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

Similar questions

More Together AI interview questions

All 9 Together AI questions →