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). Return False without modifying state if machine_id already exists or capacity < 0 (capacity == 0 is valid).
  • machine_of(table_id: str) -> Optional[str]
    • Return the machine_id currently hosting table_id, or None if table_id is not placed.
  • free_memory(machine_id: str) -> Optional[int]
    • Return the current unused memory on machine_id, or None if machine_id is unknown.
  • tables_on_machine(machine_id: str) -> List[str]
    • Return a sorted list of table_id strings currently hosted on machine_id ([] if empty or unknown).
  • create_table(table_id: str, memory: int) -> Optional[str]
    • Return None (changing nothing and recording no event) if table_id already exists, memory < 0, or no host has free >= memory.
    • Otherwise select a host m via best-fit, deduct memory from m's unused memory, append ("CreateWorkload", m, table_id) to self.calls, and return m.
  • resize_table(table_id: str, new_memory: int) -> Optional[str]
    • Return None (changing nothing) if table_id is unknown or new_memory < 0.
    • Let current be table_id's current host and old_memory be its current size:
      1. In-place resize: Because table_id already occupies old_memory on current, keep it on current whenever free_memory(current) + old_memory >= new_memory. Update current's unused memory and table_id's footprint, append nothing to self.calls, and return current.
      2. Cross-host migration: Otherwise select a destination host target via best-fit for new_memory. If no host has free >= new_memory, return None while keeping table_id on current at old_memory. If found, reclaim old_memory on current, deduct new_memory on target, move table_id to target, append ("MoveWorkload", table_id, current, target) to self.calls, and return target.

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^4 registered hosts and 5 * 10^4 create_table / resize_table calls in a single run.
  • 0 <= capacity, memory, new_memory <= 10^9 for valid requests (negative sizes must be rejected cleanly).
  • machine_of and free_memory must run in O(1) average time, and best-fit host search must run in O(log M) comparisons over M hosts rather than scanning every host or summing all placed tables.

