Build a Composable Filesystem Query Engine in the Spirit of find
System DesignModel answerLast updated
Design an extensible, object-oriented library and CLI that walks directory trees, filters entries with composable predicates, and handles symlinks, errors, and huge trees.
Problem
Design a module that lets callers search a filesystem by criteria, in the same spirit as the UNIX find utility. It should be usable both as a library and as a command-line tool.
Required capabilities
- Selection criteria:
- name pattern (glob or regex)
- entry type (regular file, directory, symbolic link)
- size range
- modification and creation time
- permissions and owner
- minimum and maximum depth
- Composition: criteria can be combined with AND, OR and NOT.
- Symlink policy: the caller can choose to skip links or follow them.
- Output: the caller can receive bare paths or richer metadata.
What to cover in your answer
- The main classes or interfaces, with a diagram or sketch and the key data structures.
- Two entry points: a library API and a command-style API. Show how both reach the same engine.
- How a developer adds a brand-new filter without editing existing code.
- The traversal strategy and its performance: early pruning, ordering of cheap versus expensive checks, and concurrency.
- Robustness: very large directories, very large trees, permission failures, files vanishing mid-scan, broken links and symlink cycles.
- A test plan, including how to test without touching a real disk.
State any assumptions you make (platform, scale, error policy).
Hints
Hint 1
Think of each criterion as an object with a single yes/no method on a directory entry, and make AND, OR and NOT objects of the same kind so they nest freely.
Hint 2
Most of the cost in a tree walk is in per-file metadata calls. Which criteria can be answered from the directory listing alone, and how can you avoid fetching metadata unless a check really needs it?
Hint 3
Separate the filesystem access, the walking strategy and the output formatting behind interfaces, so you can swap in a fake filesystem for tests or a parallel walker for speed. Do not forget cycle detection when links are followed.
Model answer
Hard Try it yourself first — then compare your approach, complexity and edge cases.
Framing
This is mainly an object-oriented design problem with real filesystem subtleties: symlink cycles, permission errors, huge directories and the cost of metadata calls. A strong answer shows clean abstractions, extensibility without modification, and awareness of those realities.
1. Requirements and assumptions
Functional: the filters listed in the problem, depth bounds, boolean composition, a symlink policy (never follow, follow only the starting roots, always follow), and path or metadata output through both a CLI and a library.
Non-functional (assumed):
- Trees of up to about 10^8 entries and single directories with over 10^6 entries, possibly on network mounts.
- Results are streamed. Memory stays proportional to depth, never to tree size.
- Errors such as permission denied, a file removed mid-scan, or a broken link are reported and the scan continues.
- Bounded resources: capped threads and open directory handles.
- Target POSIX, but hide the OS behind an interface so other backends can be added.
2. Core abstractions
FileSystem(interface):scandir(path)andstat(path, follow). Implementations areLocalFileSystemand an in-memoryFakeFileSystemfor tests.FileEntry: path, name, depth, and cheap type info from the directory listing. Itsstat()is lazy and memoized.Predicate(interface):matches(entry) -> boolplus acosthint (1 = name/type only, 10 = needs stat).- Leaves:
Name,Type,Size,Time,Perm,Owner. - Composites:
And,Or,Not.
- Leaves:
Walker(strategy):SequentialWalker,ParallelWalker.FindOptions: min/max depth, symlink mode, error policy (ignore, report, raise), aprunepredicate, and a same-device flag.Formatter: path, null-separated path, JSON, long listing.Finder(facade):find(roots, predicate, options)returns an iterator of entries.
Patterns: Specification plus Composite for predicates, Strategy for walkers and formatters, dependency injection for the filesystem, and generators for streaming and early exit ("first 10 matches").
class Predicate(ABC):
cost = 1
@abstractmethod
def matches(self, e): ...
def __and__(self, o): return And(self, o)
def __or__(self, o): return Or(self, o)
def __invert__(self): return Not(self)
class And(Predicate):
def __init__(self, *ps):
self.ps = sorted(ps, key=lambda p: p.cost) # cheap first
def matches(self, e):
return all(p.matches(e) for p in self.ps)
class Size(Predicate):
cost = 10
def __init__(self, lo=0, hi=float("inf")): self.lo, self.hi = lo, hi
def matches(self, e): return self.lo <= e.stat().st_size <= self.hi
Because name and type come free with the directory listing, a query such as name == "*.log" issues no stat calls at all. This is usually the largest single performance gain.
3. APIs
Library
q = (Name("*.log") & Type.FILE & Size(lo="100M")) | ~Owner("root")
opts = FindOptions(max_depth=5, symlinks=SymlinkMode.NEVER,
on_error=ErrorPolicy.REPORT, prune=Name(".git"))
for e in Finder().find(["/var"], q, opts):
print(e.path)
Command style
find /var -maxdepth 5 -name '*.log' -type f -size +100M -o -not -user root
A small recursive-descent CommandParser builds the same predicate tree. Precedence from tightest to loosest: parentheses, NOT, AND (explicit or implicit), OR. Both interfaces share one engine.
Extensibility: a PredicateRegistry maps a flag (such as -newer) to a factory. A new filter is one class plus one registration line, with no edits to the walker or existing predicates (open/closed principle).
4. Traversal
Use iterative DFS with an explicit stack of directory iterators. Recursion can overflow on deep trees, and one open iterator per level keeps memory at O(depth) rather than O(directory size).
For each entry:
- Compute depth. Skip beyond
max_depth; do not descend atmax_depth. - If
depth >= min_depth, evaluate the predicate and yield on a match. - Descend only if it is a directory, depth allows, and the
prunepredicate does not match. Pruning.gitornode_modulesremoves whole subtrees and beats any per-file optimization.
Short-circuit and cost ordering: sort operands by cost so cheap checks run first. Reordering is safe only for side-effect-free predicates. Actions like delete or exec must keep their written order.
Symlinks
- Never-follow mode uses
lstatand does not descend through links. - Always-follow mode tracks
(st_dev, st_ino)of directories on the current path to detect cycles (for examplea/b -> ..). A cycle is a warning, not a fatal error. - Broken links fall back to
lstatand still match a "link" type filter. - A same-device flag stops traversal from crossing into
/procor network mounts.
Concurrency: walking is syscall- and network-latency-bound, so a ParallelWalker helps.
- A bounded worker pool consumes a queue of directories. Each worker scans one directory, emits matches, and enqueues subdirectories.
- Cap threads and queue size to bound file descriptors and memory.
- Termination needs a counter of pending directories: finish when it reaches zero.
- Output order is no longer deterministic; offer a sequential mode or sort when order matters.
- Expect diminishing returns on local SSDs and large gains on NFS or cold caches.
5. Robustness
- Huge directories: iterate lazily with
scandir; never list into an array. - Permission denied / vanished files: catch per directory and per entry, hand the error to the configured policy, and continue.
- Races: a file may disappear between listing and
stat. Treat that as "not matching" plus a warning. - Time semantics: be explicit that "creation time" is unavailable on many Linux filesystems; document the fallback to change time or birth time where supported.
- Pattern cost: compile regexes once, and reject or time-limit pathological patterns.
6. Tests
- Use
FakeFileSystemto build trees deterministically: nested dirs, hidden files, empty dirs. - Unit-test each predicate and the truth tables of AND, OR and NOT, including De Morgan equivalences.
- Depth:
min_depthandmax_depthboundaries, including 0. - Symlinks: self-loop, mutual loop, broken link, link to a file, each under every mode.
- Errors: an unreadable directory should not stop siblings from being scanned; the error should be reported.
- Parser: precedence, parentheses, quoting, unknown flags.
- Parallel versus sequential: the same result set (compare as sets).
- Scale smoke test: a generated tree with a million entries, checking bounded memory and early termination.
Common mistakes
- Calling
staton every entry up front. - Building the full result list before returning.
- Recursing without a depth or cycle guard.
- Hard-coding filters inside the walker.
- Aborting the whole scan on the first permission error.
- Reordering predicates that have side effects.
Trade-offs
Sequential DFS is simple, ordered and low-overhead. Parallel traversal is faster on high-latency storage but adds nondeterminism and complexity. Lazy stat saves syscalls but can surprise callers who expect immediate errors, so document it.