Design a Multi-Tenant Namespace File Storage Service
System DesignModel answerLast updated
Design a production file storage system with hierarchical namespaces, per-directory capacity limits, atomic duplicate renaming, and petabyte-scale content storage.
Scenario
You are the founding engineer at a legal document platform that needs to store files on behalf of thousands of enterprise customers. The product team has locked in two core API operations and a set of behavioral guarantees. Your job is to design the full system — from the API surface down to the bytes on disk.
API Semantics
addFile(path: String) → finalPath: String
The path looks like "contracts/2024/acme/nda.pdf". The call must:
- Create any missing intermediate directories in a single atomic operation.
- Store the file at the leaf position.
- Return the path that was actually used, which may differ from the input due to renaming.
list(path: String) → Entry[]
Returns only the immediate children of the given directory, not a recursive listing.
Constraints and Behavioral Rules
- Each directory may hold at most 5 entries, counting both files and subdirectories toward the limit.
- An
addFilethat would breach the limit at any point along the path — including intermediate directories that need to be created — must be rejected entirely. No partial writes are acceptable. - If the leaf directory already contains a file or folder with the requested name, auto-rename the incoming file using OS-style numeric suffixes:
report.pdf → report (1).pdf → report (2).pdf. Renaming does not exempt a file from the capacity check. - If the incoming name itself already carries a suffix like
report (1).pdfand that name is also taken, find the next available number rather than nesting suffixes likereport (1) (1).pdf.
What to Cover
Walk through your design in each of the following areas. Be concrete about trade-offs — where you have a choice, say which option you would pick and why.
- Overall architecture — identify the major components and how they interact.
- Metadata schema and store choice — relational vs. NoSQL, schema layout, indexing strategy.
- Concurrency control — how you enforce the 5-entry cap and the rename logic atomically when multiple clients write to the same directory simultaneously.
- Transaction boundaries and idempotency — where the commit point is, what happens on retry, and how bytes and metadata stay in sync.
- Content storage — content-addressed vs. location-addressed keys, how large files are uploaded (streaming, resumable), and how the object storage layer relates to the metadata layer.
- Consistency and failure modes — what can go wrong at each step and how the system recovers.
- Scalability — partitioning strategy, sharding keys, caching approach.
- Observability and rate limiting — key metrics, SLIs/SLOs, per-tenant quota enforcement.
- Data lifecycle — versioning, soft deletion, garbage collection of orphaned blobs.
- Security — authentication, authorization, path traversal prevention, encryption.
Assumed Scale
Design for roughly 10,000 tenants, 5 billion file nodes, 2,000 writes/second average with 20,000 reads/second at peak, files between 1 KB and 5 GB with a ~1 MB median, and total stored data in the petabyte range.
Hints
Hint 1
Start with the hardest correctness requirement: the 5-entry cap must hold even when two clients try to add a file to the same directory at the same millisecond. Which consistency primitive does your store need to provide, and what does that rule out?
Hint 2
The rename logic and the capacity check are not independent. Sketch out the exact sequence of operations inside one transaction — what rows you lock, in what order, and why that order prevents deadlocks across concurrent writers.
Hint 3
Metadata and bytes live in separate systems. Identify the exact commit point that makes a file visible to readers, then reason about what happens to the uploaded bytes if that commit never arrives.
Model answer
Hard Try it yourself first — then compare your approach, complexity and edge cases.
1. Clarify Requirements Before Drawing Anything
Restate the invariants out loud before touching architecture. The two non-negotiable properties are:
- All-or-nothing path creation. Creating
a/b/c.txtwhereaexists butbdoes not must atomically createbandc.txtor fail. A partial write that createsbbut then hits a capacity error onbis unacceptable. - Serialized writes per directory. Capacity enforcement and rename selection are both read-then-write operations. If two clients race on the same directory, exactly one must win the slot; the other must either get the next rename index or get a 409.
Everything else is downstream of those two constraints.
2. Architecture Overview
Five components:
| Layer | Responsibility |
|---|---|
| API gateway | TLS, authentication, per-tenant rate limiting, request normalization |
| Metadata service | Stateless app servers; path parsing, transaction orchestration, rename logic |
| Metadata store | Relational DB (Postgres sharded by tenant, or Spanner for global scale) |
| Content store | Object storage (S3/GCS); clients upload directly via presigned URLs |
| Async workers | Orphan GC, virus/DLP scanning, lifecycle expiry, quota aggregation |
The deliberate split between metadata (relational, strongly consistent, small rows) and content (object storage, cheap bytes, eventually consistent) is the central architectural decision. It lets each layer scale independently.
3. Metadata Schema and Store Choice
Use a relational database. The core invariants span multiple rows ("≤5 children of this parent", "no two siblings share a name"), which requires multi-row transactions with row-level locking. A typical NoSQL store would require application-side conditional writes and distributed locking — complexity you can avoid entirely with Postgres.
nodes(
tenant_id UUID,
node_id UUID PRIMARY KEY,
parent_id UUID REFERENCES nodes(node_id),
name TEXT NOT NULL, -- NFC-normalized
type ENUM('dir','file'),
child_count INT DEFAULT 0, -- maintained on dirs
size BIGINT,
blob_hash TEXT,
version INT DEFAULT 1,
created_at TIMESTAMPTZ,
deleted_at TIMESTAMPTZ,
UNIQUE (tenant_id, parent_id, name) WHERE deleted_at IS NULL,
CHECK (child_count BETWEEN 0 AND 5)
)
file_versions(node_id, version, blob_hash, size, created_by, created_at)
blobs(tenant_id, hash PRIMARY KEY, size, storage_key, refcount, state)
idempotency(tenant_id, key PRIMARY KEY, request_hash, response, expires_at)
upload_sessions(upload_id, tenant_id, path, sha256, size, state, expires_at)
The CHECK on child_count and the UNIQUE index are database-level backstops — they reject violations even if application code has a bug.
Shard by tenant_id. Most cross-row operations are scoped to a single tenant, so this avoids cross-shard transactions in the common case.
4. Atomic Capacity Enforcement and Rename
This is the most important part of the design. Run a single serializable transaction per addFile commit:
Step 1 — Resolve and lock the path top-down.
Walk from root to leaf. For each existing directory, acquire a SELECT … FOR UPDATE lock. Always lock from root toward leaf; this consistent ordering prevents deadlocks between concurrent writers.
Step 2 — Create missing intermediate directories. For each missing directory, verify its parent has room:
UPDATE nodes SET child_count = child_count + 1
WHERE node_id = ? AND child_count < 5
Zero rows affected means the directory is full. Roll back immediately and return 409 DIRECTORY_FULL with the offending path. Insert the new directory row in the same statement batch.
Step 3 — Select the final filename.
Under the leaf directory lock, read the current sibling names. Apply the rename algorithm (described below). Check that the chosen name fits within the capacity limit. Insert the file node and a file_versions row, increment blobs.refcount.
Step 4 — Write the idempotency record and commit.
Because locks are held top-down, two writers racing on the same directory serialize naturally. Writers to different directories are unaffected.
Rename algorithm (runs inside the transaction, sibling set is frozen):
- Split the name into
stemandextat the last dot. Dotfiles like.envhave no extension. - Check whether the stem already ends with
(N)using^(.*) \((\d+)\)$. If so, strip the suffix to get the base stem. - If the requested name is free, use it exactly — even if it literally is
report (1).pdf. - Otherwise, scan
n = 1, 2, 3, …for the smallest freebase_stem (n).ext. With a cap of 5 siblings this is at most 4 iterations.
This avoids the nesting trap: adding report (1).pdf when report (1).pdf already exists produces report (2).pdf, not report (1) (1).pdf.
5. Content Storage and Large Files
Use content-addressed keys scoped per tenant: tenants/{tid}/blobs/{sha256}.
Scoping per tenant avoids a cross-tenant dedup side channel (a tenant should not be able to infer whether another tenant holds a given file). It also supports per-tenant encryption keys. Renaming or moving a file is metadata-only — the blob key never changes.
For large files, use a multipart resumable upload pattern:
POST /v1/files:initiate {path, size, sha256} Idempotency-Key → {uploadId, partUrls[]}
PUT <presigned-part-url> (client → object store directly, 8–64 MB parts)
POST /v1/files:commit {uploadId, etags[]} Idempotency-Key → {finalPath, nodeId}
The metadata commit only runs after the object store confirms all parts and the server verifies the assembled SHA-256 matches the declared hash. Never write a metadata row pointing at bytes that have not been verified.
Orphan GC: If a commit never arrives (client crashed), the blob stays in state=pending. A background worker deletes blobs with refcount=0 that are older than 24 hours.
6. Consistency and Failure Modes
| Failure point | Behavior |
|---|---|
| Client crashes mid-upload | Blob never committed; GC reclaims it after 24h |
| Commit transaction fails | Rolled back atomically; blob unreferenced; client retries with same idempotency key |
| DB node fails during commit | Transaction aborted by DB; client gets 503 and retries |
| Duplicate commit retry | Idempotency record returns stored finalPath without re-running logic |
A retried commit without idempotency would silently allocate a second rename slot. Write the idempotency record inside the same transaction as the node insert; they are atomic together.
7. Scalability
- Shard the metadata store by
tenant_id. Most operations are tenant-scoped. - Cache directory listings in Redis with a short TTL (5–10 seconds). Invalidate on write. This absorbs the read skew without requiring strong read consistency on every
listcall. - Partition the nodes table by
(tenant_id, parent_id)within a shard to keep range scans on a single leaf page. - For very hot directories (a shared inbox pattern), funnel writes through a per-directory queue to serialize them without holding DB row locks for long.
8. Observability and Rate Limiting
Key SLIs:
addFilep99 latency < 500 ms (excluding upload time)listp99 latency < 50 ms- Metadata write availability > 99.95%
- Orphan blob GC lag < 48 hours
Per-tenant rate limits enforced at the gateway (token bucket, limits stored in Redis). Per-tenant storage quotas tracked by the async aggregation worker, checked at initiate time.
9. Lifecycle and Security
Lifecycle: Soft-delete sets deleted_at; a configurable retention window (default 30 days) precedes hard delete. Versioning is stored in file_versions; old versions can be pruned by policy. blobs.refcount reaches zero only when all versions referencing a hash are purged.
Security:
- Authenticate at the gateway with short-lived JWTs.
- Authorize each operation against a tenant-scoped permission model before the transaction begins.
- Normalize all paths server-side (collapse
.., strip leading/, NFC-normalize Unicode). Never pass user-supplied path strings to the object store key — derive storage keys fromnode_idandblob_hashonly. This eliminates path traversal at the storage layer by construction. - Encrypt data in transit (TLS 1.3) and at rest (AES-256, per-tenant key in KMS).
Common Mistakes to Avoid
- Checking capacity before locking, then inserting separately. This is a classic TOCTOU race. The check and increment must be one atomic
UPDATE … WHERE child_count < 5. - Locking rows in arbitrary order. Two transactions each waiting for a lock the other holds will deadlock. Top-down consistent ordering prevents this.
- Committing metadata before bytes are verified. Readers could dereference a blob that does not yet exist or has a mismatched hash.
- Skipping the idempotency record. A retried network call after a successful but unacknowledged commit will silently consume a second directory slot and produce a spurious rename.