AlgoViz

Design an in-memory file system

medium 85 min

Design 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

0:00 / 5:02

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

  1. 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.

  2. 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.

  3. 1982

    Symbolic links arrive in 4.1a BSD: a small file whose text is another path.

  4. 1987

    SunOS 4.0 brings tmpfs, a file system that lives in memory.

  5. 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.

  1. 1ApproachWhat this question tests, where it gets hard, and how to spend the time.
  2. 2ScopeAsk what changes the design, then commit to a short list.
  3. 3API and dataThe contract first, then the data that serves it.
  4. 4DesignStart with the smallest system that works. Change it only when something breaks.
  5. 5Deep divesCompare the options before you open them, then say which you would pick.
  6. 6Explain your choicesAnswer first. Then compare your reasoning.
  7. 7By levelThe same question is judged differently for mid, senior and staff.
  8. 8MockAnswer against the clock, then score yourself.

How it works

Step through the idea, or press Play.

Step 1 of 4

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.

The box called all
all

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

QuestionDefaultIf not
Absolute paths only?YesA current directory for each session, not in the file system
Is .. allowed?Yes, and the root's parent is the rootRefuse it while splitting
Does mkdir create missing parents?No, they must existA flag, and a loop over the parts
Does write create the file?Yes, but not its directoryTwo calls: create and write
May move replace an existing target?No, an errorReplace in one step, with rules for directories
Text or bytes?Text, size in charactersBytes 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.

Python
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])
A rename rewrites a thousand keys and looks at every file there is. And a file can now sit at a place where others expect a directory.
Edit and run it in your browser

Three shapes

Map of pathsTree of nodesTree plus a cache of paths
readOne lookupOne lookup for each partOne lookup on a hit
lsLooks at all filesOnly the childrenOnly the children
move a directoryRewrites every file belowTwo linksTwo links, and forget cached paths below
empty directoriesCannot existNormalNormal
Right whenNothing moves: an archive, an object storeThe question as askedDeep paths, many reads

The design to avoid: one type that can do everything, badly

Itempath: StringisDirectory: booltext: Stringchildren: List<Item>+ add(item)+ read(): String+ write(text)

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)

A flag that is asked in every method is a class that wants to exist.

Step 2

The design to reach

The design to reach: a small tree, and one class that understands paths

FileSystem- root: Directory+ mkdir(path)+ write(path, text)+ read(path): String+ ls(path): List+ remove(path, recursive)+ move(source, target)+ size(path): int- walk(parts): Node

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

ClassOwnsDoes not know
FileSystemThe root, paths, every rule about callsHow children are stored
DirectoryIts children by name, and the parent link of each childPaths
FileIts textDirectories, paths, other files
NodeA name, a link upWhich 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

The question about the kind comes first. Otherwise a file would be asked for its children.

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 ...

PathPlaceWhy
/a/b/cdirectory /a/b, name cThe normal case
/cthe root, name cThe walk over no parts is the root
/none: bad pathThe root cannot be created, moved or removed
/a/..none: bad pathThe last part is not a name
/a/file/cnone: not a directoryA 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
/a and /ab look related, /a and /x/../a/b do 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

walk=O(d),ls=O(nlog⁡n),move=O(d),size=O(subtree)\text{walk} = O(d), \qquad \text{ls} = O(n \log n), \qquad \text{move} = O(d), \qquad \text{size} = O(\text{subtree})
The sort in ls is for people. A sorted map or a plain set of names moves the cost elsewhere.

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