GPU-Aware Cluster Manager and Pod Scheduler

Hard · System Design · Software Engineer · Technical Screen

Prompt

Design an object-oriented cluster manager and pod scheduler that assigns whole-GPU workloads onto multi-GPU machines. Represent cluster resources using these logical schemas:

  • Node: {name: string, total_gpu: int, running_pods: Pod[]}
  • Pod: {name: string, gpu_required: int}

Expose the following management, scheduling, and inspection methods:

  • add_node(name, total_gpu) and remove_node(name)
  • add_pod(name, gpu_required), schedule_pod(pod_name) (placing a pending workload onto one host that currently has enough unallocated GPUs), and remove_pod(pod_name)
  • get_node_utilization(name), list_nodes(), and list_pods()

Specify your in-memory index structures, placement heuristic, synchronization strategy, fault-handling rules, asymptotic complexity bounds, and concrete logic for schedule_pod.

Scope & Expectations

  • Data structures & complexity: Define indexes for fast lookups of pods/nodes by name and candidate hosts by free GPU count, explain how every add, delete, bind, and eviction updates those indexes, and give time and space complexity per API.
  • Placement heuristic & schedule_pod implementation: Justify a node-selection policy (such as best-fit vs. first-fit), provide clean code or pseudocode for schedule_pod, and handle edge cases including unschedulable requests where gpu_required exceeds every server's total_gpu and GPU fragmentation when small pods scatter across large hosts.
  • Concurrency & idempotency: Prevent race conditions or GPU over-allocation under simultaneous API calls, and ensure retried requests behave idempotently.
  • Node removal & eviction handling: Define safe behavior when remove_node is called on a server that still hosts active pods, covering cordoning, pod eviction, and rescheduling displaced workloads.

