Fix Priority Preemption in GPU Leasing

Medium · Software Engineering Fundamentals · Software Engineer · Onsite

Problem Statement

You are maintaining GPUManager, an in-memory lease coordinator that assigns total_gpus devices (indexed 0 through total_gpus - 1) to compute jobs based on numeric priority scores.

An early prototype iterated directly over active_leases.items() without synchronization, immediately replacing the first active lease whose priority was lower than the caller's and discarding the evicted job's identifier. In multi-GPU pools, this killed medium-priority jobs on lower-numbered GPUs while lower-priority jobs elsewhere kept running; under multi-threaded callers, concurrent check-then-write races allowed lower-priority requests to overwrite higher-priority leases.

Implement a corrected, thread-safe GPUManager class with the following interface:

from typing import Any, Dict, List


class GPUManager:
    def __init__(self, total_gpus: int) -> None:
        ...

    def request_gpu(self, job_id: Any, priority: float) -> bool:
        ...

Required State & Allocation Rules

  1. Public state:
    • self.active_leases: dictionary mapping gpu_id (int) to {"job_id": job_id, "priority": priority} for every currently leased GPU. All GPUs start idle ({}).
    • self.preempted: list of job_id values evicted due to preemption, recorded in chronological order ([] initially).
  2. Idle capacity first: When one or more GPUs in 0 .. total_gpus - 1 are not in active_leases, assign the lowest-numbered idle GPU to job_id and return True without preempting any running job.
  3. Weakest-victim preemption: When every GPU is busy (and total_gpus > 0), find the active lease with the lowest priority, breaking ties by selecting the lowest gpu_id.
    • If the incoming priority is strictly greater (>) than that weakest lease's priority, append the displaced job's job_id to self.preempted, assign that gpu_id to the incoming job, and return True.
    • If total_gpus <= 0 or priority is less than or equal to (<=) the weakest active priority, leave active_leases and preempted unchanged and return False.
  4. Thread safety: Concurrent request_gpu calls from multiple threads must execute atomically with no lost leases, duplicate assignments, or dropped preemption records.

Examples

Example 1

manager = GPUManager(2)
manager.request_gpu("train-alpha", 40)   # True  -> GPU 0
manager.request_gpu("eval-beta", 10)     # True  -> GPU 1
manager.request_gpu("urgent-gamma", 50)  # True  -> evicts "eval-beta" on GPU 1
manager.request_gpu("peer-delta", 40)    # False -> ties weakest active priority (40)

# manager.active_leases -> {
#     0: {"job_id": "train-alpha", "priority": 40},
#     1: {"job_id": "urgent-gamma", "priority": 50},
# }
# manager.preempted -> ["eval-beta"]

Walk-through: "train-alpha" and "eval-beta" claim idle GPUs 0 and 1. When "urgent-gamma" arrives with priority 50, both GPUs are occupied; although 50 beats GPU 0 (40), GPU 1 holds the weakest lease (10), so "eval-beta" is evicted on GPU 1. Next, "peer-delta" arrives with priority 40, which ties the new minimum active priority (40 on GPU 0) rather than strictly beating it, so it returns False.

Example 2

manager = GPUManager(3)
manager.request_gpu("j1", 30)  # True -> GPU 0
manager.request_gpu("j2", 15)  # True -> GPU 1
manager.request_gpu("j3", 15)  # True -> GPU 2
manager.request_gpu("j4", 20)  # True -> tie at 15 on GPUs 1 & 2; evicts "j2" on GPU 1
manager.request_gpu("j5", 25)  # True -> evicts "j3" on GPU 2

# manager.active_leases -> {
#     0: {"job_id": "j1", "priority": 30},
#     1: {"job_id": "j4", "priority": 20},
#     2: {"job_id": "j5", "priority": 25},
# }
# manager.preempted -> ["j2", "j3"]

Walk-through: After GPUs 0, 1, 2 fill with priorities 30, 15, 15, "j4" (20) sees a tie for the weakest priority (15) between GPUs 1 and 2 and deterministically evicts "j2" on lower-numbered GPU 1. Then "j5" (25) evicts the remaining priority-15 lease "j3" on GPU 2.

