Skip to main content

File Storage System

1. Executive Summary​

A file storage system provides durable, hierarchical namespace semantics (files and directories) backed by scalable blob storage, serving applications that need POSIX-like or API-driven file operations without managing raw disks. Principal-level design covers metadata separation from content, chunking large files, consistency models for directory operations, multi-tenancy, quota enforcement, and garbage collection of orphaned blobs.

This chapter designs a cloud file API serving billions of files and exabytes of content with 99.999999999% (11 nines) durability for blobs and 99.99% availability for metadata operations. Metadata in a distributed SQL or key-value store, content in object storage with erasure coding, and explicit behavior during partial upload failure are core interview topics.

2. Why This Topic Matters​

File storage underlies backup products, content management, ML datasets, and internal developer platforms. Architects must explain:

  • Metadata vs. blob separation and why mixing them fails at scale.
  • Listing performance at millions of files per directory.
  • Consistency for rename vs. read during concurrent writers.
  • Multipart upload lifecycle and orphan cleanup.
  • Access control at path granularity.

Poor design causes metadata hotspots, unbounded storage costs from abandoned uploads, and data loss during misconfigured replication. Review Storage Engine Fundamentals and Global File Transfer Platform for related patterns.

3. Problems Being Solved​

ProblemSolution
Durable blob storageObject store + replication/erasure coding
Hierarchical namespaceMetadata tree with parent pointers or materialized paths
Large filesChunking; multipart upload
Concurrent writersVersioning; optimistic locking
Quota / billingPer-tenant counters; async reconciliation
Fast metadata opsSharded metadata DB; avoid listing huge dirs
Access controlACL on inode; IAM integration
Deletion safetySoft delete; tombstone GC

4. Assumptions and System Model​

Functional:

  • Create/read/update/delete files and directories.
  • List directory contents with pagination.
  • Multipart upload for files > 5 MB.
  • Optional versioning and snapshots.
  • Presigned URLs for direct client↔blob transfer.

Non-functional:

  • Metadata ops p99 < 100 ms.
  • Throughput: 100K metadata ops/sec; 1 TB/sec aggregate blob bandwidth.
  • Durability 11 nines for committed blobs.
  • Max file size 5 TB; max path length 1024 chars.
AssumptionImplication
Small metadata, large blobsNever store file bytes in metadata DB
Read-heavyCache metadata; CDN for public blobs
Directories can be hugePagination mandatory; no full list in memory
Eventual blob GCTombstones + sweeper job
Multi-tenantShard by tenant_id

5. Essential Terminology​

TermDefinition
InodeMetadata record for file or directory
Blob / objectContent bytes in object store
ChunkFixed-size piece of large file
Multipart uploadUpload parts in parallel; commit manifest
ManifestOrdered list of chunk IDs and hashes
TombstoneDeleted marker pending GC
Erasure codingParity shards for storage efficiency
Presigned URLTime-limited direct storage access
Materialized pathFull path string as key
Copy-on-writeSnapshot without duplicating data
Quota hard limitReject writes when exceeded

6. Core Mechanism​

6.1 High-Level Architecture​

Figure 1: Metadata service orchestrates namespace; blobs stored directly in object tier.

6.2 APIs​

POST /v1/files { path, size } → { file_id, upload_urls[] }
PUT /v1/files/{id}/parts/{n} (or direct to presigned URL)
POST /v1/files/{id}/commit { parts: [{n, etag, hash}] }
GET /v1/files/{id}/download → redirect or presigned URL
GET /v1/dirs/{path}?cursor=... → paginated listing
DELETE /v1/files/{id}
POST /v1/dirs { path }

6.3 Data Model​

Inode table (sharded by tenant_id):

inode_id, tenant_id, parent_id, name, type(file|dir),
size, version, created_at, modified_at, blob_manifest_id,
acl_id, deleted_at

Blob manifest:

manifest_id → [{ chunk_id, offset, size, sha256 }]

Multipart session:

upload_id, inode_id, parts_completed[], expires_at

