Design an in-memory file system
medium 85 minDesign directories and files that live in memory: create, read, write, list, move and remove by path.
Video lesson · Chapter 1 of 6
Make a prediction
Theory
Read or listen first. About 3 min.
What it is
A file system gives names to pieces of data and arranges the names in a tree. An in-memory one keeps all of it in objects of a running program. Nothing survives a restart, and that is the point: no disk, no blocks, only the rules.
The task in an object design round: files with text, directories that hold files and directories, and calls that take a path such as /trips/sun/hat. Create, write, read, list, remove, move, size.
Three things in it are harder than they look. A path is text and must be turned into a node, with a clear error when that fails. A node sits in one place, so a move must change two directories and never hang a directory below itself. And every call must check everything before it changes anything.
Why it exists
A tree with two kinds of nodes is one of the most common shapes in software: menus, organisation charts, documents, scenes in a game, components on a page. Here everybody knows the rules already, so the talk is about objects from the first minute.
It also grows in good directions. Links turn the tree into a graph. Permissions and quotas look at every directory on the way. Threads make move the hardest call of all. Each is a real problem of real systems.
And such file systems are used: in tests that must not touch the disk, in browsers, in sandboxes, in build tools. Several are named on the Real world page.
A short history
1965
Daley and Neumann describe the file system planned for Multics: a hierarchy of directories, named by paths, with access control. The shape has not changed since.
1971
The first edition of the Unix manual appears on 3 November. A directory is a list of names that point to inodes, and the thing itself has no name.
1982
Symbolic links arrive in 4.1a BSD: a small file whose text is another path.
1987
SunOS 4.0 brings tmpfs, a file system that lives in memory.
1994
The book Design Patterns names Composite. Files in directories are its best known example.
Words to know
- Path
- Text that names a place: parts between slashes. It is not the place itself.
- Absolute path
- Starts with a slash, so it is read from the root. A relative one needs a current directory.
- Resolve or walk
- Go from part to part until a node is found or an error is certain.
- Dot and dot dot
.is here,..is the parent. The parent of the root is the root.- Root
- The only directory without a parent.
- Composite
- One type for leaf and holder, where a holder keeps items of that type.
- Inode
- The data and facts of a file, without a name.
- Hard link
- A second name for the same inode.
- Symbolic link
- A node whose content is a path. It may lead nowhere.
- Atomic
- Others see all of it or none of it.
- Invariant
- A sentence that is true after each call, such as: each child's parent is the directory that holds it.
The solution, twice
Reach the regular design first. Then go where a FAANG interviewer digs.
Solve it like an interview
New to it? Start with Approach. Revising? Go straight to the mock.
- 1ApproachWhat this question tests, where it gets hard, and how to spend the time.
- 2ScopeAsk what changes the design, then commit to a short list.
- 3API and dataThe contract first, then the data that serves it.
- 4DesignStart with the smallest system that works. Change it only when something breaks.
- 5Deep divesCompare the options before you open them, then say which you would pick.
- 6Explain your choicesAnswer first. Then compare your reasoning.
- 7By levelThe same question is judged differently for mid, senior and staff.
- 8MockAnswer against the clock, then score yourself.
How it works
Step through the idea, or press Play.
A path comes in. Split it into parts. Empty parts and single dots fall away.
Understand it
Story
Hats in boxes in boxes
Noor keeps hats in boxes, and boxes in bigger boxes. Every rule of a file system can be seen in this one picture.
Labels are read from the outside in. Sizes are counted from the inside out.
What an interviewer looks for here
Two kinds, one base
Shared: name, parent, size. Not shared: read and add.
One walk
Path handling is written once, not in each method.
Exact errors
Not found, not a directory, already exists are different answers.
Safe move
No ring, no half move, no lost subtree.
Both directions
Child and parent change together, in one method.
Room to grow
Where would links, limits and locks go?
Step 1
Six questions, and what each answer changes
| Question | Default | If not |
|---|---|---|
| Absolute paths only? | Yes | A current directory for each session, not in the file system |
Is .. allowed? | Yes, and the root's parent is the root | Refuse it while splitting |
| Does mkdir create missing parents? | No, they must exist | A flag, and a loop over the parts |
| Does write create the file? | Yes, but not its directory | Two calls: create and write |
| May move replace an existing target? | No, an error | Replace in one step, with rules for directories |
| Text or bytes? | Text, size in characters | Bytes and offsets: see Open files |
Avoid
The dictionary of paths
The shortest idea is one map from full path to text. Reading is one lookup, which is faster than any tree. Then somebody renames a directory.
class FlatFs: """One dictionary: full path to text. Directories are only prefixes.""" def __init__(self): self.files = {} def write(self, path, text): self.files[path] = text def ls(self, folder): start = folder.rstrip("/") + "/" return sorted({p[len(start):].split("/")[0] for p in self.files if p.startswith(start)}) def move(self, old, new): changed = 0 for path in list(self.files): # every file of the system is looked at if path.startswith(old + "/"): self.files[new + path[len(old):]] = self.files.pop(path) changed += 1 return changedfs = FlatFs()for i in range(1000): fs.write(f"/trips/sun/photo{i}", "x")print(fs.move("/trips/sun", "/home/sun"), "keys rewritten for one rename") # 1000fs.write("/home", "I am a file now") # and nobody objectsprint(sorted(fs.files)[:2])Three shapes
| Map of paths | Tree of nodes | Tree plus a cache of paths | |
|---|---|---|---|
| read | One lookup | One lookup for each part | One lookup on a hit |
| ls | Looks at all files | Only the children | Only the children |
| move a directory | Rewrites every file below | Two links | Two links, and forget cached paths below |
| empty directories | Cannot exist | Normal | Normal |
| Right when | Nothing moves: an archive, an object store | The question as asked | Deep paths, many reads |
The design to avoid: one type that can do everything, badly
1/4One class, one flag
Every method begins with a question about the flag. A file has an empty list of children, a directory has a text nobody wants.
has (lives on)extends (is a)
Step 2
The design to reach
The design to reach: a small tree, and one class that understands paths
1/5The door
Callers speak in paths and nothing else. One class turns text into nodes, and no node knows what a path looks like from outside.
usesdepends onextends (is a)
The holder arrow from Directory back to Node is drawn as the field children, to keep the picture calm. Why leaf and holder share a type, and how much the base may promise, is the subject of the Composite pattern. Here we use it and turn to the rest.
What each class owns, and what it must not know
| Class | Owns | Does not know |
|---|---|---|
FileSystem | The root, paths, every rule about calls | How children are stored |
Directory | Its children by name, and the parent link of each child | Paths |
File | Its text | Directories, paths, other files |
Node | A name, a link up | Which kind it is |
Step 3
From text to a node
Splitting is the easy half: cut at slashes, drop empty parts and single dots. So /a//b/./c/ is a, b, c. The walk is the other half, and it meets three problems that must not be confused.
One step of the walk
read of /trips/sun/hat
Step 4
The second helper: where will it be?
Create, write, remove and move do not look for a node. They look for a place: an existing directory and a name in it, which may be free. So the walk stops one part early. Two paths have no such place: the root, and a path that ends in ...
| Path | Place | Why |
|---|---|---|
/a/b/c | directory /a/b, name c | The normal case |
/c | the root, name c | The walk over no parts is the root |
/ | none: bad path | The root cannot be created, moved or removed |
/a/.. | none: bad path | The last part is not a name |
/a/file/c | none: not a directory | A file holds nothing |
Step 5
Move, the call that decides the round
Every check before the first change
How do you stop a directory from being moved below itself?
BreaksCompare the texts of the paths
- How
- Refuse if the target starts with the source.
- Limit
/aand/ablook related,/aand/x/../a/bdo not.- Choose when
- Never.
WorksSearch below the source
- How
- Walk the whole subtree and look for the target.
- Limit
- As slow as the subtree is large.
- Choose when
- There is no link to the parent.
StrongClimb from the target
- How
- Follow parents to the root. If the source is met, refuse.
- Limit
- Needs a parent link, which is cheap.
- Choose when
- Always, as slow as the path is deep.
The life of a node
Step 6
What does each call cost?
With depth d and n children
Do
- Turn the path into parts in one function.
- Let a directory set the parent of its child.
- Check everything, then change.
- Give each failure its own kind.
- Keep the name in the node and the key of the map equal, in one method.
Do not
- Store full paths in nodes.
- Test a flag in each method.
- Detach first and then discover that the target is taken.
- Return null for five different problems.
- Make a subclass for each file ending.
Summary
The whole topic in one minute.
Two kinds of nodes share a small base: a name, a parent, a size. A directory keeps a map from name to node and is the only one that sets the parent. One class, the file system, turns paths into nodes and holds the rules.
Two helpers carry the code. walk follows the parts and knows what went wrong. parent and name gives the place where something will be created, removed or moved.
Move is the test. Find the source, find the target, see that the name is free, climb from the target to the root and make sure the source is not met. Only then change anything.
- File and Directory share a name, a parent and a size, nothing else.
- A path is text. It is resolved in one place, part by part.
- Not found, not a directory and already exists are different answers.
- Creating, removing and moving need a place: a directory and a name.
- Move climbs from the target to the root, and refuses if it meets the source.
- Attach and detach change both directions of the link, and nobody else does.
- Moving a directory costs two links, whatever is below it.
Sources
- Daley and Neumann: A general-purpose file system for secondary storage
- POSIX: general concepts, pathname resolution
- Linux manual: path_resolution
- Linux manual: rename
- Linux manual: unlink
- Linux kernel: directory locking
- Linux kernel: overview of the virtual file system
- Linux kernel: tmpfs
- Pro Git: Git objects
- Jimfs