Constraints

  • 0 <= total_gpus <= 10,000
  • job_id can be any Python value (such as str or int).
  • priority is a finite int or float.
  • request_gpu must be safe under concurrent multi-threaded execution.
  • Target per-request time complexity is O(total_gpus) with O(total_gpus + P) space across P cumulative preemptions.

Step-by-step walkthrough

  1. Trace the prototype bugs across multi-GPU and concurrent runs

    Always begin debugging by tracing concrete scenarios step by step. In preemption (interrupting a currently running lower-priority job so a higher-priority job can take its resource), look at what goes wrong in an unsynchronized prototype that loops over active_leases.items() and returns on the first lower-priority match:

    Scenario 1 — 2 GPUs, single thread (Example 1):
      "train-alpha" (p=40) -> GPU 0,  "eval-beta" (p=10) -> GPU 1
      "urgent-gamma" (p=50) arrives:
        naive loop visits GPU 0 first -> checks 50 > 40 (True!) -> evicts "train-alpha" right away!
        wrong result: {0: urgent-gamma/50, 1: eval-beta/10}
        (priority-40 job killed while priority-10 job keeps running!)
    
    Scenario 2 — 1 GPU, concurrent requests from "w2" (p=20) and "w3" (p=30):
      GPU 0 currently holds "w1" (p=10).
      Thread w3 reads lease p=10 -> sees 30 > 10 -> writes {0: w3/30}, returns True
      Thread w2 already read p=10 -> sees 20 > 10 -> writes {0: w2/20}, returns True!
      Final state: w2 overwrote w3! Higher-priority w3 lost the GPU to lower-priority w2.
    

    Scenario 1 exposes the victim-selection flaw in the loop, and Scenario 2 exposes the concurrency race where a lower-priority thread silently overwrites a higher-priority allocation.

  2. Catalog all three flaws in the naive allocator

    Inspecting that prototype pattern surfaces three distinct defects:

    1. Evicting the first beatable lease instead of the weakest lease: Returning immediately on the first GPU where priority > lease["priority"] depends on Python dictionary insertion order. Whichever GPU happened to be leased earliest gets checked first, so a priority-50 job evicts a priority-40 job on GPU 0 while a priority-10 job sits untouched on GPU 1.
    2. Check-then-act race condition: A race condition (a bug where correctness depends on unpredictable thread timing) occurs because checking idle GPUs, scanning active_leases, and writing self.active_leases[gpu_id] = ... run without a lock. Two threads can claim the same idle GPU or overwrite a higher-priority preemption with a stale lower-priority write.
    3. Silent eviction: Overwriting self.active_leases[gpu_id] discards the displaced job's identifier instead of appending it to self.preempted, leaving callers unable to stop or requeue the interrupted workload.

    One detail must remain strict: requiring priority > weakest_priority (not >=) prevents two equal-priority jobs such as "train-alpha" (40) and "peer-delta" (40) from endlessly evicting each other back and forth.

  3. Design a deterministic, atomic preemption rule

    To make every allocation predictable and thread-safe, enforce three clear rules inside a single critical section (a block of code protected by a lock so only one thread executes it at a time):

    1. Idle GPUs always come first: Scan GPU IDs 0, 1, ..., total_gpus - 1 and assign the lowest-numbered idle GPU if any is free. Never preempt a running job while hardware sits idle.
    2. Otherwise compare against the single weakest lease: Scan GPU IDs 0, 1, ..., total_gpus - 1 to find the active lease with the minimum priority (breaking ties by choosing the lowest gpu_id). Comparing against this single minimum answers everything: if the new job cannot strictly beat the weakest lease (priority <= weakest_priority), it cannot beat any lease on the cluster!
    3. Record every preemption atomically: Wrap the entire read-decide-write sequence in with self._lock: and append the evicted job_id to self.preempted right before replacing its dictionary entry.
  4. Write the idle-GPU and weakest-lease helper scans

    Both helpers loop over range(self.total_gpus) in numeric order rather than iterating over dictionary keys, guaranteeing that past allocation history never changes future decisions. In _weakest_lease, using strict < (lease_priority < weakest_priority) ensures that when GPUs 1 and 2 tie at priority 15 (as in Example 2), lower-numbered GPU 1 stays selected:

    from typing import Any, Dict, Optional
    
    
    class GPUManager:
        def _first_free_gpu(self) -> Optional[int]:
            """Return the lowest GPU id not currently in active_leases, or None."""
            for gpu_id in range(self.total_gpus):
                if gpu_id not in self.active_leases:
                    return gpu_id
            return None
    
        def _weakest_lease(self) -> Optional[int]:
            """Return the GPU id of the lowest-priority lease (lowest GPU id wins ties)."""
            weakest_gpu_id: Optional[int] = None
            weakest_priority: Optional[float] = None
    
            # Iterate GPU ids 0..total_gpus-1 so behavior never depends on dict insertion order.
            for gpu_id in range(self.total_gpus):
                lease = self.active_leases.get(gpu_id)
                if lease is None:
                    continue
                lease_priority = lease["priority"]
                # Strict '<' keeps the first (lowest-numbered) GPU when priorities tie.
                if weakest_priority is None or lease_priority < weakest_priority:
                    weakest_gpu_id = gpu_id
                    weakest_priority = lease_priority
    
            return weakest_gpu_id
    
  5. Assemble the thread-safe request_gpu method

    Now combine both helpers inside with self._lock:. Notice the edge case total_gpus == 0: _first_free_gpu() returns None and _weakest_lease() also returns None, so checking if target_gpu is None: return False cleanly rejects requests on an empty pool without crashing:

    from typing import Any, Dict, List, Optional
    import threading
    
    
    class GPUManager:
        def __init__(self, total_gpus: int) -> None:
            self.total_gpus = total_gpus
            # active_leases: maps gpu_id (int) -> {"job_id": Any, "priority": float}
            self.active_leases: Dict[int, Dict[str, Any]] = {}
            # preempted: evicted job_ids in chronological order, e.g. ["eval-beta", "j2"]
            self.preempted: List[Any] = []
            # _lock: mutex serializing the entire check-decide-write sequence across threads
            self._lock = threading.Lock()
    
        def request_gpu(self, job_id: Any, priority: float) -> bool:
            # Hold the lock across both lookup and update so two concurrent callers
            # cannot select the same GPU and overwrite each other's lease.
            with self._lock:
                # Phase 1: prefer the lowest-numbered idle GPU before preempting anyone.
                target_gpu = self._first_free_gpu()
    
                if target_gpu is None:
                    # Phase 2: all GPUs are busy, so locate the weakest (lowest-priority) lease.
                    target_gpu = self._weakest_lease()
                    if target_gpu is None:
                        # total_gpus <= 0: cluster has no GPUs to lease at all.
                        return False
    
                    victim_lease = self.active_leases[target_gpu]
                    # Use '<=' so equal-priority jobs cannot endlessly preempt each other.
                    if priority <= victim_lease["priority"]:
                        return False
    
                    # Phase 3: record the evicted job before replacing its lease entry.
                    self.preempted.append(victim_lease["job_id"])
    
                self.active_leases[target_gpu] = {
                    "job_id": job_id,
                    "priority": priority,
                }
                return True
    
  6. Design unit tests that deterministically catch both regressions

    Naive unit tests easily miss both bugs unless you structure assertions carefully:

    1. Catching wrong-victim selection: Use at least 2 GPUs where an earlier GPU holds a medium priority (40) and a later GPU holds the lowest priority (10), followed by a request with high priority (50). Do not only assert request_gpu(...) is True—a buggy first-match loop also returns True! Assert both active_leases ({0: train-alpha, 1: urgent-gamma}) and preempted (["eval-beta"]).
    2. Catching equal-priority and tie-breaking boundaries: Assert that equal priority (40 vs 40) returns False without mutating active_leases; assert that idle GPUs are assigned before preempting; and assert deterministic tie-breaking on lowest gpu_id (Example 2: GPUs 1 and 2 tied at 15 evict GPU 1 first).
    3. Deterministically catching missing locks: Spawning random threads rarely hits a 3-line Python race window because of CPython's bytecode scheduling. Instead, inject a dict subclass whose __setitem__ pauses briefly at a 2-thread threading.Barrier(2, timeout=0.2). Without self._lock, both threads compute their target GPU before writing, meet at the barrier, and overwrite each other; with self._lock, Thread 1 enters alone, times out cleanly after 0.2s, writes its lease, and releases the lock before Thread 2 reads anything!
    def test_sample_1():
        manager = GPUManager(2)
        manager.request_gpu("train-alpha", 40)   # GPU 0 gets medium priority 40
        manager.request_gpu("eval-beta", 10)     # GPU 1 gets weakest priority 10
    
        # Priority 50 beats both 40 and 10, so it MUST evict eval-beta on GPU 1, not train-alpha on GPU 0.
        assert manager.request_gpu("urgent-gamma", 50) is True
        assert manager.request_gpu("peer-delta", 40) is False
        assert manager.active_leases == {
            0: {"job_id": "train-alpha", "priority": 40},
            1: {"job_id": "urgent-gamma", "priority": 50},
        }
        assert manager.preempted == ["eval-beta"]
    

    Let us trace our corrected code on Example 1's preemption call:

    State before call:  active_leases = {0: train-alpha/40, 1: eval-beta/10},  preempted = []
    Call request_gpu("urgent-gamma", 50):
      1. Acquire _lock
      2. _first_free_gpu(): GPU 0 busy, GPU 1 busy -> None
      3. _weakest_lease():
           gpu_id=0 -> weakest=(gpu 0, priority 40)
           gpu_id=1 -> priority 10 < 40 -> weakest=(gpu 1, priority 10)
           returns gpu_id = 1
      4. Compare 50 <= 10 (False -> preemption allowed)
      5. Append "eval-beta" to preempted -> ["eval-beta"]
      6. Write active_leases[1] = {"job_id": "urgent-gamma", "priority": 50}
      7. Release _lock and return True
    
  7. Complete solution

    from typing import Any, Dict, List, Optional
    import threading
    
    
    class GPUManager:
        """Leases GPUs to jobs.
    
        A request takes the lowest-numbered idle GPU if there is one. Otherwise it may
        preempt the lowest-priority lease, but only if its own priority is strictly higher.
        """
    
        def __init__(self, total_gpus: int) -> None:
            self.total_gpus = total_gpus
            # active_leases: maps gpu_id (int) -> {"job_id": Any, "priority": float}
            self.active_leases: Dict[int, Dict[str, Any]] = {}
            # preempted: evicted job_ids in chronological order, e.g. ["eval-beta", "j2"]
            self.preempted: List[Any] = []
            # _lock: mutex serializing the entire check-decide-write sequence across threads
            self._lock = threading.Lock()
    
        def request_gpu(self, job_id: Any, priority: float) -> bool:
            # Hold the lock across both lookup and update so two concurrent callers
            # cannot select the same GPU and overwrite each other's lease.
            with self._lock:
                # Phase 1: prefer the lowest-numbered idle GPU before preempting anyone.
                target_gpu = self._first_free_gpu()
    
                if target_gpu is None:
                    # Phase 2: all GPUs are busy, so locate the weakest (lowest-priority) lease.
                    target_gpu = self._weakest_lease()
                    if target_gpu is None:
                        # total_gpus <= 0: cluster has no GPUs to lease at all.
                        return False
    
                    victim_lease = self.active_leases[target_gpu]
                    # Use '<=' so equal-priority jobs cannot endlessly preempt each other.
                    if priority <= victim_lease["priority"]:
                        return False
    
                    # Phase 3: record the evicted job before replacing its lease entry.
                    self.preempted.append(victim_lease["job_id"])
    
                self.active_leases[target_gpu] = {
                    "job_id": job_id,
                    "priority": priority,
                }
                return True
    
        def _first_free_gpu(self) -> Optional[int]:
            """Return the lowest GPU id not currently in active_leases, or None."""
            for gpu_id in range(self.total_gpus):
                if gpu_id not in self.active_leases:
                    return gpu_id
            return None
    
        def _weakest_lease(self) -> Optional[int]:
            """Return the GPU id of the lowest-priority lease (lowest GPU id wins ties)."""
            weakest_gpu_id: Optional[int] = None
            weakest_priority: Optional[float] = None
    
            # Iterate GPU ids 0..total_gpus-1 so behavior never depends on dict insertion order.
            for gpu_id in range(self.total_gpus):
                lease = self.active_leases.get(gpu_id)
                if lease is None:
                    continue
                lease_priority = lease["priority"]
                # Strict '<' keeps the first (lowest-numbered) GPU when priorities tie.
                if weakest_priority is None or lease_priority < weakest_priority:
                    weakest_gpu_id = gpu_id
                    weakest_priority = lease_priority
    
            return weakest_gpu_id
    

    ✅ Submit now — all tests should pass.

