Multi-Tenant File Vault with Per-User Limits and Compression
System DesignModel answerLast updated
Design a multi-user file storage backend that handles uploads, downloads and copies, enforces per-user space limits, and transparently compresses data, with durability, security and testing covered.
Build a Multi-Tenant File Vault
You are asked to design the backend for a file storage product shared by many customers. Each customer has a storage allowance determined by their plan. Walk through your design as you would in a system design discussion.
What the service must do
- File operations. Users can upload new files, download them, and duplicate them. Define the API surface. Explain what "duplicate" means in your system (a server-side reference copy, a full physical copy, or copy-on-write), and say how metadata and sharing permissions behave on the new file.
- Users and allowances. Operators can create users and assign each a plan with a maximum amount of storage. Explain how usage is measured, how the limit is enforced when an upload starts or finishes, and how duplicates and compressed data are counted.
- Compression. Files are compressed when stored and restored when read. Choose algorithms, decide where in the data path compression happens, say where the compression details are recorded, and discuss the trade-off between CPU, latency and space saved.
- Reliability and scale. Address durability, availability, horizontal scaling and consistency. Describe the main components (blob storage, metadata service, indexes), how data is partitioned and replicated, which background jobs exist, and how the system recovers from failures.
- Security and operations. Cover authentication, authorization and access control lists, audit logging, file versioning, and monitoring. Propose the API methods for each feature and outline how you would test the system.
What is expected
- State your assumptions about scale (users, file counts, sizes, request rates) before designing.
- Provide an API sketch, a data model, and a component diagram or description.
- Justify key decisions and call out trade-offs and failure modes.
- Finish with a test strategy.
Hints
Hint 1
Split files into immutable chunks identified by a content hash. This makes copies cheap (just new references), enables integrity checks, and makes compression decisions per chunk.
Hint 2
Decide what you charge users for: logical (uncompressed) bytes give predictable numbers, while physical bytes leak information about other users' data. Then use an atomic conditional update on a per-user counter, with a reservation at upload start and a settle step at completion.
Hint 3
Keep file bytes out of the metadata tier. Use a transactional, sharded metadata store for namespaces, versions, quotas and reference counts, and an immutable, erasure-coded blob store underneath. Add background jobs for garbage collection, scrubbing, quota reconciliation and recompression of cold data.
Model answer
Hard Try it yourself first — then compare your approach, complexity and edge cases.
1. Scope and assumptions
Functional: upload, download, copy; plans with limits (for example Free 5 GB, Pro 1 TB, Enterprise custom); transparent compression; versioning; ACL-based sharing; audit trail.
Non-functional: 11-nines durability, 99.9% availability, read-after-write consistency for metadata, and quota overshoot bounded by one in-flight upload.
Scale to state aloud: 50M users, 5B files, 2 MB average (about 10 PB logical). Roughly 50k reads/s and 5k writes/s, with metadata calls about 10x data calls. At about 1 KB of metadata per file, metadata is around 5 TB: it must be sharded, but it is tiny next to the data.
2. API sketch
POST /v1/users {user_id, plan} -> {limit_bytes}
GET /v1/users/{id}/usage -> {used, reserved, limit}
POST /v1/uploads {path, size, type} -> {upload_id, part_urls}
PUT /v1/uploads/{id}/parts/{n} -> {etag}
POST /v1/uploads/{id}:complete {parts, checksum} -> {file_id, version}
GET /v1/files/{id}?version=&range= -> bytes (decompressed)
POST /v1/files/{id}:copy {dest_path, mode} -> {new_file_id}
DELETE /v1/files/{id}?version=
PUT /v1/files/{id}/acl {grants}
GET /v1/files/{id}/versions
GET /v1/audit?resource=&from=&to=
Multipart, resumable uploads let us reserve quota early and retry parts. All mutating calls accept an idempotency key.
3. Data model
- User (sharded by user id): plan, limit, used, reserved, row version.
- File (sharded by owner id so listing and quota stay on one shard): file id, path, current version, ACL id, timestamps, deletion marker.
- FileVersion: logical size, content type, checksum, ordered manifest of chunk hashes.
- Chunk (content-addressed, sharded by hash): physical size, codec, level, uncompressed size, refcount, placement.
- ACL: grants of owner/editor/viewer to principals, optional inheritance.
Files are cut into 4-8 MB chunks keyed by the hash of their uncompressed bytes. That gives integrity checking, optional dedup and cheap copies.
4. Architecture
Client, then an API gateway (authentication, rate limiting), then upload/download services and a metadata service (sharded, transactional). Upload services compress chunks and write them to a multi-AZ, erasure-coded blob store. An event bus feeds background workers: garbage collection, scrubbing, quota reconciliation, audit sink and tiering.
File bytes never touch the metadata tier. The metadata service is the source of truth for namespaces, versions, quotas and refcounts. The blob store is immutable and supports only put, get and delete by hash.
5. Deep dives
Copy semantics
- Default: server-side copy-on-write. Create a new file and version whose manifest references the same chunks, and bump each chunk's refcount in one transaction. Cost is O(chunks) metadata work with no data movement. Since chunks are immutable, later edits create new chunks, which is the copy-on-write behaviour.
- Deep copy physically rewrites chunks, as an async job. Use it only when isolation is required, such as another region or encryption key.
- Propagation: content type, checksum and tags are copied. The ACL is not copied; the new file takes the destination folder's ACL and the copier becomes owner, which prevents leaking access to people who could see the source. Version history is not copied; the copy begins at v1.
Quota accounting
- Charge logical bytes. Users see predictable numbers, and savings from compression and dedup go to the provider. Charging physical bytes would make usage depend on compressibility and leak information about other tenants' data.
- Copies are charged in full to the destination owner. Otherwise a user could copy a large shared file for free and the original owner could later delete theirs. Old versions count unless the plan excludes them; provide a retention policy.
- Enforcement: at upload start, run a conditional update that adds the size to
reservedonly ifused + reserved + size <= limit. At completion, move the actual size fromreservedtoused. A TTL sweeper releases abandoned reservations (for example after 24 hours). Deletes decrementused; trash keeps counting until purged. - Hot counters: the counter is a single-row transaction on the user's shard. For large organisations with shared pools, split into sub-counters or lease quota blocks to upload servers. A nightly reconciler recomputes usage from versions and alerts on drift.
Compression
- Placement: per-chunk, server-side, in the upload service before blob write. Per-chunk compression keeps range reads cheap. Client-side compression is only an optional transport encoding because it cannot be trusted for accounting.
- Algorithms: zstd at a moderate level (around 3) as default; LZ4 for latency-sensitive hot data; a background job recompresses cold data (untouched 30+ days) at a high zstd level.
- Skip when useless: already-compressed types (images, video, archives), or when a trial on the first 64 KB saves under about 5%.
- Metadata: codec, level and uncompressed size are stored per chunk. The download service decompresses and streams; clients that advertise support can receive compressed chunks directly.
- Trade-off: roughly one CPU core per few hundred MB/s ingested and a few milliseconds per chunk, in exchange for lower storage, replication and network cost. Decompression is much faster than compression, so reads stay cheap.
Durability, availability, consistency
- Blob store: erasure coding (for example 10+4) across zones, with checksums verified on read and a background scrubber repairing bad shards.
- Metadata: consensus-replicated shards, giving strong consistency within a shard and read-after-write for a user's own namespace. Multi-chunk refcount updates happen in a transaction.
- Upload commit order: write chunks, then commit metadata. A crash in between leaves orphan chunks, which GC removes after a grace period. Never the reverse order.
- Garbage collection deletes chunks only when refcount is zero and a grace period has passed, to avoid racing with new references.
- Scale out by sharding metadata on owner and chunks on hash; stateless services scale behind load balancers.
Security, audit, versioning, monitoring
- OAuth/token authentication at the gateway; authorization checks against ACLs on every call; encryption in transit and at rest with per-tenant keys.
- Append-only audit events on every mutation and access change, shipped via the event bus to immutable storage.
- Each write creates a new version; retention policy prunes old ones.
- Monitor p99 latency, error rates, quota rejections, compression ratio, GC backlog, repair queue depth and reconciler drift.
6. Testing
- Unit tests for quota arithmetic and ACL resolution.
- Concurrency tests: many parallel uploads must never exceed the limit by more than one in-flight upload.
- Fault injection: crash between chunk write and metadata commit; lose a blob shard; partition a metadata replica.
- Round-trip tests across codecs, including incompressible and empty files, and range reads.
- Copy tests: refcounts, divergence after edit, delete of source leaving the copy intact.
- Property-based checks that reconciled usage equals the sum of version sizes.
Common mistakes
- Charging physical bytes, or not charging copies.
- Routing file bytes through the metadata database.
- Committing metadata before data is durable.
- Copying the source ACL onto the duplicate.
- Compressing everything, including already-compressed media.