Async API for Large-Scale Directory Traversal
System DesignModel answerLast updated
Build a non-blocking API and worker system to crawl millions of files across cloud storage accounts with progress tracking and fault tolerance.
Problem Statement
You need to build a backend system that traverses the directory structure of cloud storage accounts containing millions of files. The system must expose an HTTP API where clients can start a traversal job, then poll for its status and retrieve discovered file metadata incrementally.
Requirements
Functional:
- Expose an endpoint to initiate a traversal job, returning a job identifier
- Provide an endpoint to query job status (queued, running, done, error) and retrieve partial results
- Support traversals over accounts containing up to 10 million files
- Return file metadata (path, size, modified timestamp, hash) without downloading content
Non-Functional:
- Handle thousands of simultaneous traversal jobs
- Survive worker crashes without losing progress or restarting from scratch
- Maximize throughput by parallelizing directory enumeration across multiple workers
- Respect strict per-account rate limits imposed by the storage provider (typically 10–20 req/sec)
Constraints:
- The cloud storage API enforces per-account and global quotas
- Directory trees may contain symbolic links that create cycles
- Some directories may be deeply nested or contain tens of thousands of entries requiring pagination
What to Deliver
- Architecture overview: Identify the main components and how they communicate
- API specification: Define the HTTP endpoints, request/response shapes, and status codes
- Job orchestration strategy: Explain how tasks are distributed, tracked, and completed
- Rate limit and failure handling: Describe your approach to quota enforcement, retries, and crash recovery
Hints
Hint 1
Think about why blocking HTTP requests won't work for multi-hour operations—where should the actual traversal happen?
Hint 2
Consider representing each directory as an independent unit of work so progress survives crashes and parallelizes naturally
Hint 3
Use stable directory identifiers (not paths) to detect cycles, and maintain a shared visited set across all workers
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Model Answer
1. Requirements Clarification
Begin by establishing concrete numbers to guide design choices:
- Job scale: ~10M files per account, ~100 files per directory average → ~100K directory listing operations
- Concurrent jobs: ~5,000 active at peak
- Storage API limits: 10–20 requests/sec per account, 5,000 req/sec global app quota
- Expected duration: At 15 req/sec, 100K calls take ~2 hours per job
The critical insight: this workload is I/O-bound and quota-constrained, not CPU-bound. Adding parallelism helps only until you hit the per-account rate limit. The bottleneck is external API throughput, so the architecture must optimize around quota utilization and fault tolerance.
2. API Design
POST /jobs
Body: { account_id, root_path, max_depth? }
Headers: Idempotency-Key
Response: 202 Accepted
{ job_id, status: "queued", created_at }
GET /jobs/{job_id}
Response: 200 OK
{ job_id, status: "queued|running|completed|failed",
progress: { directories_processed, directories_pending, files_discovered },
started_at, updated_at, error_message? }
GET /jobs/{job_id}/files?cursor=...&limit=500
Response: 200 OK
{ files: [{ path, size_bytes, modified_at, content_hash }], next_cursor? }
POST /jobs/{job_id}/cancel
Response: 202 Accepted
Return 202 Accepted immediately from POST /jobs so the HTTP connection never blocks on long-running traversal. Stream results via cursor-based pagination to avoid loading millions of records into memory. Report progress estimates (total unknown until completion).
3. Architecture
┌────────┐
│ Client │
└───┬────┘
│ HTTP
┌───▼──────────┐ ┌─────────────┐
│ API Service ├──────►│ Job Metadata│
└───┬──────────┘ │ (Postgres) │
│ └─────────────┘
│ enqueue
┌───▼──────────┐
│ Task Queue │◄──┐
│ (SQS/Kafka) │ │ enqueue children
└───┬──────────┘ │
│ pull │
┌───▼──────────────┴───┐ ┌──────────────┐
│ Worker Pool ├──────►│ Results Store│
│ (stateless, autoscale)│ │ (DynamoDB/S3)│
└───┬───────────────────┘ └──────────────┘
│
┌───▼──────────┐ ┌──────────────┐
│ Rate Limiter ├──────►│ Storage API │
│ (Redis) │ │ (external) │
└──────────────┘ └──────────────┘
Flow:
- API service validates the request, persists job metadata, enqueues the root directory as a task
- Workers claim tasks, acquire rate-limit tokens, call the storage API's list operation, write discovered files to the results store, and enqueue child directories
- A coordinator process monitors lease expirations and updates job completion status
4. Job Orchestration
Task model: Represent each directory as an independent queue message. This enables:
- Horizontal parallelism across workers
- Durable progress (queue persists frontier, not in-process stack)
- No stack overflow on deep nesting
- Simple retry semantics (re-process one directory, not the entire subtree)
Data schema:
jobs (
job_id UUID PRIMARY KEY,
account_id TEXT,
root_path TEXT,
status TEXT,
pending_count BIGINT,
processed_count BIGINT,
files_found BIGINT,
created_at, updated_at, error
)
tasks (
job_id UUID,
directory_id TEXT, -- stable ID from storage API
page_token TEXT,
status TEXT,
lease_holder TEXT,
lease_expires_at TIMESTAMP,
attempt_count INT,
PRIMARY KEY (job_id, directory_id, page_token)
)
visited (
job_id UUID,
directory_id TEXT,
PRIMARY KEY (job_id, directory_id)
)
files (
job_id UUID,
file_id TEXT,
path TEXT,
size_bytes BIGINT,
modified_at TIMESTAMP,
content_hash TEXT,
PRIMARY KEY (job_id, file_id)
)
Cycle detection: Use the storage system's stable directory identifier (inode or UUID), not the path. Before enqueuing a subdirectory, attempt INSERT INTO visited (job_id, directory_id) ON CONFLICT DO NOTHING. If the insert succeeds, enqueue the task; otherwise skip (already visited).
Completion tracking: Maintain an atomic pending_count counter. Increment when enqueuing child tasks, decrement when a task finishes. When it reaches zero, mark the job completed. For crash safety, wrap the decrement and child enqueues in a transaction.
Fault tolerance:
- Workers claim tasks with a visibility timeout (SQS) or lease (database lock)
- If a worker crashes, the lease expires and another worker retries
- All operations are idempotent: file records upsert by
(job_id, file_id), children deduplicate viavisited - Paginated listings store
page_tokenin the task, so retries resume mid-directory
5. Rate Limiting and Retries
Distributed token bucket in Redis:
- Maintain one bucket per account and one global bucket
- Use a Lua script to atomically refill and consume tokens
- Workers must acquire a token from both buckets before calling the storage API
Backpressure:
- On
429 Too Many RequestsorRetry-Afterheader, set a cooldown key in Redis so all workers respect the backoff, not just the one that received the error - If no tokens available, re-enqueue the task with a delay instead of blocking the worker thread
Retry strategy:
- Exponential backoff with jitter: 1s base, 5min cap, for transient errors (429, 5xx, timeout)
- Increment
attempt_countper task; after 5 attempts move to dead-letter queue and log partial failure - On permanent errors (403, 404), skip the task and continue (don't fail entire job)
Circuit breaker per storage provider endpoint to fast-fail during outages.
6. Key Trade-offs
Queue technology:
- SQS: Simple visibility timeouts, but limited throughput per queue
- Kafka: High throughput, but partition ordering complicates per-message retries
- Database queue: Transactional guarantees with
SELECT FOR UPDATE SKIP LOCKED, but lower scale
Task granularity:
- One directory per task keeps tasks small and retries cheap
- Batching multiple directories per task reduces queue overhead but increases retry cost
Results storage:
- Write-optimized store (DynamoDB, Cassandra) for incremental inserts during traversal
- Batch append to S3 every N files if query latency during traversal isn't required
Consistency:
- The storage account may change during traversal (files added/deleted)
- Accept eventual consistency: results reflect a point-in-time snapshot, possibly with slight drift
- Document this behavior for clients
Common Mistakes
- Attempting synchronous recursion in the HTTP handler (timeouts, no parallelism, lost state on crash)
- Using paths instead of stable IDs for cycle detection (misses symlinks and bind mounts)
- Sleeping in the worker on rate limit instead of re-enqueueing (wastes worker capacity)
- Not deduplicating child enqueues (cycles cause infinite work)
- Forgetting pagination tokens (retries restart large directories from the beginning)
Complexity Estimate
- Per-job latency: Dominated by rate limits, ~2 hours for 10M files at 15 req/sec
- Throughput: Scales horizontally; 5,000 concurrent jobs feasible with sufficient worker and queue capacity
- Worker utilization: High when rate limits allow; auto-scale based on queue depth