Unique constraint: (parent_id, name, tenant_id) where deleted_at IS NULL.

6.4 Deep Dives​

Upload flow:

  1. Client requests create file; metadata service allocates inode + upload_id.
  2. Returns presigned URLs per chunk (e.g., 64 MB parts).
  3. Client uploads parts in parallel directly to object store.
  4. Client commits with part ETags/hashes.
  5. Metadata service validates completeness, writes manifest, marks file committed.
  6. Quota counter incremented asynchronously.

Figure 2: Multipart upload with direct client-to-object transfer.

Directory listing at scale:

  • Never SELECT * without limit; cursor-based pagination (inode_id > cursor).
  • For >10K children: warn in API; consider subfolder policy.
  • Cache directory listing first page in Redis with short TTL.

Garbage collection:

  • Delete sets deleted_at; blobs referenced until manifest unlinked.
  • Sweeper scans tombstoned inodes after retention window.
  • Reference-count chunks; delete from object store when count=0.
  • Orphan multipart uploads expire after 7 days.

Figure 3: Tombstone → retention → reference-counted blob purge.

7. Step-by-Step Walkthrough​

7.1 Small file upload​

  1. Client POST 2 MB file via single PUT presigned URL.
  2. Commit with one part hash.
  3. Metadata updated; download available in 50 ms.

7.2 Concurrent rename​

  1. User A renames /docs/report.pdf → /archive/report.pdf.
  2. User B lists /docs/ during rename.
  3. Serializable transaction or per-parent lock ensures B sees consistent state.
  4. B either sees old name or not—never duplicate.

7.3 Abandoned multipart​

  1. Client uploads 3 of 10 parts; crashes.
  2. Upload session expires after 7 days.
  3. GC deletes orphan parts; no inode committed.

7.5 Cross-region read after metadata failover​

  1. Primary metadata region us-east-1 fails over to us-west-2 read replica promoted in 60s.
  2. In-flight multipart commits in ambiguous state—clients retry commit with same upload_id (idempotent).
  3. Presigned URLs issued before failover remain valid (object store regional).
  4. RPO for metadata: seconds of writes if sync replication; minutes if async—document in SLA.

7.6 Enterprise dedicated shard migration​

  1. Tenant acme exceeds 50K ops/sec on shared shard—noisy neighbor.
  2. Migrate inode range to dedicated shard online: dual-write period, cutover read path, verify checksum sample.
  3. Zero downtime if dual-read during migration—same pattern as cache rebalance in Distributed Cache Design.

7B. Extended Performance Modeling​

Metadata write path:
AuthZ: 3 ms
DB insert inode: 8 ms
Cache invalidate: 2 ms
Total p50: ~15 ms

Blob upload path (bypasses API for bytes):
Presign: 10 ms
64 MB part PUT: 500 ms–2s (network bound)
Commit: 20 ms

GC throughput target:
1B tombstones × 1% scan/day = 10M inodes/day
~115 inodes/sec per GC worker × 100 workers = 11.5K/sec → ~24 days full scan
Tune scan rate vs storage reclamation urgency

Principal architects set GC SLO same as user-facing APIs—unbounded orphans are deferred outages.

PhaseKey decisions
Requirementshierarchical NS, multipart, 11-nine durability
Scalemetadata sharded; blob in object store
APIspresigned direct upload
Datainode + manifest separation
Reliabilitycommit validation; GC
Securitypath ACL; tenant isolation

8. Invariants and Guarantees​

PropertyGuarantee
Committed fileAll chunks present with valid hashes
Namespace uniquenessOne active name per parent per tenant
DurabilityCommitted blobs replicated per policy
List consistencyPaginated snapshot per request
DeleteFile invisible after delete API returns

9. Failure Scenarios​

ScenarioMitigation
Partial commitTransaction; no inode until all parts verified
Metadata DB partitionFail writes; reads from replica if consistent
Object store outageQueue commits; retry
Hot directoryShard listings; rate limit
GC bug deleting live blobReference counting; dry-run mode
Split-brain metadataLeader election; fencing tokens

