Building a Fan-Out Service That Indexes a Huge Directory Tree
System DesignModel answerLast updated
Design an asynchronous service where workers recursively split a directory scan into child tasks, with safe retries, deduplication, progress reporting and scaling to billions of files.
You are asked to design a backend service that inventories a very large file system, starting from a root path supplied by the caller.
A client calls an API to launch an indexing job. The call returns right away, and a fleet of background workers walks the directory tree asynchronously. When a worker handles a directory, it may break the work into smaller units and push new asynchronous tasks onto the same queue that fed it, so the system ends up triggering more of its own work recursively.
Walk through your design and cover the following:
- The API for starting a job and for checking its status
- The data model for jobs, tasks and the metadata of discovered files
- How a worker schedules follow-up tasks for subdirectories and for large listings
- How you deal with retries, idempotency, deduplication and partial failures
- How the design scales to extremely large trees (think on the order of a billion files, and single directories with millions of entries)
- What role the database, the message queue and the workers each play
- How clients see progress and obtain the final results
State your assumptions about scale explicitly, and point out the trade-offs you are making.
Hints
Hint 1
Make the unit of work a single page of one directory listing rather than a whole directory. Think about what that does for huge directories and for the cost of a retry.
Hint 2
Assume the queue delivers at least once and workers die at arbitrary moments. Which writes need deterministic keys, and how can you make 'mark parent done' and 'publish children' succeed or fail together?
Hint 3
Think about how you know the job is finished when work keeps spawning more work. A counter of outstanding tasks that changes by (children - 1) per task is one approach; consider what happens when that counter becomes a hot row.
Hint 4
Decide which component is the source of truth. If the queue can lose or duplicate a message, what lets you recover, and what periodic process would detect stuck tasks?
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
1. Requirements and assumptions
Functional
- Starting a job returns a
job_idimmediately; the crawl runs in the background. - For every file we store path, size, modification time, owner and optionally a content hash.
- Clients can poll status and progress, cancel, and page through results and errors.
Non-functional
- Correct under at-least-once delivery: workers crash, messages are redelivered.
- Horizontal scalability, plus rate limiting so we do not overwhelm the storage being scanned.
- Every job reaches a terminal state, even if some directories are unreadable (a
PARTIALoutcome). - Fairness across many concurrent jobs and tenants.
Scale assumptions: up to about 1B files in about 100M directories; some directories hold over 1M entries; target of about 50k files/s per job, so a maximal crawl takes roughly 1e9 / 5e4 = 20,000 s, about 5.5 hours. At about 200 B per metadata row that is around 200 GB per large job, so the metadata store must be sharded and written in batches.
2. API
POST /v1/crawls { root_path, filters?, max_depth?, follow_symlinks?, idempotency_key }
-> 202 { job_id, status: "PENDING" }
GET /v1/crawls/{id} -> { status, dirs_found, dirs_done, files_found, bytes_seen,
tasks_pending, tasks_failed, started_at, finished_at }
GET /v1/crawls/{id}/files?cursor=&limit=1000
GET /v1/crawls/{id}/errors?cursor=
POST /v1/crawls/{id}:cancel
The idempotency key matters: a client that retries after a timeout must get the same job_id, not launch a second crawl. Enforce it with a unique constraint on (tenant_id, idempotency_key).
3. Data model
- jobs:
job_id,tenant_id,root_path,options,status,idempotency_key, timestamps. - job_counters: keyed by
(job_id, shard), holdingpending_tasks,files_found,dirs_done,failed_tasks. Sharded so a hot job does not hammer a single row. - tasks:
task_id = hash(job_id, dir_path, page_cursor),state(QUEUED/RUNNING/DONE/FAILED),attempts,lease_expires_at,last_error. - file_metadata: primary key
(job_id, path), sharded by hash of that key. The key makes re-writes idempotent. - visited_dirs: unique
(job_id, inode/file_id)to break cycles from symlinks and hard links when following links is enabled. - outbox:
(id, task_id, payload, published)for reliable publishing.
4. Architecture and roles
Client -> API -> DB (job + root task + outbox row in one txn)
Outbox relay -> Queue (partitioned by job)
Queue -> stateless worker pool
list one page (rate-limited) -> batch upsert files
-> txn: child tasks + outbox + parent DONE + counter update
Completion detector -> terminal status -> optional export to object storage
- Database = source of truth. Job, task and result state live here. A lost queue message loses nothing because every task is recoverable from the task table.
- Queue = distribution and buffering. It gives backpressure and lets workers scale; delivery is at-least-once with visibility timeouts and a dead-letter queue.
- Workers = stateless executors. Lease a task, do the work, commit, then ack.
5. Recursive scheduling
A task is one directory page (dir_path, cursor). The worker:
- Lists up to N entries (say 5,000).
- Batch-upserts file rows.
- Creates one child task per subdirectory and, if more entries remain, a continuation task
(dir_path, next_cursor).
Paging is what tames huge directories: a 1M-entry directory becomes about 200 small tasks that retry cheaply, instead of one long fragile task. (Continuations depend on a stable cursor; for filesystems without one, use a sorted-name marker.)
6. Never lose a subtree: transactional outbox
Ordering is the trap. If the worker marks the parent done and then crashes before enqueueing children, the whole subtree is lost. If it enqueues children and then crashes, the parent retries and children are enqueued twice, which deterministic IDs make harmless. So do this in one transaction: insert child tasks (ON CONFLICT DO NOTHING), insert outbox rows, mark the parent DONE, and apply pending_tasks += newly_inserted_children - 1. A relay publishes outbox rows to the queue. The worker acks the message only after commit.
7. Completion detection
The counter starts at 1 (root). Each task changes it by children - 1 in the same transaction as its state change, so it cannot hit zero while work remains. When it reaches zero, the job is terminal. To avoid a hot row, use K counter shards and sum them, or have a detector periodically check for non-terminal tasks of the job.
8. Retries, idempotency, deduplication
- Leases and sweeper: tasks carry
lease_expires_at; a sweeper re-enqueues expired ones, covering dead workers and dropped messages. - Duplicate deliveries: a message for a task already
DONEis acked and dropped. - Idempotent writes: file upserts keyed by
(job_id, path), deterministic task IDs, counters changed only together with the state transition. - Backoff: exponential with jitter for transient errors (timeouts, throttling); permanent errors (permission denied, path vanished) fail the task immediately.
- Dedup of directories:
visited_dirsfor symlink and hard-link cycles; a depth limit as a backstop.
9. Partial failures
After max_attempts a task becomes FAILED, its error is recorded, and the counter still decrements so the job can finish. A job with failed tasks ends as PARTIAL, and the errors endpoint lists the affected paths so they can be re-run selectively. Cancellation sets a job flag that workers check before processing and before enqueueing children.
10. Scaling and protection of the source
- Partition the queue and tables by job to keep locality; autoscale workers on queue depth.
- Per-job and per-backend token-bucket rate limits, with a fair scheduler (weighted round robin across jobs) so one giant crawl does not starve small ones.
- Batch writes (hundreds to thousands of rows) and shard the metadata store by
hash(job_id, path). - Prefer breadth-limited expansion or priority by depth to bound the number of queued tasks; the task table, not memory, holds the frontier.
- Hot directories are handled by paging; very wide fan-out is throttled by limiting child tasks created per transaction.
11. Progress and results
Status reads come from the sharded counters (eventually consistent, cheap). Results are paged by cursor over file_metadata, and for large jobs a finished export (for example columnar files in object storage) is exposed via a result location. Optionally push updates via webhook on terminal state.
Common mistakes
- Treating the queue as the source of truth.
- Marking a parent done before durably recording children.
- A single global counter row.
- One task per whole directory, which makes large directories a bottleneck.
- No idempotency key on job creation, no cycle detection, and no rate limiting of the scanned system.