KatInterview

Fast Machine Selection for a Memory-Aware Table Placer

Data Structure DesignModel answer
MediumModel answerData Structure Designdata-structure-designbisectbest-fit

Last 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:

  1. On a resize, check whether the table's current machine can still hold it.
  2. If it cannot, pick another machine and move the table there.
  3. 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

  1. Analyze the time complexity of the existing approach.
  2. 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.
  3. 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.