10. Performance Characteristics​

1B files metadata ≈ 500 bytes/inode → 500 GB metadata (sharded)
100K metadata ops/sec → 50+ DB shards with connection pooling
Blob bandwidth 1 TB/sec → parallel object store partitions
Listing p99: 20–80 ms with index on (parent_id, name)

11. Scalability Limits​

LimitMitigation
Single directory millions of filesPagination; subfolder policy
Metadata hotspot tenantDedicated shard
Manifest size huge fileChunk size tuning
GC backlogParallel sweeper workers

12. Operational Considerations​

  • Metrics: metadata QPS, upload success rate, GC lag, quota violations.
  • Alerts: orphan part growth; commit failure spike.
  • Runbooks: restore from backup; emergency read-only mode.
  • Chaos test: object store regional failure.

13. Security Considerations​

  • AuthZ on every metadata and presigned URL generation.
  • Presigned URLs short TTL; bound to content-hash where possible.
  • Tenant isolation in shard keys and ACL checks.
  • Encryption at rest (SSE-KMS) and in transit (TLS).
  • Audit log for admin access and cross-tenant operations.

14. Cost Considerations​

Object storage cheap; metadata DB and API tier dominate ops cost. Lifecycle policies move cold blobs to archive tier. Erasure coding vs replication: EC saves ~50% storage at CPU cost. Chargeback per tenant using metered storage + API calls.

15. Production Implementations​

SystemNotes
Amazon S3Object store; not hierarchical—apps add metadata
Google Cloud StorageSimilar; uniform bucket-level access
Azure Blob StorageHierarchical namespace option on ADLS Gen2
CephFSUnified metadata + object via Ceph
HDFSNameNode metadata + DataNode blocks

16. Alternatives and Tradeoffs​

ApproachProsCons
Metadata DB + object storeIndustry standardTwo systems to operate
POSIX on block storageFamiliarHard to scale horizontally
Flat object keys onlySimpleNo real directories
Copy-on-write FSSnapshots nativeComplex implementation
Strong listing consistencyPredictableHigher metadata latency

17. Common Misconceptions​

MisconceptionReality
"Store files in PostgreSQL BYTEA"Does not scale past GB
"S3 has folders"Prefix simulation only
"Delete is immediate free space"GC async
"Unlimited directory size"Listing degrades
"Presigned URL skips auth"Auth at issuance time

18. Principal Architect Perspective​

  • Metadata is the bottleneck—design shards and pagination first.
  • Multipart commit is a transaction—half-committed files corrupt trust.
  • GC is production code—not a background afterthought.
  • Quota enforcement needs async reconciliation for accuracy.
  • 11 nines requires cross-region replication policy explicit in design.

19. Architecture Review Exercise​

Scenario: File bytes stored in MySQL BLOB column; 500 GB database; backups failing.

Review: Migrate to object store + inode metadata; presigned uploads; chunked transfer.

20. Whiteboard Explanation​

"Metadata service owns the namespace in a sharded SQL store—inode per file with parent pointer and manifest reference. File bytes never touch the DB; clients upload chunks via presigned URLs to object storage, then commit a manifest. Deletes tombstone inodes; GC workers decrement chunk reference counts and purge unreferenced blobs. Directory listings are always paginated. ACLs checked on every operation. Multipart sessions expire to prevent orphan storage leaks."

21. Interview Questions​

  1. Design file storage for 1B files. — Signals: metadata/blob split, sharding. Red flags: DB blobs.
  2. Upload 10 GB file? — Signals: multipart, presigned, parallel. Follow-up: commit atomicity.
  3. Directory with 1M files? — Signals: pagination, never full list.
  4. Delete file—when is space freed? — Signals: tombstone, GC, ref counting.
  5. Consistency for rename? — Signals: transaction or lock per parent.
  6. Durability 11 nines? — Signals: cross-AZ/region replication, erasure coding.
  7. Quota enforcement? — Signals: counter + reconcile; reject on commit.
  8. Presigned URL security? — Signals: short TTL, scoped permissions.
  9. Versioning design? — Signals: new manifest; copy-on-write chunks.
  10. Hot tenant shard? — Signals: dedicated shard; rate limits.
  11. Orphan multipart cleanup? — Signals: expiry sweeper.
  12. List vs search? — Signals: listing is prefix of path; search needs index.
  13. Snapshot without copying data? — Signals: COW manifests.
  14. Metadata cache invalidation? — Signals: delete on write; short TTL.