Step-by-step walkthrough

  1. 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, return None without changing any state or emitting any upstream call. 3. Deterministic placement: when choosing a machine, use best-fit — pick the machine with the smallest free_memory that is still >= memory, breaking ties by the lexicographically smallest machine_id.

  2. Analyze why the naive implementation takes O(M * T) time

    A typical first-draft dispatcher stores only three minimal dictionaries (capacity[m], memory[t], and placement[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 M machines and T tables, free_memory loops over all T tables (O(T)), and best_fit calls free_memory once for each of the M machines — O(M * T) time per request. With M = 10,000 machines and T = 100,000 tables, a single create_table performs 10^9 loop 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 caching free[machine_id] and updating it by +/- delta whenever a table is placed, resized, or moved (O(1)). 2. Linearly scanning all machines (O(M)): even with O(1) free[machine_id], scanning 10,000 machines across 20,000 requests performs 2 * 10^8 checks. We need an ordered index over free memory.

  3. 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 immediately
    

    To 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 (capacity 10) and b (capacity 6) receiving t1 (size 5) followed by t2 (size 10):

    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 MoveWorkload slightly more frequent on big growth spikes.

  4. 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 on by_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_left finds the index in O(log M) comparisons, while del by_free[i] and bisect.insort shift elements in the underlying C pointer array (O(M) worst-case shifts, executed as a single fast memmove that easily handles M = 10,000 in milliseconds). In C++ (std::set) or Java (TreeSet), a balanced binary search tree (a tree that keeps its height at O(log M) on every insert and delete) makes both lookup and update strictly O(log M).

  5. Keep free memory synchronized through one helper

    Whenever you store the same fact in two places (self.free and self.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 True
    
  6. Implement create_table and resize_table safely

    Now let's write create_table and resize_table, paying attention to two subtle points in resize_table:

    1. Include the table's own old memory when checking the current host: if machine "b" has 2 units free and "t1" already occupies 6 units on "b", "t1" can grow up to available_here = 2 + 6 = 8 units right where it sits! Checking new_memory <= self.free[current] alone would mistakenly evict "t1" when resizing from 6 to 7 (or even from 6 to 5!).
    2. Why _best_fit(new_memory) never picks current during a move: we only enter the move branch when available_here < new_memory. Since old_memory >= 0, we have self.free[current] <= available_here < new_memory. Because current still holds its old free value inside self.by_free during the search, _best_fit(new_memory) only inspects machines with free >= new_memory and therefore skips current automatically.
    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
    
  7. Trace Sample 1 and assemble the full solution

    Let's trace Example 1 across "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 Dispatcher implementation:

    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) per create_table or resize_table, because recomputing one machine's free memory scans all T entries in placement, and choosing a destination repeats that scan across all M machines.
  • machine_of and free_memory: O(1) average time, because each reads a single key from a hash map (table_machine or free).
  • _best_fit: O(log M) time, because bisect_left halves the sorted M-element by_free list at each step without inspecting non-matching machines.
  • _set_free, add_machine, create_table, and resize_table: O(log M) comparisons plus O(M) worst-case pointer shifts in Python's list (del and bisect.insort shift trailing pointers via a fast C memmove). Replacing by_free with a balanced binary search tree (a self-balancing tree such as C++ std::set, Java TreeSet, or Python sortedcontainers.SortedList that keeps tree height logarithmic) makes both search and update strictly O(log M).
  • tables_on_machine: O(k log k) time, where k is the number of tables currently on that machine, to sort those k IDs for output (O(1) to read the underlying Set[str]).
  • Space: O(M + T), because each machine appears once in capacity, free, tables_on, and by_free (4M entries), and each table appears once in table_memory, table_machine, and one machine's tables_on set (3T entries), plus one tuple per upstream call in calls.

Edge cases

  • Unknown table_id in resize_table: Returns None immediately without changing any dictionary or emitting an upstream call.
  • Downsizing or same-size resize (new_memory <= old_memory): Since free[current] >= 0, available_here = free[current] + old_memory is 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 string machine_id.
  • Zero-memory tables (memory == 0): Valid (0 >= 0), fits even on a machine with 0 free memory, and goes to the fullest machine (ties broken by smallest ID).
  • Failed create_table or resize_table when no machine fits: Returns None and leaves the cluster completely unchanged — a failed resize_table preserves the table's old host and old memory footprint.
  • Duplicate IDs and negative capacities/sizes: Rejected cleanly (False for add_machine, None for create_table/resize_table).
  • Memory fragmentation: Even if total cluster free memory exceeds new_memory (say two machines each have 3 free and a table requests 5), no single machine can host it, so the dispatcher rightly returns None unless compaction/rebalancing is added.

Common mistakes

  • Forgetting to add back old_memory during resize_table: Checking self.free[current] >= new_memory instead of self.free[current] + old_memory >= new_memory treats the table's own existing memory as unavailable, triggering unnecessary moves or false failures.
  • Updating self.free in one branch without updating self.by_free: Once the dict and sorted list disagree, bisect_left looks up the wrong old key and deletes a neighbor's entry. Routing every update through _set_free eliminates 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 threshold x — that query requires a sorted array or search tree.
  • Mutating state before checking whether target exists: Releasing memory on current before confirming _best_fit(new_memory) succeeded would corrupt current whenever a resize cannot fit anywhere.
  • Claiming Python bisect.insort is strictly O(log M) total time: Binary search is O(log M) comparisons, whereas inserting/deleting inside a contiguous array shifts O(M) pointers in the worst case; stating both the practical speed of memmove and 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 draining set and immediately remove its (free, machine_id) tuple from by_free so _best_fit never schedules new or migrating workloads onto it (and have _set_free skip by_free updates for any ID in draining). Then iterate over a copy of tables_on[machine_id] sorted from largest table_memory to smallest — placing big tables first avoids filling the biggest cluster gaps with tiny tables — and migrate each one via _best_fit. If any table returns None, 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_table prefer machines where free >= memory * 1.2 (falling back to strict free >= memory only when needed) so tables can absorb routine 20% growth in place. Second, when a 50 GB table on machine m needs 2 GB more and m also hosts a 3 GB table, evicting the 3 GB neighbor costs 17x less network transfer than moving the 50 GB table! Because tables_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 source to target, its memory must remain reserved on both machines — releasing source early risks another table overwriting memory the live workload still uses, and not reserving target early risks two concurrent moves oversubscribing target. Introduce a pending_moves state: resize_table subtracts new_memory on target immediately, keeps old_memory locked on source, and exposes complete_move(table_id) (which releases old_memory on source and switches table_machine) plus fail_move(table_id) (which refunds new_memory on target).

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) supports lower_bound((memory, "")), insert, and delete in guaranteed O(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 maximum free_memory in its subtree) can find the first machine (by index) with free >= memory by walking down one root-to-leaf path in O(log M) time and updating a machine's free memory along the same path in O(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 above memory's bucket is guaranteed to fit in O(1) time, trading exact best-fit tightness for O(1) bucket updates.

Follow-up questions

Similar questions

More Airtable interview questions

All 12 Airtable questions →