Fast Best-Fit Dispatcher for Memory-Bound Workloads
Easy · Software Engineering Fundamentals · Software Engineer · Onsite
Problem Statement
Implement a single-threaded, in-memory Dispatcher that places and resizes memory-bound table workloads across a fleet of fixed-capacity host machines without scanning all hosts or recomputing per-host usage from scratch on every operation.
Placement Policy & Orchestrator Log
Whenever the dispatcher chooses a host for a workload requiring req memory units, it uses best-fit: pick the registered host whose current unused memory satisfies free >= req and is minimal among all eligible hosts, breaking ties by the lexicographically smallest machine_id.
Every placement or cross-host migration appends an event tuple to self.calls: List[tuple] in chronological order:
- ("CreateWorkload", machine_id, table_id) when a new table is placed on machine_id.
- ("MoveWorkload", table_id, from_id, to_id) when an existing table migrates from from_id to to_id during a resize.
Required Methods
add_machine(machine_id: str, capacity: int) -> bool- Register a host with total memory
capacity(initially completely unused). ReturnFalsewithout modifying state ifmachine_idalready exists orcapacity < 0(capacity == 0is valid).
- Register a host with total memory
machine_of(table_id: str) -> Optional[str]- Return the
machine_idcurrently hostingtable_id, orNoneiftable_idis not placed.
- Return the
free_memory(machine_id: str) -> Optional[int]- Return the current unused memory on
machine_id, orNoneifmachine_idis unknown.
- Return the current unused memory on
tables_on_machine(machine_id: str) -> List[str]- Return a sorted list of
table_idstrings currently hosted onmachine_id([]if empty or unknown).
- Return a sorted list of
create_table(table_id: str, memory: int) -> Optional[str]- Return
None(changing nothing and recording no event) iftable_idalready exists,memory < 0, or no host hasfree >= memory. - Otherwise select a host
mvia best-fit, deductmemoryfromm's unused memory, append("CreateWorkload", m, table_id)toself.calls, and returnm.
- Return
resize_table(table_id: str, new_memory: int) -> Optional[str]- Return
None(changing nothing) iftable_idis unknown ornew_memory < 0. - Let
currentbetable_id's current host andold_memorybe its current size:- In-place resize: Because
table_idalready occupiesold_memoryoncurrent, keep it oncurrentwheneverfree_memory(current) + old_memory >= new_memory. Updatecurrent's unused memory andtable_id's footprint, append nothing toself.calls, and returncurrent. - Cross-host migration: Otherwise select a destination host
targetvia best-fit fornew_memory. If no host hasfree >= new_memory, returnNonewhile keepingtable_idoncurrentatold_memory. If found, reclaimold_memoryoncurrent, deductnew_memoryontarget, movetable_idtotarget, append("MoveWorkload", table_id, current, target)toself.calls, and returntarget.
- In-place resize: Because
- Return
Examples
Example 1
d = Dispatcher()
d.add_machine("node_a", 14) # -> True
d.add_machine("node_b", 9) # -> True
d.add_machine("node_c", 9) # -> True
d.add_machine("node_d", 16) # -> True
d.create_table("orders", 7) # -> "node_b" (9 free ties node_c; "node_b" < "node_c")
d.create_table("users", 12) # -> "node_a" (14 free is tightest >= 12)
d.resize_table("orders", 8) # -> "node_b" (2 free + 7 old == 9 >= 8; stays in place)
d.resize_table("orders", 11) # -> "node_d" (1 free + 8 old == 9 < 11; moves to node_d)
[d.free_memory(m) for m in ["node_a", "node_b", "node_c", "node_d"]]
# -> [2, 9, 9, 5]
d.calls
# -> [
# ("CreateWorkload", "node_b", "orders"),
# ("CreateWorkload", "node_a", "users"),
# ("MoveWorkload", "orders", "node_b", "node_d"),
# ]
Walk-through: "orders" initially picks "node_b" (9 free, ahead of "node_c" alphabetically), leaving 2 free on "node_b". Growing "orders" from 7 to 8 reuses its existing 7 units (2 + 7 >= 8), so no migration occurs. Growing "orders" further to 11 exceeds "node_b"'s 9 total capacity, so "orders" migrates to "node_d" (16 free -> 5 free) and frees "node_b" back to 9.
Example 2
d = Dispatcher()
d.add_machine("h1", 6) # -> True
d.add_machine("h2", 4) # -> True
d.create_table("events", 6) # -> "h1" ("h1" now has 0 free)
d.create_table("meta", 0) # -> "h1" (0 free is tightest >= 0)
d.tables_on_machine("h1") # -> ["events", "meta"]
d.resize_table("events", 8) # -> None (no host fits 8; "events" stays 6 on "h1")
d.free_memory("h1") # -> 0
Walk-through: A zero-memory workload is valid and lands on the fullest host ("h1" with 0 free). When "events" asks to grow to 8, neither host can fit 8, so resize_table returns None and leaves "events" untouched on "h1".
Constraints
- Up to
10^4registered hosts and5 * 10^4create_table/resize_tablecalls in a single run. 0 <= capacity, memory, new_memory <= 10^9for valid requests (negative sizes must be rejected cleanly).machine_ofandfree_memorymust run inO(1)average time, and best-fit host search must run inO(log M)comparisons overMhosts rather than scanning every host or summing all placed tables.
Step-by-step walkthrough
Understand the dispatcher's job and invariants
Our single-threaded in-memory dispatcher sits between downstream table requests and an upstream cluster orchestrator:
Downstream request Dispatcher action & upstream call ---------------------------------- ------------------------------------------------------- create_table(table_id, memory) -> Pick a machine with free >= memory; emit ("CreateWorkload", machine_id, table_id) resize_table(table_id, new_memory) -> If current machine can hold new_memory: resize in place (no upstream call — data stays where it is!) -> Otherwise pick a new machine with free >= new_memory; emit ("MoveWorkload", table_id, from_id, to_id)Three rules govern correctness: 1. Never move unnecessarily: migrating a table across machines copies gigabytes of memory over the network, so a resize must stay on its current machine whenever
free_on_current + old_memory >= new_memory. 2. All-or-nothing rejection: if an ID is invalid, memory is negative, or no machine has enough free memory, returnNonewithout changing any state or emitting any upstream call. 3. Deterministic placement: when choosing a machine, use best-fit — pick the machine with the smallestfree_memorythat is still>= memory, breaking ties by the lexicographically smallestmachine_id.Analyze why the naive implementation takes O(M * T) time
A typical first-draft dispatcher stores only three minimal dictionaries (
capacity[m],memory[t], andplacement[t] = m) and recomputes everything else from scratch on every call:def free_memory(self, machine_id): used = 0 for table_id in self.placement: # scans all T tables! if self.placement[table_id] == machine_id: used += self.memory[table_id] return self.capacity[machine_id] - used def best_fit(self, memory): best = None for machine_id in self.capacity: # scans all M machines! candidate = (self.free_memory(machine_id), machine_id) if candidate[0] >= memory and (best is None or candidate < best): best = candidate return None if best is None else best[1]With
Mmachines andTtables,free_memoryloops over allTtables (O(T)), andbest_fitcallsfree_memoryonce for each of theMmachines —O(M * T)time per request. WithM = 10,000machines andT = 100,000tables, a singlecreate_tableperforms10^9loop iterations!Notice that there are two separate bottlenecks, and fixing only the first is still slow: 1. Repeatedly summing free memory (
O(T)): solved by cachingfree[machine_id]and updating it by+/- deltawhenever a table is placed, resized, or moved (O(1)). 2. Linearly scanning all machines (O(M)): even withO(1)free[machine_id], scanning 10,000 machines across 20,000 requests performs2 * 10^8checks. We need an ordered index over free memory.Compare scheduling policies: first-fit, best-fit, and worst-fit
Before picking the ordered index, let's compare the three classic bin-packing policies:
Policy Rule Strength Trade-off --------- --------------------------------------- ----------------------------- -------------------------------------- First-fit First machine (by ID) with free >= req Fast with a segment tree Small tables carve up big empty machines Best-fit Smallest free memory with free >= req Saves big machines for big jobs Tight packing leaves less room to grow Worst-fit Largest free memory Leaves headroom for growth Consumes the largest machines immediatelyTo see why best-fit reduces memory fragmentation (a state where total free RAM across the cluster exceeds a request, yet no single machine has a big enough contiguous block), trace two machines
a(capacity10) andb(capacity6) receivingt1(size5) followed byt2(size10):Best-fit: 1. t1 (size 5) -> picks b (free 6 is tightest >= 5). Remaining free: a = 10, b = 1 2. t2 (size 10) -> picks a (free 10 >= 10). Both tables succeed! Worst-fit: 1. t1 (size 5) -> picks a (free 10 is largest). Remaining free: a = 5, b = 6 2. t2 (size 10) -> REJECTED! Total free is 11, yet neither machine has 10 free.Best-fit preserves large contiguous blocks for large tables. Its downside is that tightly packed tables have less spare room on their current host if they later grow, making
MoveWorkloadslightly more frequent on big growth spikes.Design one fast index per question
Every operation the dispatcher performs asks one of four concrete questions. We pair each question with the exact data structure that answers it directly:
Question Data structure Lookup cost ------------------------------------------------ ------------------------------------ ----------- Which machine holds table t? How big is t? table_machine[t], table_memory[t] O(1) avg How much free memory does machine m have? free[m] (updated incrementally) O(1) avg Which tables currently sit on machine m? tables_on[m] (set of table IDs) O(1) update Which machine has the smallest free >= memory? by_free: sorted [(free, machine_id)] O(log M)Look closely at how binary search (repeatedly halving a sorted array to find a boundary in
O(log M)comparisons) answers both best-fit and tie-breaking in a single call onby_free:by_free = [(1, "d"), (6, "b"), (6, "c"), (10, "a")] Query: _best_fit(memory = 5) Search key: (5, "") <-- "" is smaller than every non-empty string ID bisect_left lands at index 1 -> (6, "b"), beating (6, "c") on tie-break and (10, "a") on fit! Query: _best_fit(memory = 6) Search key: (6, "") Since (6, "") < (6, "b") < (6, "c"), bisect_left still lands on (6, "b")!One honest engineering note on Python's
list:bisect_leftfinds the index inO(log M)comparisons, whiledel by_free[i]andbisect.insortshift elements in the underlying C pointer array (O(M)worst-case shifts, executed as a single fastmemmovethat easily handlesM = 10,000in milliseconds). In C++ (std::set) or Java (TreeSet), a balanced binary search tree (a tree that keeps its height atO(log M)on every insert and delete) makes both lookup and update strictlyO(log M).Keep free memory synchronized through one helper
Whenever you store the same fact in two places (
self.freeandself.by_free), the #1 bug risk is updating one and forgetting the other. We prevent that by routing every free-memory change through a single private helper_set_free:def _set_free(self, machine_id: str, new_free: int) -> None: """Update `machine_id`'s free memory in both `self.free` and `self.by_free` atomically.""" old_pair = (self.free[machine_id], machine_id) old_index = bisect.bisect_left(self.by_free, old_pair) del self.by_free[old_index] self.free[machine_id] = new_free bisect.insort(self.by_free, (new_free, machine_id)) def _best_fit(self, memory: int) -> Optional[str]: """Return the machine with the smallest free memory >= `memory` (ties broken by id).""" # Because "" sorts lexicographically before every string id, bisect_left lands on the # first pair with free >= memory, and on the smallest machine_id among ties. index = bisect.bisect_left(self.by_free, (memory, "")) if index == len(self.by_free): return None return self.by_free[index][1] def add_machine(self, machine_id: str, capacity: int) -> bool: if machine_id in self.capacity or capacity < 0: return False self.capacity[machine_id] = capacity self.free[machine_id] = capacity self.tables_on[machine_id] = set() bisect.insort(self.by_free, (capacity, machine_id)) return TrueImplement create_table and resize_table safely
Now let's write
create_tableandresize_table, paying attention to two subtle points inresize_table:- Include the table's own old memory when checking the current host: if machine
"b"has2units free and"t1"already occupies6units on"b","t1"can grow up toavailable_here = 2 + 6 = 8units right where it sits! Checkingnew_memory <= self.free[current]alone would mistakenly evict"t1"when resizing from6to7(or even from6to5!). - Why
_best_fit(new_memory)never pickscurrentduring a move: we only enter the move branch whenavailable_here < new_memory. Sinceold_memory >= 0, we haveself.free[current] <= available_here < new_memory. Becausecurrentstill holds its oldfreevalue insideself.by_freeduring the search,_best_fit(new_memory)only inspects machines withfree >= new_memoryand therefore skipscurrentautomatically.
def create_table(self, table_id: str, memory: int) -> Optional[str]: """Place a new table using best-fit, or return None without mutating state.""" # Validate inputs and capacity before modifying any index if table_id in self.table_machine or memory < 0: return None machine_id = self._best_fit(memory) if machine_id is None: return None self.table_memory[table_id] = memory self.table_machine[table_id] = machine_id self.tables_on[machine_id].add(table_id) self._set_free(machine_id, self.free[machine_id] - memory) self.calls.append(("CreateWorkload", machine_id, table_id)) return machine_id def resize_table(self, table_id: str, new_memory: int) -> Optional[str]: """Resize in place if the current host has room; otherwise migrate via best-fit.""" if table_id not in self.table_machine or new_memory < 0: return None current = self.table_machine[table_id] old_memory = self.table_memory[table_id] # Include `old_memory` because resizing in place reclaims the table's existing space available_here = self.free[current] + old_memory if new_memory <= available_here: self._set_free(current, available_here - new_memory) self.table_memory[table_id] = new_memory return current # Here available_here < new_memory, and since old_memory >= 0 we also know # self.free[current] < new_memory, so _best_fit(new_memory) can never pick `current`. target = self._best_fit(new_memory) if target is None: return None # Release the old footprint on `current` and claim `new_memory` on `target` self._set_free(current, available_here) self.tables_on[current].discard(table_id) self._set_free(target, self.free[target] - new_memory) self.tables_on[target].add(table_id) self.table_machine[table_id] = target self.table_memory[table_id] = new_memory self.calls.append(("MoveWorkload", table_id, current, target)) return target- Include the table's own old memory when checking the current host: if machine
Trace Sample 1 and assemble the full solution
Let's trace
Example 1across"node_a"(14),"node_b"(9),"node_c"(9), and"node_d"(16):Start: by_free = [(9, "node_b"), (9, "node_c"), (14, "node_a"), (16, "node_d")] 1. create_table("orders", 7): - bisect_left((7, "")) -> (9, "node_b") (ties node_c at 9, wins on "node_b" < "node_c") - node_b's free: 9 -> 2; by_free = [(2, "node_b"), (9, "node_c"), (14, "node_a"), (16, "node_d")] - calls: [("CreateWorkload", "node_b", "orders")] 2. create_table("users", 12): - bisect_left((12, "")) -> (14, "node_a") - node_a's free: 14 -> 2; by_free = [(2, "node_a"), (2, "node_b"), (9, "node_c"), (16, "node_d")] - calls: [..., ("CreateWorkload", "node_a", "users")] 3. resize_table("orders", 8): - current = "node_b", available_here = free["node_b"] + 7 = 2 + 7 = 9 >= 8 (fits in place!) - node_b's free: 2 -> 1; no upstream call emitted 4. resize_table("orders", 11): - current = "node_b", available_here = 1 + 8 = 9 < 11 (cannot stay on "node_b"!) - bisect_left((11, "")) on [(1, "node_b"), (2, "node_a"), (9, "node_c"), (16, "node_d")] -> (16, "node_d") - node_b's free: 1 -> 9; node_d's free: 16 -> 5 - by_free = [(2, "node_a"), (5, "node_d"), (9, "node_b"), (9, "node_c")] - calls: [..., ("MoveWorkload", "orders", "node_b", "node_d")]Here is the complete
Dispatcherimplementation:from typing import Dict, List, Optional, Set, Tuple import bisect class Dispatcher: """Places tables on machines using best-fit and keeps every lookup index synchronized. `calls` records upstream orchestrator calls in chronological order: ("CreateWorkload", machine_id, table_id) and ("MoveWorkload", table_id, from_id, to_id). """ def __init__(self): # capacity: fixed total memory per machine, e.g. {"a": 10, "b": 8} self.capacity: Dict[str, int] = {} # free: current unused memory per machine, maintained incrementally in O(1) self.free: Dict[str, int] = {} # tables_on: reverse mapping {machine_id: {table_ids_placed_on_it}} self.tables_on: Dict[str, Set[str]] = {} # table_memory: current memory footprint per table, e.g. {"t1": 6} self.table_memory: Dict[str, int] = {} # table_machine: current host machine per table, e.g. {"t1": "b"} self.table_machine: Dict[str, str] = {} # by_free: sorted list of (free_memory, machine_id) pairs, e.g. [(2, "b"), (10, "a")] self.by_free: List[Tuple[int, str]] = [] # calls: audit log of upstream orchestrator actions self.calls: List[tuple] = [] # ----- O(1) / direct lookups ----- def machine_of(self, table_id: str) -> Optional[str]: return self.table_machine.get(table_id) def free_memory(self, machine_id: str) -> Optional[int]: return self.free.get(machine_id) def tables_on_machine(self, machine_id: str) -> List[str]: return sorted(self.tables_on.get(machine_id, set())) # ----- free-memory index maintenance ----- def _set_free(self, machine_id: str, new_free: int) -> None: """Update `machine_id`'s free memory in both `self.free` and `self.by_free` atomically.""" old_pair = (self.free[machine_id], machine_id) old_index = bisect.bisect_left(self.by_free, old_pair) del self.by_free[old_index] self.free[machine_id] = new_free bisect.insort(self.by_free, (new_free, machine_id)) def _best_fit(self, memory: int) -> Optional[str]: """Return the machine with the smallest free memory >= `memory` (ties broken by id).""" # Because "" sorts lexicographically before every string id, bisect_left lands on the # first pair with free >= memory, and on the smallest machine_id among ties. index = bisect.bisect_left(self.by_free, (memory, "")) if index == len(self.by_free): return None return self.by_free[index][1] # ----- public scheduling API ----- def add_machine(self, machine_id: str, capacity: int) -> bool: if machine_id in self.capacity or capacity < 0: return False self.capacity[machine_id] = capacity self.free[machine_id] = capacity self.tables_on[machine_id] = set() bisect.insort(self.by_free, (capacity, machine_id)) return True def create_table(self, table_id: str, memory: int) -> Optional[str]: """Place a new table using best-fit, or return None without mutating state.""" # Validate inputs and capacity before modifying any index if table_id in self.table_machine or memory < 0: return None machine_id = self._best_fit(memory) if machine_id is None: return None self.table_memory[table_id] = memory self.table_machine[table_id] = machine_id self.tables_on[machine_id].add(table_id) self._set_free(machine_id, self.free[machine_id] - memory) self.calls.append(("CreateWorkload", machine_id, table_id)) return machine_id def resize_table(self, table_id: str, new_memory: int) -> Optional[str]: """Resize in place if the current host has room; otherwise migrate via best-fit.""" if table_id not in self.table_machine or new_memory < 0: return None current = self.table_machine[table_id] old_memory = self.table_memory[table_id] # Include `old_memory` because resizing in place reclaims the table's existing space available_here = self.free[current] + old_memory if new_memory <= available_here: self._set_free(current, available_here - new_memory) self.table_memory[table_id] = new_memory return current # Here available_here < new_memory, and since old_memory >= 0 we also know # self.free[current] < new_memory, so _best_fit(new_memory) can never pick `current`. target = self._best_fit(new_memory) if target is None: return None # Release the old footprint on `current` and claim `new_memory` on `target` self._set_free(current, available_here) self.tables_on[current].discard(table_id) self._set_free(target, self.free[target] - new_memory) self.tables_on[target].add(table_id) self.table_machine[table_id] = target self.table_memory[table_id] = new_memory self.calls.append(("MoveWorkload", table_id, current, target)) return target✅ Submit now — all tests should pass.
Intuition & how it works
Picture a parking-garage attendant assigning delivery vans of different heights to garages with fixed ceiling clearances. A naive attendant walks through every single garage, counts every van currently parked inside to figure out how much space is left, and repeats that entire walk from scratch whenever a new van arrives. Instead, a smart attendant keeps a live digital board listing each garage's remaining space sorted from smallest to largest, plus a quick index card for each van showing which garage it is parked in.
The naive dispatcher falls into two separate performance traps: it sums all T tables to recompute a machine's free memory (O(T)), and it scans all M machines to pick a host, costing O(M * T) work per request (up to a billion checks when M = 10,000 and T = 100,000). By maintaining free[machine_id] incrementally on each edit and keeping (free_memory, machine_id) pairs in a sorted list by_free, we can use binary search (repeatedly halving the sorted list to jump straight to the boundary in O(log M) comparisons) to run best-fit — choosing the machine with the tightest sufficient space so big empty machines stay available for big tables.
Trace a quick 3-step slice of Example 1 with hosts node_a (14 free), node_b (9 free), and node_d (16 free), so by_free = [(9, "node_b"), (14, "node_a"), (16, "node_d")]:
1. create_table("orders", 7): Binary search for (7, "") lands on (9, "node_b"). "orders" goes to "node_b", updating "node_b" to 2 free (by_free = [(2, "node_b"), (14, "node_a"), (16, "node_d")]).
2. resize_table("orders", 8): On "node_b", "orders" can use "node_b"'s 2 free units plus its own 7 existing units (available_here = 9 >= 8), so "orders" grows in place on "node_b" (1 free) with zero data migration.
3. resize_table("orders", 11): If "node_a" meanwhile dropped to 2 free ("users" took 12), available_here = 1 + 8 = 9 < 11 on "node_b", so "orders" must move. Binary search for (11, "") skips (1, "node_b") and (2, "node_a"), picks (16, "node_d"), restores "node_b" to 9 free, and updates "node_d" to 5 free.
Complexity
Let M be the number of registered machines and T be the number of placed tables.
- Naive baseline:
O(M * T)percreate_tableorresize_table, because recomputing one machine's free memory scans allTentries inplacement, and choosing a destination repeats that scan across allMmachines. machine_ofandfree_memory:O(1)average time, because each reads a single key from a hash map (table_machineorfree)._best_fit:O(log M)time, becausebisect_lefthalves the sortedM-elementby_freelist at each step without inspecting non-matching machines._set_free,add_machine,create_table, andresize_table:O(log M)comparisons plusO(M)worst-case pointer shifts in Python'slist(delandbisect.insortshift trailing pointers via a fast Cmemmove). Replacingby_freewith a balanced binary search tree (a self-balancing tree such as C++std::set, JavaTreeSet, or Pythonsortedcontainers.SortedListthat keeps tree height logarithmic) makes both search and update strictlyO(log M).tables_on_machine:O(k log k)time, wherekis the number of tables currently on that machine, to sort thosekIDs for output (O(1)to read the underlyingSet[str]).- Space:
O(M + T), because each machine appears once incapacity,free,tables_on, andby_free(4Mentries), and each table appears once intable_memory,table_machine, and one machine'stables_onset (3Tentries), plus one tuple per upstream call incalls.
Edge cases
- Unknown
table_idinresize_table: ReturnsNoneimmediately without changing any dictionary or emitting an upstream call. - Downsizing or same-size resize (
new_memory <= old_memory): Sincefree[current] >= 0,available_here = free[current] + old_memoryis always>= new_memory, so shrinking always succeeds in place and never moves the table. - Exact-fit placement (
free == memory):bisect_left(by_free, (memory, ""))includes exact matches because(memory, "") <= (memory, machine_id)for every stringmachine_id. - Zero-memory tables (
memory == 0): Valid (0 >= 0), fits even on a machine with0free memory, and goes to the fullest machine (ties broken by smallest ID). - Failed
create_tableorresize_tablewhen no machine fits: ReturnsNoneand leaves the cluster completely unchanged — a failedresize_tablepreserves the table's old host and old memory footprint. - Duplicate IDs and negative capacities/sizes: Rejected cleanly (
Falseforadd_machine,Noneforcreate_table/resize_table). - Memory fragmentation: Even if total cluster free memory exceeds
new_memory(say two machines each have3free and a table requests5), no single machine can host it, so the dispatcher rightly returnsNoneunless compaction/rebalancing is added.
Common mistakes
- Forgetting to add back
old_memoryduringresize_table: Checkingself.free[current] >= new_memoryinstead ofself.free[current] + old_memory >= new_memorytreats the table's own existing memory as unavailable, triggering unnecessary moves or false failures. - Updating
self.freein one branch without updatingself.by_free: Once the dict and sorted list disagree,bisect_leftlooks up the wrong old key and deletes a neighbor's entry. Routing every update through_set_freeeliminates this class of bug. - Using a min-heap or max-heap for best-fit: A heap (a tree structure that only exposes its global minimum or maximum in
O(1)) cannot efficiently find the smallest value greater than or equal to an arbitrary thresholdx— that query requires a sorted array or search tree. - Mutating state before checking whether
targetexists: Releasing memory oncurrentbefore confirming_best_fit(new_memory)succeeded would corruptcurrentwhenever a resize cannot fit anywhere. - Claiming Python
bisect.insortis strictlyO(log M)total time: Binary search isO(log M)comparisons, whereas inserting/deleting inside a contiguous array shiftsO(M)pointers in the worst case; stating both the practical speed ofmemmoveand the balanced-BST upgrade shows strong engineering precision. - Moving a table on shrink just because another machine is "tighter": Moving workloads copies state over the network, so in-place fit always takes priority over re-optimizing bin packing.
Follow-up questions
- How would you gracefully drain a host machine ahead of scheduled maintenance? Add the machine ID to a
drainingset and immediately remove its(free, machine_id)tuple fromby_freeso_best_fitnever schedules new or migrating workloads onto it (and have_set_freeskipby_freeupdates for any ID indraining). Then iterate over a copy oftables_on[machine_id]sorted from largesttable_memoryto smallest — placing big tables first avoids filling the biggest cluster gaps with tiny tables — and migrate each one via_best_fit. If any table returnsNone, abort or report the unmovable tables so an operator knows the drain could not complete. - Migrating large tables across the network is expensive—what placement or eviction heuristics reduce migration volume? First, reserve growth headroom during initial placement: instead of packing a machine to 100%, have
create_tableprefer machines wherefree >= memory * 1.2(falling back to strictfree >= memoryonly when needed) so tables can absorb routine 20% growth in place. Second, when a50 GBtable on machinemneeds2 GBmore andmalso hosts a3 GBtable, evicting the3 GBneighbor costs17xless network transfer than moving the50 GBtable! Becausetables_on[m]already tracks local neighbors, the dispatcher can compare both options. - How must memory accounting change if MoveWorkload runs asynchronously over several minutes instead of completing instantaneously? While a table is copying from
sourcetotarget, its memory must remain reserved on both machines — releasingsourceearly risks another table overwriting memory the live workload still uses, and not reservingtargetearly risks two concurrent moves oversubscribingtarget. Introduce apending_movesstate:resize_tablesubtractsnew_memoryontargetimmediately, keepsold_memorylocked onsource, and exposescomplete_move(table_id)(which releasesold_memoryonsourceand switchestable_machine) plusfail_move(table_id)(which refundsnew_memoryontarget).
Alternative approaches
- Balanced binary search tree for strict
O(log M)best-fit: Keying a red-black tree or AVL tree by(free_memory, machine_id)supportslower_bound((memory, "")), insert, and delete in guaranteedO(log M)worst-case time without array shifting. - Segment tree for
O(log M)first-fit: A segment tree (a complete binary tree over a fixed array of machines where each internal node stores the maximumfree_memoryin its subtree) can find the first machine (by index) withfree >= memoryby walking down one root-to-leaf path inO(log M)time and updating a machine's free memory along the same path inO(log M)time using only plain Python lists. - Power-of-two size buckets (segregated free lists): Group machines into buckets by
floor(log2(free_memory))([1],[2..3],[4..7],[8..15], ...), just like memory allocators (malloc) do. Any machine in a bucket strictly abovememory's bucket is guaranteed to fit inO(1)time, trading exact best-fit tightness forO(1)bucket updates.
Follow-up questions
- How would you gracefully drain a host machine ahead of scheduled maintenance?
- Migrating large tables across the network is expensive—what placement or eviction heuristics reduce migration volume?
- How must memory accounting change if MoveWorkload runs asynchronously over several minutes instead of completing instantaneously?
Similar questions
- Command-Pattern Undo and Redo Engine for Spreadsheets
- Resilient HTTP Client with Retries and Idempotency
- Reusable Database Connection Pool
- Calculate Working Days Between Dates
- Thread-Safe On-Demand Connection Pool
- Sharded Multi-Tenant Full-Text Search Service
More Airtable interview questions
- Command-Pattern Undo and Redo Engine for Spreadsheets Medium
- Calculate Working Days Between Dates Medium
- Deterministic JSON Wire Format for Cyclic Graphs Hard Pro
- Schema-Grounded Formula Assistant for Collaborative Tables Medium Pro
- Thread-Safe On-Demand Connection Pool Medium Pro
- Sharded Multi-Tenant Full-Text Search Service Medium Pro
- Idempotent Asynchronous Job Execution API Medium Pro
- Workspace Metric Drop Triage and Recommendation Experiment Easy Pro
- Resilient HTTP Client with Retries and Idempotency Medium Pro
- Breadth-First Object Graph Serialization Medium Pro