Intuition & how it works

Imagine managing a small emergency clinic with two treatment beds (GPUs). Bed 0 holds a patient with a serious fracture (priority 40), and Bed 1 holds someone with a mild sprain (priority 10). When a life-threatening trauma case (priority 50) arrives, preemption (interrupting a lower-priority task so a more urgent one can claim its resource) should obviously free up Bed 1—the least urgent case in the room. And if two intake nurses assign beds at the exact same moment, they need to share a single locked clipboard so they do not assign the same bed to two different patients.

A naive first-match allocator fails on both counts. First, scanning active_leases in dictionary insertion order and immediately evicting the first job whose priority happens to be smaller than the newcomer's kicks out the priority-40 fracture in Bed 0 while leaving the priority-10 sprain in Bed 1 untouched. Second, because reading active_leases and writing the new lease are not wrapped in a mutex (a mutual-exclusion lock that lets only one thread execute a protected section at a time), a check-then-act race condition (a concurrency bug where two threads inspect stale state before either writes its update) can happen: if priority-20 and priority-30 arrive simultaneously while priority-10 holds the GPU, both see priority 10, and if priority 20 writes second, it silently overwrites priority 30!

Walk through our corrected logic on Example 1 (total_gpus = 2): 1. request_gpu("train-alpha", 40) acquires _lock, sees GPU 0 is free, and writes {0: train-alpha/40}. 2. request_gpu("eval-beta", 10) acquires _lock, sees GPU 1 is free, and writes {0: train-alpha/40, 1: eval-beta/10}. 3. request_gpu("urgent-gamma", 50) acquires _lock, finds no idle GPU, scans GPU 0 (40) and GPU 1 (10) to pick GPU 1 as the weakest lease, checks 50 > 10, appends "eval-beta" to preempted, and updates GPU 1 to urgent-gamma/50—leaving {0: train-alpha/40, 1: urgent-gamma/50}. 4. request_gpu("peer-delta", 40) compares 40 against the new weakest priority 40 on GPU 0; because 40 <= 40, it returns False without evicting anyone.

