Design an In-Memory File System
Intermediate · 20 min read · Low-Level Design, Case Studies: Core
Composite tree, path resolution, cycle-safe moves, visitors and locking.
"Design an in-memory file system" (mkdir, ls, read/write files, delete, move, find) is the textbook Composite problem, and a common machine-coding round in its own right (a version of it is LeetCode 588).
What the interviewer expects
The full design in this lesson is longer than anything you'd write in one round. It's there so you understand the edge cases and can answer follow-up questions. In the round itself, aim for this:
1. Requirements
2. Model: Composite
Files and directories share an interface (name, parent, size), and a directory holds children of either kind. The size of a directory is the sum of its children's sizes — the recursion lives in the structure.
3. Implementation
Turn a path string into clean components once, handling ., .. and repeated slashes; everything else works on the list.
4. Concurrency
The simplest correct design is one read-write lock for the whole tree: ls, readFile, size and find take the read lock and run in parallel; anything that changes structure or content takes the write lock.
5. Patterns used
6. Extensions
Interview questions
- Why is the file system a good fit for the Composite pattern?
- How do you stop someone moving a directory into its own subdirectory?
- How would you make directory size O(1)?
Further reading
Key takeaways
- Composite models the tree: shared Node type, children only on directories, recursive operations in the structure.
- Normalise paths once (., .., extra slashes) and give each failure its own exception.
- Use parent pointers for path(), .. and cycle-safe move.
- Put whole-tree queries in visitors (or a sealed-type switch).
- One read-write lock is a correct baseline; name lock coupling and copy-on-write as next steps.
Previous: Design a Library Management System · Next: Design a Key-Value Store with Transactions