Metadata Store for Folders, Quotas and Largest-File Queries
System DesignModel answerLast updated
Design an in-memory hierarchical file metadata service with create, recursive delete, fast top-k largest files per directory, and nested quota enforcement, plus a multi-node scaling plan.
Metadata service for a hierarchical file store
Design a service that keeps the metadata of a file system (folders and files) entirely in memory. It must answer queries with low latency, and the query that finds the biggest files under a folder must be especially fast, even if that makes writes more expensive.
Operations
create(path, size) -> bool: add a file atpathwith the given size. Missing intermediate folders are created automatically. Returnfalseif the path already exists, if a component of the prefix is a file, or if the new file would push any ancestor folder over its quota.delete(path) -> bool: remove a file, or a folder together with everything below it. Returnfalseif the path does not exist.get_top_k(path, k) -> list[str]: return the paths of theklargest files in the folder's whole subtree. Order by size descending, and break ties by path ascending so results are deterministic.update_quota(path, limit) -> bool: set a storage cap on a folder. Returnfalseif the folder's current usage is already abovelimit, or iflimitis larger than the quota of its nearest ancestor that has one.
Scale and assumptions
- Up to about 10^6 files and folders in total.
- Everything fits in RAM on one machine for the core design.
- Quotas nest: a folder's usage can never exceed the quota of any ancestor.
Example
create("/home/user/data.txt", 100)
create("/home/user/logs/app.log", 200)
get_top_k("/home/user", 1) -> ["/home/user/logs/app.log"]
What to deliver
- Requirements and scale estimates, including memory.
- The data model and the algorithm for each operation, with complexity.
- Code for the core structure.
- Trade-offs against alternative designs, and how you would extend this to several machines.
Hints
Hint 1
If every folder could hand you its files already sorted by size, what would get_top_k reduce to? Think about what you would have to maintain on writes to make that true.
Hint 2
Keep a running byte total per folder so a quota check is O(1) per ancestor. Validate every ancestor before changing anything, so a rejected create leaves no partial state.
Hint 3
To shard across machines, partition by top-level path prefix. Then ask what breaks for queries and quotas that span partitions, and how a k-way merge of per-shard top-k lists helps.
Model answer
Hard Try it yourself first — then compare your approach, complexity and edge cases.
1. Requirements and sizing
Behavior I am committing to
createmakes missing parent folders (likemkdir -p), fails if the target exists or a prefix component is a file, and fails if any existing ancestor would exceed its quota.get_top_kranks by size descending, then path ascending. A file or missing path returns an empty list, andk <= 0returns an empty list.update_quotafails for a missing path or a file, whenused > limit, or whenlimitexceeds the nearest ancestor quota.
Scale. N = 10^6 nodes, typical depth d around 10 to 20. Reads of top-k are the hot path, so I accept costlier writes.
Memory. If every folder keeps an index of all files below it, each file appears in about d indexes. That is roughly 10^6 x 10 = 10^7 entries. At 40 to 80 bytes each in a compiled language, that is 0.5 to 1 GB, which fits comfortably. In Python it is several times larger, so I would say that this is the main cost of the design and is the thing to revisit first.
2. Data model
A tree (a trie over path components). Each node holds:
| Field | Purpose |
|---|---|
name, parent, children (dict) | navigation |
is_file, size, path | file data |
used | total bytes in the subtree |
quota | optional cap, None if unset |
files | sorted collection of (-size, path) for every file in the subtree |
The sorted files index on each folder turns get_top_k into a slice. The used counter makes quota checks constant time per ancestor.
3. Operations
create. Walk the existing part of the path (O(d)). Reject if a prefix component is a file or the target exists. Check used + size <= quota on every existing ancestor before mutating anything; newly created folders have no quota, so only existing ones matter. Then create the missing folders and the file, and walk up the ancestors adding size to used and inserting the entry into files. Cost: O(d log N).
get_top_k. Find the folder in O(d), then slice the first k entries: O(log N + k), independent of subtree size.
delete. The target's own index lists every file below it. For each of those m files, remove the entry from every proper ancestor, and subtract the target's used from those ancestors. Then detach the node. Cost: O(m · d · log N). Deleting a single file is the m = 1 case.
update_quota. Compare with used, walk up to the nearest ancestor that has a quota, compare, then store. Cost: O(d).
from sortedcontainers import SortedList
class Node:
__slots__ = ("name", "parent", "children", "is_file",
"size", "path", "used", "quota", "files")
def __init__(self, name, parent=None, is_file=False, size=0, path=""):
self.name, self.parent = name, parent
self.children = {}
self.is_file, self.size, self.path = is_file, size, path
self.used = size if is_file else 0
self.quota = None
self.files = None if is_file else SortedList()
class MetaStore:
def __init__(self):
self.root = Node("")
@staticmethod
def _parts(path):
return [p for p in path.split("/") if p]
def _find(self, path):
node = self.root
for p in self._parts(path):
node = node.children.get(p)
if node is None:
return None
return node
@staticmethod
def _up(node):
while node is not None:
yield node
node = node.parent
def create(self, path, size):
parts = self._parts(path)
if not parts:
return False
node, complete = self.root, True
for p in parts[:-1]:
nxt = node.children.get(p)
if nxt is None:
complete = False
break
if nxt.is_file:
return False
node = nxt
if complete and parts[-1] in node.children:
return False
for a in self._up(node):
if a.quota is not None and a.used + size > a.quota:
return False
node = self.root
for p in parts[:-1]:
if p not in node.children:
node.children[p] = Node(p, node)
node = node.children[p]
full = "/" + "/".join(parts)
f = Node(parts[-1], node, True, size, full)
node.children[parts[-1]] = f
entry = (-size, full)
for a in self._up(node):
a.used += size
a.files.add(entry)
return True
def delete(self, path):
node = self._find(path)
if node is None or node is self.root:
return False
entries = [(-node.size, node.path)] if node.is_file else list(node.files)
for a in self._up(node.parent):
a.used -= node.used
for e in entries:
a.files.remove(e)
del node.parent.children[node.name]
return True
def get_top_k(self, path, k):
node = self._find(path)
if node is None or node.is_file or k <= 0:
return []
return [p for _, p in node.files[:k]]
def update_quota(self, path, limit):
node = self._find(path)
if node is None or node.is_file or node.used > limit:
return False
for a in self._up(node.parent):
if a.quota is not None:
if limit > a.quota:
return False
break
node.quota = limit
return True
On the example, the index of /home/user holds (-200, ".../app.log") then (-100, ".../data.txt"), so top-1 is app.log.
4. Trade-offs
- Per-folder full index (chosen): reads O(log N + k), writes O(d log N), memory about d times the file count.
- Lazy, direct files only plus heap merge across children: writes O(1), memory O(N), but a read can touch the whole subtree. This breaks the stated priority.
- Capped cache of the top K_max (say 100) per folder: bounds memory, but deletes can drain the cache and force a refill from children, which complicates correctness. A good middle ground if k is known to be small.
- Large deletes: removing a root with 10^6 files means about 10^7 index removals. Mitigate with tombstoning the subtree and filtering at read time, with background cleanup, or by rebuilding ancestor indexes in bulk when m is a large share of them.
- Quota semantics: because a parent's quota may later be lowered below a child's, always validate every ancestor on create, not just the nearest one.
- Concurrency: use a reader-writer lock, or per-subtree locks taken root-to-leaf, since a write touches the whole ancestor chain. Reads are far more frequent, so a single writer with snapshot reads is a reasonable start.
5. Scaling to multiple nodes
- Partition by top-level path prefix (or a hash of the first one or two components), with a routing layer or consistent hashing. Hot tenants can be split further by deeper prefix.
- Top-k within a shard is unchanged. For a query at a folder spanning shards (for example
/), each shard returns its local top k and the coordinator does a k-way merge, costing O(S · k). - Quotas across shards need a single owner per quota folder, or a reservation protocol: reserve bytes at the owner, then commit the create. Two-phase style handling avoids over-admission.
- Durability: replicate each shard (leader plus followers), write an append-only log of mutations, and snapshot periodically. Recovery is snapshot plus log replay.
- Rebalancing: moving a subtree means moving its index, so prefer coarse, infrequent moves.
6. Common mistakes
- Mutating ancestors before finishing all quota checks, leaving partial state on failure.
- Forgetting to remove a deleted subtree's files from every ancestor index, which leaves ghost results.
- Sorting only by size, so ties return unstable results.
- Skipping the memory estimate, or ignoring that the index multiplies storage by the depth.
- Allowing a child quota larger than its parent's, or only checking the immediate parent.