Complexity

  • Time: O(G) per request_gpu call, where G = total_gpus. Under the lock, _first_free_gpu scans at most G integer IDs doing O(1) dictionary membership checks, and only when all G GPUs are busy does _weakest_lease do a second O(G) scan to find the minimum priority.
  • Space: O(G + P), where G is total_gpus and P is the cumulative number of preemptions. active_leases stores at most G entries (one dictionary per leased GPU), and preempted appends one job ID per eviction (in production, a worker queue would consume and clear entries from preempted so memory stays O(G)).

Edge cases

  • Zero GPUs (total_gpus == 0): Both _first_free_gpu and _weakest_lease scan an empty range(0) and return None, so request_gpu safely returns False without modifying state.
  • Equal priority (priority == weakest_priority): The guard priority <= victim_lease["priority"] returns False, preventing thrashing (two equal-priority jobs repeatedly evicting each other and wasting time restarting).
  • Ties among multiple weakest leases: Scanning gpu_id from 0 upward with strict < deterministically picks the lowest-numbered GPU every time (as in Example 2 where GPUs 1 and 2 tie at 15), regardless of past dictionary insertion order.
  • High-priority arrival while an idle GPU exists: Phase 1 assigns the idle GPU before Phase 2 ever runs, ensuring no running job is needlessly killed when spare capacity is available.
  • All active leases stronger than the newcomer: request_gpu returns False before touching active_leases or preempted, leaving cluster state completely unchanged.

