Fast Machine Selection for a Memory-Aware Table Placer
Data Structure DesignModel answerLast updated
Redesign a slow in-memory placer so it finds a machine with enough free RAM, resizes tables, and moves them quickly, while justifying a placement policy.
Speeding up a placement service
A single-threaded, in-memory placer decides which machine hosts each table. It exposes two kinds of calls.
Calls from the storage layer
CreateTable(tableId, memoryRequired)ResizeTable(tableId, newMemoryRequired)
Calls the placer makes to a lower-level orchestrator
CreateWorkload(machineId, tableId): put a table on a machine.MoveWorkload(tableId, fromMachineId, toMachineId): relocate a table.
The placer tracks:
- a fixed set of machines, each with a known memory capacity,
- a set of tables, each needing some amount of memory,
- which machine currently hosts each table.
Required behavior:
- On a resize, check whether the table's current machine can still hold it.
- If it cannot, pick another machine and move the table there.
- On a create, pick a machine and place the table on it.
You inherit a version that is correct but slow. It re-sums table sizes to learn each machine's free memory, and it scans every machine on every request.
What to produce
- Analyze the time complexity of the existing approach.
- Propose data structures that make these fast:
- looking up a table or a machine,
- finding a machine with enough free memory,
- updating free memory after a place, move, or resize.
- Choose a placement policy (for example first-fit or best-fit) and discuss the trade-offs.
Ground rules
- No external database and no concurrency.
- Prioritize efficiency, correctness, and maintainability.
- Cover edge cases: unknown table, shrinking a table, exact fit, and fragmentation.
Hints
Hint 1
Ask what gets recomputed on every request. If a value can be maintained incrementally with a delta, you never need to re-sum anything.
Hint 2
You need a structure that answers 'smallest free memory that is at least X' quickly. Think about an ordered collection of (freeMemory, machineId) pairs and a binary search.
Hint 3
Funnel every change to a machine's free memory through one helper that updates both the free-memory map and the ordered index, so they cannot drift apart. Do all validation before mutating anything so a failed call leaves state untouched.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Why the naive version is slow
Two costs dominate:
- Recomputing free memory. Each machine's free memory is obtained by summing the sizes of its tables, costing O(T) in the worst case.
- Scanning all machines. Choosing a destination checks every machine, and each check does the recomputation above. That gives roughly O(M·T) per request (M machines, T tables). Looking up a table by ID in an unindexed list adds another O(T).
Improved design
Keep derived state current instead of recomputing it:
| Structure | Purpose |
|---|---|
tables: tableId -> (machineId, memory) | O(1) lookup of placement and size |
machines: machineId -> set(tableId) | O(1) view of what runs where (debugging, rebalancing) |
free: machineId -> freeMemory | Maintained by deltas, never summed |
Sorted index of (freeMemory, machineId) | Binary search for the smallest free value that is at least X |
Invariant: for every machine m, free[m] == capacity[m] - sum(memory of tables on m), and the index holds exactly one entry (free[m], m) per machine.
Every place, move, or resize changes free memory on at most two machines. All such changes go through one helper, _set_free, which removes the old index entry, updates the map, and inserts the new entry. That single choke point keeps the invariant true after every call.
Placement policy
I would choose best-fit: pick the machine with the least free memory that still fits. A binary search with bisect_left(index, (need,)) returns the first entry whose free memory is at least need, and the one-element tuple makes an exact fit valid.
| Policy | Pros | Cons |
|---|---|---|
| First-fit | Simple, no index | O(M) scan, arbitrary packing |
| Best-fit | Tight packing, keeps large holes available | Machines run nearly full, so growth often forces moves |
| Worst-fit (max-heap) | O(log M), leaves headroom for growth | Fragments every machine, large tables may not fit |
The key tension: best-fit minimizes fragmentation, while worst-fit minimizes future moves when tables grow often. A sensible hybrid is best-fit with a headroom reserve (say 10%) so resizes usually stay in place.
Resize logic
Moves are expensive in a real system, so try to stay put first. With delta = new - old, the table fits in place when delta <= free[current]. Shrinking has a negative delta, so it always fits. Otherwise search for a machine with free >= new, excluding the current machine (its free memory does not include the table's own footprint in the right way, and it is already known not to fit). Then update both machines and call MoveWorkload.
Complexity
| Operation | Naive | Improved |
|---|---|---|
| Table or machine lookup | O(T) | O(1) |
| Free memory of a machine | O(T) | O(1) |
| Choose a machine | O(M·T) | O(log M) |
| Update after change | recomputed later | O(log M) with a balanced tree or SortedList; O(M) memmove with a plain sorted list |
Space is O(M + T). In Python, bisect.insort on a list is technically O(M) but is a fast memmove, fine up to around 10^5 machines. I would state that trade-off aloud and name sortedcontainers.SortedList or a balanced tree as the asymptotically clean option.
Edge cases
- Resize of an unknown table: raise
KeyError; silently creating it hides caller bugs. - Duplicate create: raise an error; overwriting would corrupt accounting.
- Shrinking: always succeeds in place and returns memory to the index.
- Exact fit: allowed (
free == need). - Memory values: zero is allowed, negative is rejected.
- No machine fits: raise
NoCapacityErrorand leave state unchanged. This covers a table bigger than every machine, and fragmentation where total free memory suffices but no single machine has enough. Rebalancing (moving small tables to consolidate space) is a natural follow-up; it is bin-packing-like and NP-hard, so it is done heuristically. - Machine IDs must be mutually comparable because they break ties in the index.
- Atomicity: perform all checks before any mutation.
Code
import bisect
class NoCapacityError(Exception):
pass
class Placer:
def __init__(self, capacities, orchestrator):
self.free = dict(capacities)
self.tables = {} # tid -> (machine, mem)
self.machines = {m: set() for m in capacities}
self._index = sorted((f, m) for m, f in self.free.items())
self.orch = orchestrator
def _set_free(self, m, new_free):
i = bisect.bisect_left(self._index, (self.free[m], m))
self._index.pop(i)
self.free[m] = new_free
bisect.insort(self._index, (new_free, m))
def _best_fit(self, need, exclude=None):
i = bisect.bisect_left(self._index, (need,))
while i < len(self._index):
m = self._index[i][1]
if m != exclude:
return m
i += 1
return None
def create_table(self, tid, mem):
if mem < 0 or tid in self.tables:
raise ValueError("bad request")
dest = self._best_fit(mem)
if dest is None:
raise NoCapacityError()
self._set_free(dest, self.free[dest] - mem)
self.tables[tid] = (dest, mem)
self.machines[dest].add(tid)
self.orch.create_workload(dest, tid)
return dest
def resize_table(self, tid, new_mem):
if new_mem < 0:
raise ValueError("negative memory")
cur, old = self.tables[tid] # KeyError if missing
delta = new_mem - old
if delta <= self.free[cur]:
if delta:
self._set_free(cur, self.free[cur] - delta)
self.tables[tid] = (cur, new_mem)
return cur
dest = self._best_fit(new_mem, exclude=cur)
if dest is None:
raise NoCapacityError()
self._set_free(cur, self.free[cur] + old)
self._set_free(dest, self.free[dest] - new_mem)
self.machines[cur].discard(tid)
self.machines[dest].add(tid)
self.tables[tid] = (dest, new_mem)
self.orch.move_workload(tid, cur, dest)
return dest
Common mistakes
- Updating
freein several places so the map and index diverge. - Searching with
free >= deltawhen moving, instead offree >= new_mem(the table is not yet on the destination). - Mutating state before confirming a destination exists, leaving a half-applied change on failure.
- Forgetting that the current machine may be returned by the search during a move.
- Not discussing the best-fit versus worst-fit trade-off or the cost of moves.