21B. Extended Interview Question Deep Dives​

Q15 (Principal): A tenant reports files "disappearing" after delete API returns 404 but storage bill unchanged for 60 days.

Strong signals: Explains tombstone + async GC; ref count decrement; retention before physical purge; billing uses logical meter vs physical free. Follow-up: How prove blob purged?—GC audit log + object store lifecycle metrics. Red flags: "Delete is immediate." Rubric: 5/5 if mentions billing lag vs GC lag distinction and compliance hold blocking purge.

Q16 (Principal): Design versioning for compliance—retain all overwrites 7 years.

Strong signals: New manifest per version; immutable blocks; lifecycle to glacier; list versions API; delete creates delete marker not purge. Tradeoff: Storage cost 10×—legal holds override lifecycle. Link Global Object Store versioning semantics.

22. Interview Follow-Ups​

  1. POSIX compatibility layer on object store. — FUSE gateway; metadata latency.
  2. Cross-region replication. — Async metadata; conflict on concurrent writes.
  3. Encryption per-tenant keys. — KMS integration; key rotation.

22A. Production Low-Level Design (Interview + Game Day)​

Per Production LLD and Game Day Standard. Closely related to Global File Transfer §23.

C4 context​

Step-by-step flow:

StepInteractionExplanation
1–3Control planeNo file bytes in API
4Data planeDirect to object store
5–6Atomic commitVisible only when complete
7–8Read / GCRef-count safe delete

Production stack​

LayerAWS / genericPurpose
APIAPI GW + ECSMetadata + authz
MetadataAurora / Spanner-classinodes, manifests, sessions
BlobsS3Multipart; SSE-KMS
GCPeriodic workersOrphans + tombstones
ScanOptional AV hookQuarantine before READY
QuotaCounter + reconcilePer-tenant limits

API contract (snippet)​

POST /v1/files/uploads {"path":"/a/b.bin","size":53687091200,"part_size":67108864}
→ {"upload_id":"u…","parts":[{"index":0,"url":"https://…"},…]}

POST /v1/files/uploads/{id}/commit {"parts":[{"index":0,"etag":"…","sha256":"…"},…]}
→ {"file_id":"f…","status":"READY"}

Data model​

EntityKeyNotes
inode(tenant_id, file_id)path, size, status
manifest(file_id, part_index)etag/hash
upload_sessionupload_idTTL; state
blob_refsobject_keyref count

Happy-path sequence​

Failure / partial upload​

SLOs (one-liner)​

SLOTargetHow achieved
Metadata p99< 100 msSharded DB; no byte proxy
Commit integrity0 silent corruptHash verify
Orphan storageGC lag < 24 hSweeper + alert
Durability blobs11 nines classObject store EC/repl

22B. Game Day Playbooks​

Catalog​

#DrillFrequencySLO
GD-1Kill client at 50% of 50 GBMonthlyResume / no visible file
GD-2Commit hash mismatchQuarterlyFAILED; no READY
GD-3Orphan part floodQuarterlyGC lag SLO
GD-4Hot directory listQuarterlyPagination enforced
GD-5Quota raceSemi-annualHard limit at commit
GD-6Cross-tenant path probeAnnualAuthz deny

GD-1 — Mid-upload failure​

GD-2 — Bad commit​

Pass criteria: Zero READY files without verified manifest; GC cleans parts.

23. Strong Answer Example​

Question: "How do you upload a 50 GB file reliably?"

Answer this as a 45-minute design discussion using the PRACTICE framework. Strong students separate metadata vs blobs, use presigned multipart, and commit only after hash verify—not “stream 50 GB through the API pod.”