Step-by-step walkthrough

  1. Clarify requirements and cluster rules

    Think of a GPU cluster as a row of multi-stall parking garages. Each physical server is a node (for example, an 8-GPU machine), and each workload is a pod (the smallest deployable unit of containers that run together on one machine). Unlike flexible CPU threads that can time-share cores, a 4-GPU training or inference pod needs 4 whole, dedicated GPUs inside the same garage at the same time—you cannot give it 2 GPUs on server A and 2 GPUs on server B.

    Before writing data structures or code, lock down the exact rules and guarantees with the interviewer.

    Functional requirements

    • Node lifecycle (add_node, remove_node): Register a server with {name, total_gpu, running_pods} and remove it cleanly when hardware is retired or fails.
    • Pod lifecycle (add_pod, schedule_pod, remove_pod): add_pod(name, gpu_required) registers a pod in a pending state holding zero GPUs; schedule_pod(pod_name) assigns it to one node with enough free GPUs; remove_pod(pod_name) deletes the pod and releases its GPUs if it was running.
    • Cluster visibility (get_node_utilization, list_nodes, list_pods): Inspect per-node GPU usage and list every node and pod in the cluster.

    Non-functional requirements

    • Zero over-commitment (hard safety invariant): On every node at every instant, the sum of gpu_required across its running_pods must never exceed total_gpu.
    • Sub-millisecond scheduling latency: Finding a node and updating indexes must take microseconds of CPU time so the scheduler never bottlenecks pod startup.
    • Thread safety and idempotency: Concurrent threads calling schedule_pod and remove_pod must never double-assign the same GPUs. Every API must be idempotent—meaning that if a client times out and repeats the exact same request, the second call leaves cluster state unchanged instead of allocating GPUs twice.
    • Zero silent pod loss: Deleting an occupied host must either fail loudly by default or explicitly evacuate and re-place its active workloads.

    Explicit assumptions to state

    • A pod runs on a single node and requests a whole integer gpu_required >= 1 (multi-node gang scheduling and fractional GPUs are covered in follow-ups).
    • Physical GPU servers have small integer GPU counts, typically 1, 2, 4, 8, or 16 GPUs (G = 16 initially, extensible if larger nodes join).
    • schedule_pod can be called directly by a client and is also retried by a background loop (schedule_pending) whenever GPUs free up.
  2. Back-of-the-envelope scale estimates

    Ground the design in realistic numbers for an AI cloud cluster (such as a GPU cloud running training and inference jobs):

    Cluster size        2,000 GPU servers, mostly 8 GPUs each (some 4 and 16)  -> ~16,000 total GPUs
    Running pods        80% cluster utilization, average 2 GPUs per pod        -> ~6,400 running pods
    Pending queue       batch job bursts can submit thousands of pods at once  -> up to 10,000 pending pods
    API request rate    ~20 schedule/remove calls/s steady; bursts of ~1,000/s
    In-memory state     ~250 bytes/node + ~250 bytes/pod                       -> ~3-5 MB total RAM
    Bucket index size   one bucket per possible free-GPU count (0..16)         -> 17 buckets
    

    Three architectural conclusions fall straight out of this math:

    1. All cluster state fits comfortably in memory (~5 MB) inside a single scheduler process, backed by an append-only log on disk for crash recovery.
    2. One process-wide lock is fast enough. Updating a few hash maps and array buckets takes ~2–5 microseconds in Python or Go, so 1,000 calls/second keeps the lock busy less than 0.5% of the time.
    3. The real engineering challenges are GPU fragmentation, concurrency races, and safe node draining—not raw memory or CPU throughput.
  3. API contracts and failure reasons

    Give every method an unambiguous signature, return shape, and retry behavior:

    add_node(name, total_gpu) -> bool
        True  = node created
        False = exact retry (same name and same total_gpu already exists; no state change)
        ValueError if total_gpu < 1, or if name already exists with a different total_gpu
    
    remove_node(name, drain=False) -> dict[pod_name, new_node_name | None]
        NodeNotEmpty if running_pods is non-empty and drain=False
        drain=True: mark node unschedulable, evict its pods, reschedule largest-first, delete node;
                    returns {pod_name: new_node_name or None if now pending}
        unknown name -> {} (idempotent retry after node was already deleted)
    
    add_pod(name, gpu_required) -> bool
        True  = pod registered in PENDING state (node_name = None)
        False = exact retry (same name and same gpu_required)
        ValueError if gpu_required < 1, or if name exists with a different gpu_required
    
    schedule_pod(pod_name) -> node_name | None
        returns assigned node_name on success (or existing node_name if already scheduled)
        returns None if unplaceable right now, setting pod.reason to:
            "NO_NODE_LARGE_ENOUGH"    no schedulable node has total_gpu >= gpu_required
            "INSUFFICIENT_FREE_GPUS"  large-enough nodes exist, but none currently has enough free GPUs
        KeyError if pod_name has not been registered
    
    remove_pod(pod_name) -> bool
        True if pod existed (frees GPUs on its node if running, or removes from pending); False otherwise
    
    get_node_utilization(name) -> float
        returns (total_gpu - free_gpu) / total_gpu in [0.0, 1.0]; KeyError if unknown node
    
    list_nodes() -> list[{name, total_gpu, free_gpu, running_pods: [{name, gpu_required}]}]
    list_pods()  -> list[{name, gpu_required, node, reason}]
    schedule_pending() -> dict[pod_name, node_name]
    

    Notice two deliberate API choices:

    • Separating permanent vs. transient failure (NO_NODE_LARGE_ENOUGH vs. INSUFFICIENT_FREE_GPUS). If a user submits a 16-GPU pod to a cluster that only has 8-GPU servers, waiting for running jobs to finish will never make that pod fit. Reporting NO_NODE_LARGE_ENOUGH tells the caller or autoscaler immediately that larger hardware is required.
    • Using resource names as idempotency keys. Repeating add_pod("job-1", 4) or schedule_pod("job-1") after a network timeout returns cleanly without duplicating pods or GPUs, while a conflicting call like add_pod("job-1", 8) raises ValueError so client bugs are caught immediately.
  4. Data model and O(1) bucket indexes

    If we stored nodes in a plain list, every schedule_pod call would scan up to N = 2,000 nodes (O(N) time). Instead, we index every entity by the exact question we ask of it:

    • Hash maps (nodes, pods): A hash map (Python dict) maps name -> object in O(1) average time. Inside each Node, running_pods is also a dict mapping pod_name -> Pod so removing a finished pod is O(1) instead of scanning a list; list_nodes() converts it back to the {name, gpu_required} list shape at read time.
    • Bucket array (free_buckets[0..G]): Because free GPU counts on a server are small integers (0 through G, typically 16), we maintain an array where free_buckets[f] holds all schedulable nodes that currently have exactly f free GPUs. Each bucket is an ordered set (implemented with Python's OrderedDict, which remembers insertion order while supporting O(1) add, delete, and peek-oldest).
    • Capacity histogram (nodes_by_size[t]): Counts how many schedulable nodes have total_gpu == t, answering "does any server in the cluster have at least need total GPUs?" in at most G steps.

    Here is how free_buckets looks for three servers—node-a (8 free), node-b (4 free), and node-c (4 free)—before and after scheduling a 3-GPU pod:

    BEFORE schedule_pod("pod-1", gpu_required=3):
      free_buckets[0]: {}
      free_buckets[1]: {}  <-- node-b will land here (4 - 3 = 1 free)
      free_buckets[2]: {}
      free_buckets[3]: {}  <-- scan starts at index 3 (empty)
      free_buckets[4]: { "node-b", "node-c" }  <-- first non-empty bucket >= 3! Pick oldest: "node-b"
      ...
      free_buckets[8]: { "node-a" }
    
    AFTER binding "pod-1" to "node-b":
      free_buckets[1]: { "node-b" }            <-- moved in O(1)
      free_buckets[4]: { "node-c" }            <-- "node-a" (8 free) stays untouched for 8-GPU jobs!
    
    import threading
    from collections import OrderedDict
    
    
    class NodeNotEmpty(Exception):
        """Raised if a caller deletes an occupied server without enabling drain=True."""
    
    
    class Node:
        def __init__(self, name: str, total_gpu: int):
            self.name = name
            self.total_gpu = total_gpu
            self.free_gpu = total_gpu
            # running_pods: dict[pod_name, Pod] for O(1) bind and unbind
            self.running_pods = {}
            # schedulable becomes False when a node is cordoned for draining
            self.schedulable = True
    
    
    class Pod:
        def __init__(self, name: str, gpu_required: int):
            self.name = name
            self.gpu_required = gpu_required
            # node_name is None while the pod is waiting in self.pending
            self.node_name = None
            # reason explains why the most recent scheduling attempt returned None
            self.reason = None
    
    
    class Cluster:
        def __init__(self, initial_max_gpu: int = 16):
            self.max_gpu = initial_max_gpu
            self.lock = threading.Lock()
            self.nodes = {}    # node_name -> Node
            self.pods = {}     # pod_name -> Pod
            self.pending = {}  # pod_name -> Pod in FIFO arrival order (Python dict preserves order)
            # free_buckets[f]: OrderedDict[node_name, None] of schedulable nodes with f free GPUs
            self.free_buckets = [OrderedDict() for _ in range(initial_max_gpu + 1)]
            # nodes_by_size[t]: count of schedulable nodes whose hardware total_gpu == t
            self.nodes_by_size = [0] * (initial_max_gpu + 1)
    

    Every public method preserves three data invariants whenever self.lock is released:

    1. node.free_gpu == node.total_gpu - sum(p.gpu_required for p in node.running_pods.values()) and node.free_gpu >= 0.
    2. Every schedulable node appears in exactly one bucket—free_buckets[node.free_gpu]—and an unschedulable (cordoned) node appears in zero buckets.
    3. pod.node_name is None if and only if pod.name in self.pending.

    (Fallback for unbounded sizes: if a "node" represented a 1,000-GPU virtual pool instead of an 8–16 GPU physical server, replace free_buckets with a balanced binary search tree keyed by (free_gpu, node_name) so best-fit lookup and updates run in O(log N) time.)

  5. High-level system architecture

    In production, the in-memory Cluster object sits inside a fault-tolerant control plane:

        Job Controllers / CLI / Autoscaler
                        |
                        | HTTPS / gRPC (resource names + UIDs act as idempotency keys)
                        v
        +---------------------------------------------------+
        | API Layer (auth, schema validation, error codes)  |
        +---------------------------------------------------+
                        |
                        v
        +---------------------------------------------------+   append before reply   +-----------------------+
        | Cluster Core (single active leader, one lock)     | ----------------------> | Write-Ahead Log (WAL) |
        |  - nodes, pods, pending maps                      |                         | (Raft / etcd / disk)  |
        |  - free_buckets[0..G], nodes_by_size[0..G]        |                         +-----------------------+
        +---------------------------------------------------+
           ^                      ^                      |
           | schedule_pending()   | cordon / drain       | pod bindings
           | (on GPU free + 1s)   | on missed leases     v
        [ Pending Loop ]    [ Health Monitor ] <--- [ Node Agents (kubelet-like) ]
                                                      heartbeats every 10 s; launch/kill GPU containers
    

    Each component has one clear job:

    • Cluster Core: Holds all in-memory maps and buckets under self.lock and makes every placement decision.
    • Write-Ahead Log (WAL): An append-only durable log on disk (or a consensus store like etcd) where every mutation (NodeAdded, PodBound, NodeDrained) is persisted before returning success to the caller, allowing a crashed scheduler to replay the log and reconstruct identical in-memory buckets in milliseconds.
    • Node Agents and Health Monitor: Each GPU server runs a lightweight daemon that starts containers on assigned GPUs and sends a heartbeat (a periodic "I am alive" ping) every 10 seconds. Missed heartbeats trigger cordoning and draining.
    • Pending Loop: Triggers schedule_pending() whenever remove_pod or add_node frees capacity, plus a 1-second safety tick.
  6. Deep dive 1: Placement strategy and schedule_pod

    When a pod asks for need GPUs, three classic placement strategies exist:

    • First-Fit: Scan nodes in a fixed registration order and pick the first node with free_gpu >= need.
    • Best-Fit: Pick the node with the smallest free_gpu >= need, leaving the tightest remainder.
    • Worst-Fit (Spread): Pick the node with the largest free_gpu, spreading load evenly across servers.

    Why Best-Fit wins for GPU clusters: Multi-GPU training pods (4 or 8 GPUs) require an entire server or half-server all at once. First-Fit and Worst-Fit nibble away at empty 8-GPU servers with small 1-GPU or 4-GPU pods, stranding capacity:

    Trace 1 — Nodes A(8 GPUs), B(4 GPUs). Arrivals: pod1(4 GPUs), then pod2(8 GPUs).
      First-Fit (order A, B):  pod1 -> A (leaves A=4, B=4)  |  pod2(8) -> FAILS (neither has 8!)
      Best-Fit:                pod1 -> B (leaves A=8, B=0)  |  pod2(8) -> A (both fit!)
    
    Trace 2 — Nodes A(8 GPUs), B(8 GPUs). Arrivals: four 1-GPU pods, then pod5(8 GPUs).
      Worst-Fit (Spread):      2 pods on A, 2 pods on B (leaves A=6, B=6)  |  pod5(8) -> FAILS
      Best-Fit:                all 4 pods pack onto A   (leaves A=4, B=8)  |  pod5(8) -> B (fits!)
    

    Important caveat—Best-Fit is a greedy heuristic, not globally optimal: Bin packing is NP-hard (no fast algorithm finds the perfect packing for every future sequence). For example, if Node A has 5 GPUs, Node B has 4 GPUs, and pods of sizes 3, 4, 2 arrive in order, Best-Fit puts 3 -> B (1 left) and 4 -> A (1 left), blocking the 2-GPU pod—even though 3 + 2 on A and 4 on B would have fit all three! We pair Best-Fit with largest-first retries and reservations (Deep Dive 2) to recover from greedy traps. (When spreading IS desired—such as placing two replicas of an online inference service on separate hosts so one crash never takes down both—model that explicitly as an anti-affinity filter rather than making Worst-Fit the cluster default.)

    Tie-breaking: Within the winning bucket free_buckets[free], next(iter(bucket)) picks the node that has been sitting at that free count the longest in O(1) time—deterministic for unit testing and log replay.

    To make bucket corruption impossible, every change to node.free_gpu goes through _bind and _unbind, which always remove the node from its old bucket before mutating free_gpu and re-insert it into its new bucket after:

    class ClusterSchedulerCore(Cluster):
        # ----- internal index helpers (caller MUST hold self.lock) -----
    
        def _ensure_capacity(self, gpu_count: int) -> None:
            # Grow bucket and size arrays dynamically if a larger server (e.g., 32 GPUs) joins
            while len(self.free_buckets) <= gpu_count:
                self.free_buckets.append(OrderedDict())
                self.nodes_by_size.append(0)
            if gpu_count > self.max_gpu:
                self.max_gpu = gpu_count
    
        def _index_add(self, node: Node) -> None:
            if node.schedulable:
                self.free_buckets[node.free_gpu][node.name] = None
    
        def _index_remove(self, node: Node) -> None:
            self.free_buckets[node.free_gpu].pop(node.name, None)
    
        def _some_node_large_enough(self, need: int) -> bool:
            if need > self.max_gpu:
                return False
            for size in range(need, self.max_gpu + 1):
                if self.nodes_by_size[size] > 0:
                    return True
            return False
    
        def _best_fit(self, need: int):
            if need > self.max_gpu:
                return None
            # Scan upward from exact fit (free == need) to largest bucket (free == max_gpu)
            for free in range(need, self.max_gpu + 1):
                bucket = self.free_buckets[free]
                if bucket:
                    oldest_node_name = next(iter(bucket))
                    return self.nodes[oldest_node_name]
            return None
    
        def _bind(self, pod: Pod, node: Node) -> None:
            # Remove from old free-count bucket BEFORE subtracting GPUs
            self._index_remove(node)
            node.free_gpu -= pod.gpu_required
            node.running_pods[pod.name] = pod
            # Re-insert into the smaller free-count bucket
            self._index_add(node)
            pod.node_name = node.name
            pod.reason = None
            self.pending.pop(pod.name, None)
    
        def _unbind(self, pod: Pod) -> None:
            node = self.nodes[pod.node_name]
            self._index_remove(node)
            node.free_gpu += pod.gpu_required
            del node.running_pods[pod.name]
            self._index_add(node)
            pod.node_name = None
    
        def _schedule(self, pod: Pod):
            # Idempotent: already running -> return existing assignment without reallocating
            if pod.node_name is not None:
                return pod.node_name
            need = pod.gpu_required
            if not self._some_node_large_enough(need):
                pod.reason = "NO_NODE_LARGE_ENOUGH"
                return None
            node = self._best_fit(need)
            if node is None:
                pod.reason = "INSUFFICIENT_FREE_GPUS"
                return None
            self._bind(pod, node)
            return node.name
    
        def schedule_pod(self, pod_name: str):
            with self.lock:
                pod = self.pods.get(pod_name)
                if pod is None:
                    raise KeyError(f"unknown pod {pod_name}")
                return self._schedule(pod)
    
  7. Index maintenance across all APIs and complexity

    With _bind and _unbind encapsulating bucket transitions, the remaining CRUD and visibility methods stay short and bug-resistant:

    class ClusterAPI(ClusterSchedulerCore):
        def add_node(self, name: str, total_gpu: int) -> bool:
            if total_gpu < 1:
                raise ValueError("total_gpu must be at least 1")
            with self.lock:
                existing = self.nodes.get(name)
                if existing is not None:
                    if existing.total_gpu == total_gpu:
                        return False  # idempotent retry
                    raise ValueError(f"node {name} exists with {existing.total_gpu} GPUs")
                self._ensure_capacity(total_gpu)
                node = Node(name, total_gpu)
                self.nodes[name] = node
                self.nodes_by_size[total_gpu] += 1
                self._index_add(node)
                return True
    
        def add_pod(self, name: str, gpu_required: int) -> bool:
            if gpu_required < 1:
                raise ValueError("gpu_required must be at least 1")
            with self.lock:
                existing = self.pods.get(name)
                if existing is not None:
                    if existing.gpu_required == gpu_required:
                        return False  # idempotent retry
                    raise ValueError(f"pod {name} exists with gpu_required={existing.gpu_required}")
                pod = Pod(name, gpu_required)
                self.pods[name] = pod
                self.pending[name] = pod
                return True
    
        def remove_pod(self, pod_name: str) -> bool:
            with self.lock:
                pod = self.pods.pop(pod_name, None)
                if pod is None:
                    return False
                self.pending.pop(pod_name, None)
                if pod.node_name is not None:
                    self._unbind(pod)
                return True
    
        def get_node_utilization(self, name: str) -> float:
            with self.lock:
                node = self.nodes.get(name)
                if node is None:
                    raise KeyError(f"unknown node {name}")
                return (node.total_gpu - node.free_gpu) / node.total_gpu
    
        def list_nodes(self) -> list:
            with self.lock:
                result = []
                for node in self.nodes.values():
                    pods_view = [
                        {"name": p.name, "gpu_required": p.gpu_required}
                        for p in node.running_pods.values()
                    ]
                    result.append({
                        "name": node.name,
                        "total_gpu": node.total_gpu,
                        "free_gpu": node.free_gpu,
                        "running_pods": pods_view,
                    })
                return result
    
        def list_pods(self) -> list:
            with self.lock:
                return [
                    {
                        "name": pod.name,
                        "gpu_required": pod.gpu_required,
                        "node": pod.node_name,
                        "reason": pod.reason,
                    }
                    for pod in self.pods.values()
                ]
    

    Index update matrix and API complexity (N = nodes, P = pods, G = max GPUs per node ≈ 16, k = pods on a removed node, Q = pending pods):

    API / Event Indexes Updated Time Why (in plain words)
    add_node nodes, free_buckets[total], nodes_by_size[total] O(1) One dictionary insert, one bucket insert, one counter increment
    remove_node (empty) nodes, free_buckets, nodes_by_size O(1) One dictionary delete, one bucket delete, one counter decrement
    remove_node(drain=True) Cordon node, unbind k pods, re-place largest-first O(k log k + k * G) Sort k evicted pods (k <= G, so tiny) and scan at most G buckets per pod
    add_pod pods, pending O(1) Two dictionary inserts
    schedule_pod free_buckets (move node), running_pods, pending O(G) Scan at most G + 1 buckets (<= 17 on standard servers) plus O(1) map updates
    remove_pod pods, pending, free_buckets (move node up) O(1) Dictionary pops plus one O(1) bucket move if the pod was running
    get_node_utilization Read nodes[name] O(1) Single dictionary lookup and arithmetic
    list_nodes / list_pods Read nodes and running_pods / pods O(N + P) / O(P) Visits every node and pod once to serialize output
    schedule_pending Sort pending by size, schedule each O(Q log Q + Q * G) Sort Q waiting pods largest-first and attempt O(G) best-fit per pod

    Total space complexity is O(N + P + G): one Node record and one bucket entry per node, one Pod record per pod, and G + 1 bucket headers.

  8. Deep dive 2: Fragmentation, starvation, and reservations

    Even with Best-Fit, churn over hours creates external fragmentation—plenty of free GPUs exist across the cluster, yet they are scattered across partially used servers so a large pod cannot fit anywhere:

    4 nodes x 8 GPUs = 32 total GPUs, running twelve 1-GPU pods (20 GPUs free!):
      Fragmented cluster:  Node A [1,1,1,.,.,.,.,.] (5 free)   Node B [1,1,1,.,.,.,.,.] (5 free)
                           Node C [1,1,1,.,.,.,.,.] (5 free)   Node D [1,1,1,.,.,.,.,.] (5 free)
                           -> 20 GPUs free, yet ZERO 8-GPU pods (or even 6-GPU pods) can start!
    
      Best-Fit cluster:    Node A [1,1,1,1,1,1,1,1] (0 free)   Node B [1,1,1,1,.,.,.,.] (4 free)
                           Node C [.,.,.,.,.,.,.,.] (8 free)   Node D [.,.,.,.,.,.,.,.] (8 free)
                           -> Same twelve 1-GPU pods, and TWO 8-GPU training pods fit immediately!
    

    Track fragmentation directly on dashboards with two numbers:

    • largest_free_block: largest f with a non-empty free_buckets[f] (biggest pod placeable right now).
    • stranded_gpus(8): sum of free_gpu across all nodes with 0 < free_gpu < 8 (20 stranded GPUs in the fragmented layout vs. only 4 in the Best-Fit layout).

    We combine three mechanisms so large pods neither block small ones nor starve forever:

    1. Best-Fit Decreasing on schedule_pending: When capacity opens up, sort waiting pods from largest gpu_required down to smallest (preserving FIFO arrival order on ties because Python's sorted is stable) so an 8-GPU pod claims a newly emptied server before eight 1-GPU pods nibble it away:
    def _pod_gpu_required(pod: Pod) -> int:
        return pod.gpu_required
    
    
    class ClusterPendingMixin(ClusterAPI):
        def schedule_pending(self) -> dict:
            with self.lock:
                placed = {}
                # sorted() materializes a snapshot list first, so _bind can safely pop from self.pending;
                # Python's Timsort is stable, keeping FIFO arrival order among equal-sized pods.
                ordered_pending = sorted(
                    self.pending.values(),
                    key=_pod_gpu_required,
                    reverse=True,
                )
                for pod in ordered_pending:
                    node_name = self._schedule(pod)
                    if node_name is not None:
                        placed[pod.name] = node_name
                return placed
    
    1. Bounded node reservations against starvation: If a steady stream of 1-GPU inference pods arrives every second, a draining 8-GPU node might reach 7 free GPUs and immediately get refilled by another 1-GPU pod, starving a waiting 8-GPU job forever. A reservation fixes this: if a pod with INSUFFICIENT_FREE_GPUS waits longer than 5 minutes, pick a node with total_gpu >= need and the fewest used GPUs, pull it out of free_buckets so no new unrelated pods land on it, and bind the waiting large pod the instant its remaining pods exit. Cap reservations at 5% of cluster nodes so idle-draining cost stays bounded.
    2. Backfilling instead of strict FIFO: Strict first-in-first-out queuing causes head-of-line blocking (one unplaceable 8-GPU pod at the front blocks fifty 1-GPU pods behind it while 4-GPU holes sit idle). With backfilling, smaller pods jump ahead into unreserved nodes immediately, and can even use a reserved node if they declare a maximum runtime shorter than the reserved node's remaining drain time.
  9. Deep dive 3: Concurrency, idempotency, and failure handling

    Preventing the check-then-act race: Without synchronization, two threads scheduling two 4-GPU pods onto node-a (4 free GPUs) race like this:

    Thread 1: reads free_buckets[4] -> sees "node-a" (free_gpu = 4)
    Thread 2: reads free_buckets[4] -> ALSO sees "node-a" (free_gpu = 4)
    Thread 1: subtracts 4 -> node-a.free_gpu = 0, binds pod-x
    Thread 2: subtracts 4 -> node-a.free_gpu = -4, binds pod-y  (OVER-COMMITTED!)
    

    Wrapping every public method in with self.lock: makes "check free_buckets + decrement free_gpu + move bucket" a single atomic critical section. Thread 2 runs microsecond later, sees node-a in free_buckets[0], and cleanly picks another node or sets INSUFFICIENT_FREE_GPUS. Per-node fine-grained locks are a trap here because schedule_pod must read the global free_buckets array and mutate a node together. (If horizontal multi-replica scheduling is ever needed, each replica reads a cached cluster snapshot and commits bindings via optimistic concurrency control—a compare-and-set write that succeeds only if node.version in the backing store still equals the snapshot version, retrying on conflict.)

    Guarding idempotency against name reuse: Name-based idempotency has one subtle edge case: a client deletes train-7, creates a brand-new train-7, and then a delayed network retry of the first remove_pod("train-7") arrives and kills the new job! Solve this by assigning a unique uid (UUID or monotonic generation number) on add_pod and accepting an optional expected_uid on remove_pod.

    Write-ahead log + group commit without holding the lock on disk I/O: Holding self.lock during a 2 ms disk flush would cap throughput at 500 calls/s. Instead: 1. Acquire self.lock, validate and update in-memory maps/buckets, append a serialized log record with sequence number lsn to an in-memory buffer, and release self.lock. 2. A background flusher writes all queued records in a single disk fsync (group commit—amortizing one disk write across dozens of concurrent calls). 3. Both mutating calls and read/no-op retries wait until flushed_lsn >= observed_lsn before returning to the client, guaranteeing no acknowledged state ever disappears on crash.

    Safe node removal and crash handling (remove_node): By default (drain=False), remove_node raises NodeNotEmpty so a typo never kills active training runs. With drain=True, we cordon first (remove the node from free_buckets and nodes_by_size so nothing new lands on it—including the pods we are about to reschedule!), evict running pods, and reschedule largest-first:

    class ClusterFull(ClusterPendingMixin):
        def remove_node(self, name: str, drain: bool = False) -> dict:
            with self.lock:
                node = self.nodes.get(name)
                if node is None:
                    return {}  # idempotent: node was already removed
                if node.running_pods and not drain:
                    raise NodeNotEmpty(f"node {name} still runs {len(node.running_pods)} pods")
    
                # Step 1 — Cordon: remove from free_buckets and size counts BEFORE rescheduling
                self._index_remove(node)
                node.schedulable = False
                self.nodes_by_size[node.total_gpu] -= 1
    
                # Step 2 — Evict all running pods back to pending
                evicted_pods = list(node.running_pods.values())
                for pod in evicted_pods:
                    self._unbind(pod)
                    self.pending[pod.name] = pod
                del self.nodes[name]
    
                # Step 3 — Reschedule largest pods first so big pods claim empty nodes first
                evicted_pods.sort(key=_pod_gpu_required, reverse=True)
                placements = {}
                for pod in evicted_pods:
                    placements[pod.name] = self._schedule(pod)
                return placements
    

    Split-brain protection on network partitions: If a node stops sending heartbeats for 30 seconds, it might simply have lost network connectivity while its GPU processes are still writing to shared checkpoint storage! Rescheduling immediately would run two copies of the same job (split-brain). Fix this with a lease: the node agent automatically kills local containers if it cannot renew its control-plane lease within 30 seconds, and the scheduler waits until that 30-second lease + clock-skew grace window expires before rescheduling evicted pods.

  10. Scaling to 10x and trade-off summary

    At 10× scale (20,000 nodes, 160,000 GPUs, ~64,000 pods), schedule_pod still scans only G = 17 buckets, and RAM is ~50 MB. Three bottlenecks emerge in order, each with a clean fix:

    1. WAL disk flushes at thousands of bindings/s: Solved by group commit (batching all mutations arriving within 1–2 ms into a single log flush).
    2. list_nodes() / list_pods() holding self.lock for tens of milliseconds: Serve read-only list endpoints with pagination from an asynchronously updated read snapshot (or log-fed read replica) so dashboards never stall schedule_pod.
    3. Heterogeneous GPUs and multi-pool scaling: An H100-80GB GPU is not interchangeable with an A100-40GB GPU. Maintain one independent (free_buckets, nodes_by_size) pool per (gpu_model, region) pair; beyond a single leader's throughput, run one independent Cluster process per pool (cell architecture).

    Summary of key trade-offs

    • Fixed bucket array (O(G)) vs. balanced search tree (O(log N)): Buckets give O(1) updates and <= 17-step scans for real GPU servers; balanced trees take over only if virtual node sizes grow into the thousands.
    • Best-Fit + reservations vs. First-Fit / Spread: Preserves full empty servers for 8-GPU jobs while bounding large-pod starvation, trading a small reservation drain overhead (<5% of nodes) for dramatically lower GPU stranding.
    • Single lock + group-commit WAL vs. fine-grained locks: Eliminates race conditions and deadlocks in a few lines of code while comfortably handling >10,000 in-memory ops/s.
    • Refuse-by-default removal + lease-gated draining: Protects running GPU workloads from accidental deletion and split-brain corruption while ensuring zero pods vanish silently.

Intuition & how it works

Imagine running parking dispatch for a fleet of 8-stall and 4-stall garages where sedans need 1 stall and full-length tour buses need 8 stalls inside the same garage at once. In a GPU cluster, each server is a node (a garage with total_gpu slots) and each workload is a pod (a vehicle needing gpu_required slots on a single server).

The obvious beginner design keeps nodes in a plain list, scans from the front to pick the first server with enough free GPUs (first-fit), and subtracts GPUs directly. That naive approach fails in three ways: scanning N servers on every placement wastes O(N) time, dropping small 1-GPU jobs onto empty 8-GPU servers fragments the cluster so 8-GPU training jobs starve even when dozens of GPUs sit idle overall, and two concurrent requests can read the same free_gpu count and double-book the same physical GPUs.

Instead, we group schedulable servers into an array of free-GPU buckets free_buckets[0..16] (where free_buckets[f] is an insertion-ordered hash set of servers with exactly f free GPUs) and use Best-Fit under a single lock—scanning upward from need to 16 so every pod takes the tightest-fitting server and leaves empty 8-GPU servers intact. Walk through a tiny trace with node-a (8 GPUs), node-b (4 GPUs), and three pods:

  1. Initially free_buckets[4] = {"node-b"} and free_buckets[8] = {"node-a"}, with size counts nodes_by_size[4] = 1, nodes_by_size[8] = 1.
  2. schedule_pod("pod-small") (gpu_required = 4) scans starting at free_buckets[4], immediately finds "node-b", moves "node-b" to free_buckets[0] in O(1) time, and leaves "node-a" untouched in free_buckets[8].
  3. schedule_pod("pod-big") (gpu_required = 8) scans starting at free_buckets[8], binds to "node-a", and moves "node-a" to free_buckets[0]. (First-fit in registration order node-a, node-b would have put pod-small on node-a, leaving 4 free on each node and blocking pod-big!)
  4. schedule_pod("pod-huge") (gpu_required = 16) checks nodes_by_size for size >= 16, finds zero such servers, and immediately returns None with reason = "NO_NODE_LARGE_ENOUGH" instead of waiting forever for capacity that does not exist.

Key trade-offs

  • Bucket array (O(G)) vs. balanced binary search tree (O(log N)). Because physical GPU servers hold a small integer number of GPUs (G <= 16 on standard 4-, 8-, or 16-GPU hosts), an array of G + 1 ordered buckets finds the best-fit node in at most 17 bucket checks and moves a node between buckets in O(1) dictionary operations. A balanced binary search tree (a sorted tree that stays shallow so lookups and updates take O(log N) steps across N nodes, keyed by (free_gpu, node_name)) requires more complex pointer updates per call, so it is only preferable if "nodes" represent virtual pools with thousands of GPUs.
  • Best-Fit vs. First-Fit vs. Worst-Fit (Spread). Best-Fit packs partially used servers first, preserving completely empty 8-GPU servers for large jobs. First-Fit is slightly simpler if unindexed, while Worst-Fit spreads pods across hosts so a hardware crash affects fewer replicas of one service—at the heavy cost of stranding free GPUs everywhere. Because bin packing is NP-hard (no fast greedy rule is optimal on all arrival orders), we pair Best-Fit with largest-first pending retries and bounded node reservations (temporarily holding a node off-limits to small pods until running pods exit so a starving 8-GPU job can start), applying spreading only as an explicit anti-affinity rule for replicated services.
  • Backfilling vs. strict FIFO queuing. Strict first-in-first-out queuing is fair but suffers from head-of-line blocking, where one unplaceable 8-GPU pod at the front stalls dozens of 1-GPU pods behind it while GPUs sit idle. Backfilling lets smaller pods jump ahead into unreserved holes (or onto a reserved node if their declared runtime finishes before the node drains), maximizing utilization while time-capped reservations prevent large-pod starvation.
  • Single coarse lock vs. per-node locks vs. optimistic concurrency. One process-wide lock makes bucket lookups and node updates atomic in ~2–5 microseconds per call, supporting well over 10,000 calls/second with zero deadlock risk. Per-node locks add complex lock-ordering and re-validation logic because the global free_buckets index and the chosen Node must change together. If multiple active scheduler replicas are ever required, optimistic concurrency control (committing a binding to shared storage via compare-and-set on node.version and retrying on version mismatch) avoids distributed locks at the cost of retry churn when the cluster is nearly full.
  • Refuse-by-default vs. automatic drain on remove_node. Raising NodeNotEmpty by default protects long-running GPU training jobs from accidental operator commands. Explicit drain=True cordons the node first (marking it unschedulable and removing it from free_buckets so evicted pods cannot bounce right back onto it), evicts its pods, and reschedules largest-first while returning every pod's new node (or None if queued).
  • Logging state mutations vs. persisting bucket indexes. Buckets and size histograms are derived data, so only source-of-truth events (NodeAdded, PodBound, PodRemoved, NodeDrained) are appended to the write-ahead log (WAL) (an append-only crash-recovery log flushed via group commit, where one disk sync batches many queued calls outside the in-memory lock). Rebuilding buckets on startup takes one O(N + P) pass over the loaded nodes and pods—a few milliseconds—and eliminates disk-to-index drift.

Common mistakes

  • Scanning all N nodes linearly inside schedule_pod. Iterating over self.nodes.values() on every call takes O(N) time and defeats sub-linear host selection by unallocated GPU count.
  • Mutating node.free_gpu without removing and re-inserting in free_buckets. If free_gpu drops from 8 to 4 while node remains inside free_buckets[8], the next 8-GPU pod picks that node and over-commits physical GPUs. Centralizing every capacity change inside _bind and _unbind prevents index desynchronization.
  • Storing node.running_pods internally as a plain list. Removing a pod from a list takes O(k) linear search and allows accidental duplicate appends; keeping a dict internally gives O(1) removal while list_nodes() still emits the expected Pod[] list schema.
  • Conflating NO_NODE_LARGE_ENOUGH with INSUFFICIENT_FREE_GPUS. Returning a single generic None leaves a 16-GPU pod waiting forever in an 8-GPU cluster with zero feedback to the user or cluster autoscaler.
  • Check-then-act race conditions or holding the lock across disk/network I/O. Reading free capacity outside a lock allows double-allocation under concurrent calls, while keeping self.lock held during disk flushes or RPCs to node agents stretches a microsecond lock into milliseconds and stalls all scheduling.
  • Evicting pods during remove_node before cordoning the node. If the node is still inside free_buckets when its pods are unbound and rescheduled, _schedule immediately places those same pods right back onto the node being deleted.
  • Rescheduling pods from an unreachable node before its heartbeat lease expires. A network-partitioned server may still be executing GPU kernels and writing checkpoints; starting a replacement pod early causes split-brain checkpoint corruption.
  • Forgetting idempotency and name reuse. A retried schedule_pod("p1") must return p1's existing node rather than allocating a second set of GPUs, and pairing names with unique creation uids stops a delayed retry of an old remove_pod("p1") from killing a newly created pod with the same name.

Follow-up questions

  • How would you adapt the data model and placement logic to support fractional GPU sharing across small inference workloads? If the hardware uses NVIDIA Multi-Instance GPU (MIG)—a hardware feature on A100/H100 cards that partitions one GPU into up to seven isolated slices with dedicated memory and compute—treat each MIG slice profile (such as 1g.10gb or 2g.20gb) as its own discrete resource pool with its own bucket array. If pods share a GPU via software time-slicing (which lacks hardware memory isolation), each GPU must also track free_vram_mb alongside compute slices, refusing any placement whose memory sum exceeds card VRAM. Keep fractional inference nodes in a separate pool from whole-GPU training nodes so tiny 1/7-GPU slices never fragment the servers needed by 8-GPU training jobs.
  • How would you extend the scheduler for distributed multi-node training jobs that need all worker pods placed simultaneously (gang scheduling)? A distributed training job cannot make progress until all 4 of its 8-GPU worker pods are running at once, so scheduling its pods one at a time risks a cluster deadlock where Job A holds 2 of its 4 nodes, Job B holds the remaining 2 nodes, and both wait forever. Instead, implement all-or-nothing gang scheduling under self.lock: verify that 4 distinct nodes can satisfy the 4 member pods (using Best-Fit per member and preferring nodes under the same leaf network switch or rack for fast gradient exchange), bind all 4 atomically if they fit, or bind zero and keep the entire gang pending. Starving gangs use whole-node reservations capped at a small percentage of cluster capacity so 1-node jobs cannot starve them indefinitely.
  • How would you incorporate intra-server hardware topology (such as NVSwitch, PCIe switches, and NUMA affinity) when assigning specific GPUs inside an 8-GPU host? Track a bitmask of individual free GPU IDs (0..7) on each Node rather than an anonymous integer count, and return the chosen gpu_ids list on binding. free_buckets still filters candidate nodes by free GPU count in O(G) time, and a second-level scorer picks the subset of GPUs on that node with the fastest hardware interconnect: on NVSwitch servers (where an all-to-all crossbar connects all 8 GPUs at uniform bandwidth), prefer GPUs attached to the same CPU socket and network card (NUMA locality), whereas on PCIe servers (where GPUs sit in tree-structured switch pairs), pack a 2- or 4-GPU pod under a single PCIe switch or CPU socket so peer-to-peer GPU traffic never crosses the slow inter-socket CPU link.

Follow-up questions

Similar questions

More Together AI interview questions

All 9 Together AI questions →