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
- Public state:
self.active_leases: dictionary mappinggpu_id(int) to{"job_id": job_id, "priority": priority}for every currently leased GPU. All GPUs start idle ({}).self.preempted: list ofjob_idvalues evicted due to preemption, recorded in chronological order ([]initially).
- Idle capacity first: When one or more GPUs in
0 .. total_gpus - 1are not inactive_leases, assign the lowest-numbered idle GPU tojob_idand returnTruewithout preempting any running job. - Weakest-victim preemption: When every GPU is busy (and
total_gpus > 0), find the active lease with the lowestpriority, breaking ties by selecting the lowestgpu_id.- If the incoming
priorityis strictly greater (>) than that weakest lease's priority, append the displaced job'sjob_idtoself.preempted, assign thatgpu_idto the incoming job, and returnTrue. - If
total_gpus <= 0orpriorityis less than or equal to (<=) the weakest active priority, leaveactive_leasesandpreemptedunchanged and returnFalse.
- If the incoming
- Thread safety: Concurrent
request_gpucalls 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,000job_idcan be any Python value (such asstrorint).priorityis a finiteintorfloat.request_gpumust be safe under concurrent multi-threaded execution.- Target per-request time complexity is
O(total_gpus)withO(total_gpus + P)space acrossPcumulative preemptions.
Step-by-step walkthrough
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.
Catalog all three flaws in the naive allocator
Inspecting that prototype pattern surfaces three distinct defects:
- 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-50job evicts a priority-40job on GPU0while a priority-10job sits untouched on GPU1. - 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 writingself.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. - Silent eviction: Overwriting
self.active_leases[gpu_id]discards the displaced job's identifier instead of appending it toself.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.- Evicting the first beatable lease instead of the weakest lease: Returning immediately on the first GPU where
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):
- Idle GPUs always come first: Scan GPU IDs
0, 1, ..., total_gpus - 1and assign the lowest-numbered idle GPU if any is free. Never preempt a running job while hardware sits idle. - Otherwise compare against the single weakest lease: Scan GPU IDs
0, 1, ..., total_gpus - 1to find the active lease with the minimumpriority(breaking ties by choosing the lowestgpu_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! - Record every preemption atomically: Wrap the entire read-decide-write sequence in
with self._lock:and append the evictedjob_idtoself.preemptedright before replacing its dictionary entry.
- Idle GPUs always come first: Scan GPU IDs
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 GPUs1and2tie at priority15(as in Example 2), lower-numbered GPU1stays 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_idAssemble the thread-safe request_gpu method
Now combine both helpers inside
with self._lock:. Notice the edge casetotal_gpus == 0:_first_free_gpu()returnsNoneand_weakest_lease()also returnsNone, so checkingif target_gpu is None: return Falsecleanly 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 TrueDesign unit tests that deterministically catch both regressions
Naive unit tests easily miss both bugs unless you structure assertions carefully:
- 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 assertrequest_gpu(...) is True—a buggy first-match loop also returnsTrue! Assert bothactive_leases({0: train-alpha, 1: urgent-gamma}) andpreempted(["eval-beta"]). - Catching equal-priority and tie-breaking boundaries: Assert that equal priority (
40vs40) returnsFalsewithout mutatingactive_leases; assert that idle GPUs are assigned before preempting; and assert deterministic tie-breaking on lowestgpu_id(Example 2: GPUs1and2tied at15evict GPU1first). - Deterministically catching missing locks: Spawning random threads rarely hits a 3-line Python race window because of CPython's bytecode scheduling. Instead, inject a
dictsubclass whose__setitem__pauses briefly at a 2-threadthreading.Barrier(2, timeout=0.2). Withoutself._lock, both threads compute their target GPU before writing, meet at the barrier, and overwrite each other; withself._lock, Thread 1 enters alone, times out cleanly after0.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- Catching wrong-victim selection: Use at least 2 GPUs where an earlier GPU holds a medium priority (
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)perrequest_gpucall, whereG = total_gpus. Under the lock,_first_free_gpuscans at mostGinteger IDs doingO(1)dictionary membership checks, and only when allGGPUs are busy does_weakest_leasedo a secondO(G)scan to find the minimum priority. - Space:
O(G + P), whereGistotal_gpusandPis the cumulative number of preemptions.active_leasesstores at mostGentries (one dictionary per leased GPU), andpreemptedappends one job ID per eviction (in production, a worker queue would consume and clear entries frompreemptedso memory staysO(G)).
Edge cases
- Zero GPUs (
total_gpus == 0): Both_first_free_gpuand_weakest_leasescan an emptyrange(0)and returnNone, sorequest_gpusafely returnsFalsewithout modifying state. - Equal priority (
priority == weakest_priority): The guardpriority <= victim_lease["priority"]returnsFalse, preventing thrashing (two equal-priority jobs repeatedly evicting each other and wasting time restarting). - Ties among multiple weakest leases: Scanning
gpu_idfrom0upward with strict<deterministically picks the lowest-numbered GPU every time (as in Example 2 where GPUs1and2tie at15), 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_gpureturnsFalsebefore touchingactive_leasesorpreempted, leaving cluster state completely unchanged.
Common mistakes
- Asserting only
assert manager.request_gpu(...) is Truein unit tests: On[train-alpha(40), eval-beta(10)]followed byurgent-gamma(50), a buggy first-match loop also returnsTrue—it just kills the wrong job (train-alphainstead ofeval-beta)! Regression tests must assert the exactactive_leasesmapping andpreemptedlist. - 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
_lockstill lets two concurrent threads spot the same free GPU0and overwrite each other's lease. - Relying on random
sleepstress tests for thread safety: On CPython, random threads rarely collide inside a tiny 3-line window; wrappingactive_leasesin a test helper that pauses writes at athreading.Barrierdeterministically exposes missing locks every single run. - Dropping evicted jobs on the floor: Overwriting a lease dictionary entry without recording or signaling the evicted
job_idleaves 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). Whenurgent-gammapreemptseval-betaon GPU1, mark GPU1asDRAININGwithdeadline = time.monotonic() + 30.0(using a monotonic clock, a timer that only moves forward and never jumps when system wall-clock time is adjusted), recordurgent-gammaaspending_job, sendeval-betaa checkpoint signal (such asSIGTERMor an RPC), and excludeDRAININGGPUs from normal victim selection so a second requester does not double-evicteval-beta. As soon aseval-betareports its checkpoint complete—or a background sweeper seestime.monotonic() >= deadlineand force-killseval-beta—flip the lease toACTIVEforurgent-gammaand notifyurgent-gammavia a callback orFuture(and if an even higher-priority job arrives mid-drain, let it either pick another weaker GPU or replaceurgent-gammaaspending_job). - What happens to allocation latency when the pool scales to thousands of GPUs, and which data structures reduce the lookup cost? Scanning
GGPUs linearly inside one global lock takesO(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 index0inO(log G)update time):free_heapstoring idlegpu_idintegers, andlease_heapstoring(priority, gpu_id, version)tuples. Using lazy deletion (incrementing a per-GPUversioncounter on updates and discarding stale tuples when popped from the heap top) lowers each allocation or preemption toO(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_idon every request and lease, maintain auser_gpu_counts: Dict[str, int]map under the same_lock, and enforce the integer check2 * (user_gpu_counts[user_id] + 1) <= self.total_gpus(so with5GPUs, one user can hold at most2). Remember one crucial exception: if all GPUs are busy and userupreempts their own lower-priority job, their net GPU count after eviction staysuser_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
- How would you support graceful eviction where an interrupted job gets a 30-second window to save a checkpoint before losing its GPU?
- What happens to allocation latency when the pool scales to thousands of GPUs, and which data structures reduce the lookup cost?
- How would you enforce per-tenant fairness caps so no single user can hold more than half of the cluster's GPUs?
Similar questions
- Hybrid-Cloud GPU Cluster Scheduling Service
- Safe Transition Path to Disarm State
- Lower Flat Programs to Triad IR
- Dynamic Dynasty Succession Without an Initial Monarch
- DOM Button Click Listener and Event Target
- Catalog Search, Filtering, and Pagination