Figure A: PRACTICE map — walk the board in this order.


Student interview script (PRACTICE)​

P — Problem framing​

"A 50 GB single-stream PUT through the API is fragile and expensive. Need multipart, direct-to-object-store, and a commit that makes the file visible only when all parts verify.

Short answer: Create upload session → client PUTs ~64 MB parts via presigned URLs → Commit with ordered etags/hashes → metadata txn marks READY. Failures leave no user-visible file; GC reaps orphans after TTL."

R — Requirements​

Hierarchical namespace; multipart; download presign; quota; soft delete + GC.

A — Assumptions​

Object store multipart/compose; metadata is source of truth for namespace; bytes never on API disk.

C — Capacity​

50 GB ÷ 64 MB ≈ 800 parts
Metadata: session + 800 manifest rows — fine
API CPU: auth + commit only

T — Topology​

Metadata API + DB; client ↔ object store; GC workers.

I — Invariants​

No READY without full verified manifest; ref-count before blob purge; tenant in shard key.

C — Constraints​

Flaky WAN → resume; listing must paginate; legal hold blocks GC.

E — Evolution​

Single PUT small files → multipart → resume → AV quarantine → multi-region metadata.

Closing line:

"50 GB upload = presigned parts + hash-verified commit + orphan GC; metadata plane never streams the file."

Scoring signals​

StrongWeak
Control vs data planeNFS single box
Commit atomicityVisible partial files
GC / ref-countIgnore orphan cost

Compact outline​

"Create session → presigned 64 MB parts → commit+verify → READY; TTL GC orphans; quota at commit."

24. Weak Answer Example​

Weak: "Use a single NFS server."

Red flags: No scale, no cloud durability model, no multipart, no multi-tenant isolation.

25. Hands-On Exercise​

  1. Implement inode + manifest schema with multipart commit.
  2. Simulate orphan part GC after expired upload.
  3. Paginated directory listing benchmark at 1M entries.
  4. Reference-counted chunk deletion on file remove.
  5. Extension: Presigned URL generator with TTL and ACL scope.

26. Knowledge Check​

  1. Why separate metadata and blobs?
  2. Three steps of multipart commit?
  3. When is a blob safe to delete?
  4. How prevent hot directory listing?

27. Flashcards​

FrontBack
InodeFile metadata record without bytes
ManifestOrdered chunk list for a file
TombstoneSoft-deleted inode pending GC
Presigned URLDirect timed access to object store
Ref countingTrack chunk usage before purge
MultipartParallel chunked upload protocol
Materialized pathFull path as lookup key
Erasure codingParity-based durable storage
Quota reconcileAsync fix counter drift
Pagination cursorStable large directory listing

28. Cheat Sheet​

REQUIREMENTS: hierarchical files, multipart, 11-nine blobs
SCALE: sharded metadata; object store for bytes
APIs: create/commit/download/list/delete
DATA: inode table + manifest + upload sessions
ARCH: API → metadata DB; client → object direct
DEEP: commit txn; GC ref count; paginated list
RELIABILITY: hash verify; replica; orphan sweeper
SECURITY: ACL; presigned TTL; tenant shard
OPS: GC lag; quota alerts; backup metadata

17A. Failure Scenario Drill​

Deploy enables public list on bucket metadata API without pagination—attacker enumerates 10M paths; metadata DB CPU saturates; legitimate uploads fail. Mitigation: mandatory pagination max 1000; rate limit per API key; WAF on abnormal list QPS. Principal owns API abuse review same as storage durability review.

18.1 When Principal Escalates File Storage Design​

Escalate when: (1) file bytes stored in relational DB; (2) no multipart commit atomicity; (3) GC not implemented—storage cost grows unbounded; (4) cross-tenant path collision possible without tenant prefix in shard key. These precede data loss or compliance incidents.

19A. Extended Review Scenario​

Scenario B: Versioning disabled; user overwrites payroll.csv; no recovery.

Review: Enable object versioning or file rev history; soft delete with 30d retention; audit who issued overwrite API.