Common mistakes

  • Asserting only assert manager.request_gpu(...) is True in unit tests: On [train-alpha(40), eval-beta(10)] followed by urgent-gamma(50), a buggy first-match loop also returns True—it just kills the wrong job (train-alpha instead of eval-beta)! Regression tests must assert the exact active_leases mapping and preempted list.
  • Putting the weakest lease in GPU 0 during testing: If you set up [eval-beta(10), train-alpha(40)] instead of [train-alpha(40), eval-beta(10)], the first GPU in dictionary order happens to be the weakest one, so a first-match loop passes by coincidence.
  • Changing > to >=: Allowing equal-priority preemption lets tied jobs steal GPUs from each other in an infinite loop, destroying training progress.
  • Locking only the preemption loop: Leaving the idle-GPU check outside _lock still lets two concurrent threads spot the same free GPU 0 and overwrite each other's lease.
  • Relying on random sleep stress tests for thread safety: On CPython, random threads rarely collide inside a tiny 3-line window; wrapping active_leases in a test helper that pauses writes at a threading.Barrier deterministically exposes missing locks every single run.
  • Dropping evicted jobs on the floor: Overwriting a lease dictionary entry without recording or signaling the evicted job_id leaves orphaned worker processes consuming GPU memory alongside the new job.

Follow-up questions

  • How would you support graceful eviction where an interrupted job gets a 30-second window to save a checkpoint before losing its GPU? Turn preemption into a two-phase state transition (ACTIVE -> DRAINING -> Reassigned). When urgent-gamma preempts eval-beta on GPU 1, mark GPU 1 as DRAINING with deadline = time.monotonic() + 30.0 (using a monotonic clock, a timer that only moves forward and never jumps when system wall-clock time is adjusted), record urgent-gamma as pending_job, send eval-beta a checkpoint signal (such as SIGTERM or an RPC), and exclude DRAINING GPUs from normal victim selection so a second requester does not double-evict eval-beta. As soon as eval-beta reports its checkpoint complete—or a background sweeper sees time.monotonic() >= deadline and force-kills eval-beta—flip the lease to ACTIVE for urgent-gamma and notify urgent-gamma via a callback or Future (and if an even higher-priority job arrives mid-drain, let it either pick another weaker GPU or replace urgent-gamma as pending_job).
  • What happens to allocation latency when the pool scales to thousands of GPUs, and which data structures reduce the lookup cost? Scanning G GPUs linearly inside one global lock takes O(G) time while forcing every concurrent request to wait in single file. Replace the two linear scans with two min-heaps (binary tree structures tucked inside arrays that keep the smallest element at index 0 in O(log G) update time): free_heap storing idle gpu_id integers, and lease_heap storing (priority, gpu_id, version) tuples. Using lazy deletion (incrementing a per-GPU version counter on updates and discarding stale tuples when popped from the heap top) lowers each allocation or preemption to O(log G) time; to remove single-lock contention at massive scale, shard (partition) the GPU pool across independent per-rack or per-pool managers, each with its own lock and heaps.
  • How would you enforce per-tenant fairness caps so no single user can hold more than half of the cluster's GPUs? Include user_id on every request and lease, maintain a user_gpu_counts: Dict[str, int] map under the same _lock, and enforce the integer check 2 * (user_gpu_counts[user_id] + 1) <= self.total_gpus (so with 5 GPUs, one user can hold at most 2). Remember one crucial exception: if all GPUs are busy and user u preempts their own lower-priority job, their net GPU count after eviction stays user_gpu_counts[u], so that swap is still legal even at the cap! In production clusters, hard caps can leave GPUs idle when only one user is active, so schedulers often allow soft "elastic borrowing" above 50% while marking over-quota leases as the very first victims when another user arrives.

Follow-up questions

Similar questions

More Mithril interview questions

All 4 Mithril questions →