21A. Additional Interview Questions​

  1. Cross-region read after write? — Signals: primary region metadata; async replica lag disclosed. Red flags: claim instant global consistency.
  2. Compare to Dropbox block model. — Signals: this chapter is namespace + blob; Dropbox adds sync—see Dropbox Design.

23B. Extended Follow-Ups​

  1. Legal hold on delete. — Tombstone blocks GC until hold released; compliance audit trail.
  2. Antivirus scan pipeline. — Async scan before marking file READY; quarantine infected uploads.

23A. Additional Strong Answer​

Q: How enforce per-tenant 10 TB quota accurately?

Outline: Fast path: atomic counter increment on commit (approximate). Slow path: nightly reconciliation scan summing manifest sizes vs counter; alert drift > 1%. Hard reject on commit if counter ≥ limit even if reconciliation lags—may temporarily over-block by small margin vs under-block which is worse for billing.

28A. Principal Interview Deep Dive​

Multipart part size selection​

Part sizeTradeoff
5 MBMore parts for large files; more commit metadata
64 MBFewer API calls; memory buffer on client
256 MBHigh memory; fewer parts; good on datacenter links

Default 64 MB for files > 100 MB; single PUT for smaller.

Metadata shard key design​

Shard by hash(tenant_id) not hash(path)—keeps tenant data colocated for quota and ACL cache locality. Cross-tenant hot path isolation: noisy neighbor tenant on dedicated shard if enterprise contract.

Read path latency breakdown​

Stepp99
AuthZ + metadata lookup10–30 ms
Presigned URL generation5 ms
Client direct GET from object store50–200 ms by size

Optimize metadata; never proxy bytes through API tier at scale.

28B. Extended BOE Walkthrough​

Interviewer: "1 billion files, 100K metadata ops per second."

Strong candidate:

"1B inodes × 500 bytes ≈ 500 GB metadata—sharded SQL or distributed KV, say 50 shards × 2K ops/sec each with headroom.

Blobs in object store—never in DB. Upload: presigned multipart; commit transactional on inode + manifest. Delete: tombstone + async GC with ref counting.

List directory: cursor pagination only—never load 1M children. Quota per tenant with reconcile job.

Durability: object store 11 nines; metadata 3× replicated. Link Global Object Store for blob tier details."

30. References​

  • Ghemawat, Gobioff, Leung — Google File System paper.
  • Amazon S3 documentation — multipart upload specification.
  • Kleppmann, DDIA — storage and replication chapters.

Distinction: GFS paper describes Google's implementation; S3 API is de facto cloud standard.

30A. Further Reading Paths​

Apply blob patterns in Global Object Store. Contrast namespace sync needs with Dropbox Design. Lab: implement multipart commit with hash verification and measure orphan part storage without GC.

30B. Capacity Planning Worked Example​

Tenant count: 10,000
Avg files per tenant: 100,000
Total inodes: 1B
Inode row size: 512 bytes
Metadata storage: ~512 GB (+ indexes ~40% → 720 GB)
Object storage: 1B × 2 MB avg = 2 EB (dominant cost)

Metadata ops: 100K/sec → 50 shards × 2K ops with replicas
API tier: stateless autoscaled on CPU
GC workers: 1% of blob storage scanned daily for orphan detection

30D. Principal Architecture Review Checklist​

Before production launch of file storage API, verify:

  • Multipart commit is atomic—no visible inode until all part hashes verified
  • Presigned URL TTL ≤ 15 minutes for upload; scoped to upload_id
  • Directory list API enforces max page size 1000 with mandatory cursor
  • GC sweeper running with lag alert < 24h
  • Quota hard limit tested at commit boundary—not only soft warnings
  • Cross-tenant inode isolation via shard key includes tenant_id
  • Load test: cache bypass on metadata (no CDN for inode ops) at 2× peak QPS
  • DR drill: metadata restore RTO documented; blob store CRR RPO aligned with business

Missing any item is a release blocker for principal sign-off—not post-launch backlog.