logoNEURAL COOK
SearchAll PostsTagsNotesAuthor
logoNEURAL COOK

A posts created with Next.js and Tailwind.css

Explore

  • All posts
  • Notes
  • Snippets
  • Tags
  • RSS feed

Connect

instagramlinkedinmailgithub

© 2026 VIKI. All rights reserved.

Built with
Contents
Atomic CASGlobal Lock OrderingRead Write SynchronizationReadWriteLock vs synchronized vs ReentrantLock60-Day LLD & Machine Coding Mastery Roadmap
The Four Pillars of OOPComposition, Asociation & AggregationDatabase locking / atomic updates
Don't Repeat Yourself (DRY) PrincipleKeep it Simple, Stupid (KISS) PrincipleYou Aren't Gonna Need It (YAGNI) Principle
Design a Library Management System (LMS)Design a News FeedDesign a Parking LotDesign Thread-Safe Dropbox File Storage SystemDesign Tic Tac ToeDesing a Vending Machine
D : Dependency InversionI : The Interface Segregation PrincipleL : The Liskov Substitution PrincipleO : The Open/Closed PrincipleS : The Single Responsibility Principle
UML Activity Diagrams: Modeling Process and WorkflowUML Class Diagrams: Static Structure ModelingUML Sequence Diagrams: Modeling Dynamic InteractionsUse Case Diagrams: Functional Requirement Modeling
Low Level Design/problems

Design Thread-Safe Dropbox File Storage System

13 min read
On this pageCore requirements — must implement
Core requirements — must implementExtended requirements — discuss if time permitsNon-functional requirementsExplicit assumptionsSolutionEntitiesAPIsServicesSearch, listing, pagination, and indexesFailure tablePatterns: what they solve and what not to overuseTrade-offs to articulateCommon follow-ups and concise answers
Terminology
  • Logical file: stable identity, name, parent, owner, lifecycle state.
  • Version: immutable content snapshot of a logical file.
  • Manifest: ordered list of chunk hashes for one version.
  • Chunk: byte block stored by content hash; chunks may be deduplicated only when privacy policy permits it.
  • Resource: FILE or FOLDER, the target of a share or link.
  • Share: authenticated principal-to-resource grant.
  • Share link: bearer-token grant with independent restrictions.

This separation is essential: names, folders, ACLs, and version history are metadata; bytes live in object storage. Do not store a multi-GB file as one row, load it wholly into memory, or mutate a committed version in place.

# Core requirements — must implement

  • Users create folders; upload, rename, move, delete, restore, and download files.
  • A user shares a file or folder directly with another user at VIEW, COMMENT, or EDIT level.
  • Owners create, expire, password-protect, restrict, or revoke public links.
  • Large uploads resume after failure, verify chunks, and avoid duplicate finalization.

# Extended requirements — discuss if time permits

  • Files retain immutable versions and can restore an earlier version by creating a new current version.
  • Folder access is inherited by descendants; a direct grant can be more specific.
  • Connected devices obtain ordered changes and resolve edit conflicts deterministically.
  • Users list, search, paginate, view activity, and receive asynchronous notifications.

# Non-functional requirements

  • Authorization must use the latest committed grant/revocation for sensitive operations.
  • Metadata writes are atomic within their database transaction; bytes and asynchronous effects are eventually reconciled.
  • Content is streamed; upload and download memory is bounded by a chunk/buffer.
  • Retries are safe through idempotency keys and immutable versions.
  • Audit trails, retention, encryption, rate limits, and abuse controls are included.

# Explicit assumptions

AreaAssumption
Storagemetadata is in a database; file bytes are chunked and stored in object storage.
UsersUsers are authenticated; file owner is fixed unless explicitly transferred.
PermissionsVIEW, COMMENT, EDIT, OWNER; folder permissions inherit to children.
ConflictUpload/update includes baseVersionId; stale writes create a conflict or fail—never silently overwrite.
UploadsLarge uploads use resumable chunks with hash verification.
VersioningFile content versions are immutable; rename/move is only metadata.
DeletesSoft delete first; permanent cleanup happens later.
ConsistencyMetadata and access checks are strongly consistent; notifications/search/sync propagation may be eventually consistent.

# Solution

# Entities

A 10 MB file split into three chunks:

File: report.pdf
  └─ FileVersion 3
      └─ Manifest
          ├─ Item 0 → Chunk hash-A (4 MB)
          ├─ Item 1 → Chunk hash-B (4 MB)
          └─ Item 2 → Chunk hash-C (2 MB)
RecordFieldsPurpose
Userid, name, email, statusOwner/collaborator identity
Folderid, name, owner, parentId, stateFile hierarchy
Fileid, name, owner, parentId, currentVersionId, revisionLogical file metadata
FileVersionid, fileId, version, manifest, author, baseVersionVersion history/conflicts
Manifestid, totalSizeFile version’s chunk list
ManifestItemmanifestId, chunkHash, position, sizeChunk ordering
Chunkhash, storageKey, size, refCountStored file bytes
UploadSessionid, fileId, userId, baseVersion, expiry, stateResumable upload
UploadPartsessionId, partNo, chunkHash, sizeUploaded-part tracking
ShareresourceId, granteeId, role, expiry, stateDirect sharing
ShareLinkresourceId, tokenHash, role, expiry, statePublic-link sharing
OutboxEventid, resourceId, type, payload, publishedAtReliable async events
IdempotencyRecordkey, userId, result, expirySafe request retries

Deletion

Deletion is normally a state transition to TRASHED, not immediate byte removal. A retention worker permanently deletes metadata and decrements chunk references only after retention and legal-hold checks.

Effective-access algorithm
  1. Authenticate the actor (or validate a link token separately).
  2. Load the resource and reject missing, trashed, quarantined, or inaccessible ancestors.
  3. If actor is owner, allow owner capabilities.
  4. Load active direct grant on the resource.
  5. Walk ancestors to load active folder grants for the actor, stopping at root.
  6. Combine grants according to a documented rule: use the most specific direct grant first; otherwise the strongest inherited grant. This guide has no explicit deny rule.
  7. Map effective role and resource policy to the requested action; authorize immediately before the protected write/download URL is issued.

# APIs

  • Identity comes from the access token, not a client-supplied userId.
  • Mutating requests accept Idempotency-Key
  • Version writes also accept If-Match/baseVersionId.
OperationEndpointNotes
Create folderPOST /folders{parentId, name}; unique sibling name.
List folderGET /folders/{id}/children?cursor=&limit=Stable cursor based on (sortKey, id).
Start uploadPOST /files/uploadsReturns session and negotiated part size.
Upload partPUT /uploads/{sessionId}/parts/{partNo}Hash header and idempotent part write.
Complete uploadPOST /uploads/{sessionId}/completeManifest + final checksum + base version.
DownloadGET /files/{id}/contentValidates access, returns short-lived signed URL; supports Range.
Version historyGET /files/{id}/versions?cursor=Read requires current authorization.
Restore versionPOST /files/{id}/versions/{versionId}/restoreCreates a new head version.
Share resourcePUT /resources/{type}/{id}/shares/{granteeId}Upsert role/expiry.
Public linkPOST /resources/{type}/{id}/linksReturn raw token once.
Revoke link/shareDELETE /links/{id} / DELETE /shares/{id}Commit revocation before acknowledging.
SearchGET /search?q=&scope=&cursor=&limit=Auth-filter results, never filter only after returning.
ChangesGET /changes?cursor=Per-user change log for sync.

# Services

  • Controllers validate syntax and translate errors
  • Application services own use cases
  • Repositories own persistence
  • Adapters own object storage, queues, email, and search.

# Upload, chunking, deduplication, and versioning

  1. Client calls startUpload with file metadata, expected bytes, optional content hash, parent, and target/base version.
  2. Server authorizes CREATE_CHILD or WRITE, creates an expiring UploadSession, returns chunk size and missing-part state if resuming.
  3. Client splits the stream into fixed-size parts (for example, 4–16 MiB); for each part it calculates a hash and uploads it.
  4. Chunk store uses an atomic put-if-absent by hash. It verifies the supplied hash before accepting the part.
  5. Client calls complete with the ordered manifest and whole-file checksum.
  6. Server validates every part, authorizes again, detects base-version conflicts, writes immutable Manifest, FileVersion, updates File.currentVersionId, and inserts an outbox event in one transaction.
  7. Background work indexes, notifies, and signals sync clients. Session cleanup removes orphaned unreferenced chunks after a safety window.
  • Fixed vs content-defined chunks: fixed chunks are simpler and predictable; content-defined chunking improves dedupe after insertions but adds CPU and implementation complexity.
  • Deduplication privacy: global hash-based dedupe can expose whether another tenant possesses content. Prefer tenant-scoped dedupe or encrypted chunk domains; never let a “chunk exists” response become an information leak.
  • Reference counts: increment only when a committed manifest begins referencing a chunk; decrement in the deletion transaction. Physical garbage collection is asynchronous and rechecks references.
  • Integrity: use cryptographic chunk hashes, ordered manifest positions, total length, and a final content hash. HTTPS alone is not a storage-integrity model.
  • Versioning: metadata rename/move need not create content versions. Content replacement always creates one. Restore points the head at a new version made from an earlier manifest, preserving history.

# Conflict policy

For a binary file, do not silently overwrite another editor’s unseen version. On completion, compare baseVersionId with current head:

  • Equal: commit normally.
  • Different: return 409 Conflict, or create name (conflicted copy) with the client’s uploaded version, depending on product policy.
  • Text three-way merge is a specialized extension; it needs a base, server head, and client proposal, and is unsuitable as a generic binary-file default.

# Concurrency choices

Contended operationSafe technique
Same upload part retriedUnique (sessionId, partNo) plus hash comparison; return original receipt.
Two writers commit same fileOptimistic concurrency: conditional update where currentVersionId = baseVersionId or revision = expectedRevision.
Two users create same sibling nameDatabase unique constraint on active (parentId, normalizedName); map violation to 409.
Link max-use countAtomic conditional increment accessCount < maxAccessCount.
Deduplicated chunk insertionObject-store conditional create / DB unique hash; never check-then-insert without atomicity.
ACL cache after revocationInvalidate event; for sensitive reads, use short TTL or versioned ACL epoch.

Use fine-grained locks only within a process, keyed by file/session/resource. Never hold a lock across network upload, object storage, notification, or user callback. Lock ordering must be stable when moving between folders to prevent deadlocks. In a multi-instance deployment, use DB conditional writes/transactions rather than relying on in-memory locks.

# Transactional outbox

The database cannot atomically commit metadata and publish to an external broker. The outbox closes the crash window:

  • Publisher retries unpublished rows; it may publish an event more than once.
  • Consumers store processed event IDs or use idempotent upserts.
  • Events carry aggregate version/revision so stale events do not regress a read model.
  • The acknowledged write is strongly consistent in metadata; search, notifications, thumbnails, and other projections are eventually consistent.

# Search, listing, pagination, and indexes

Use keyset/cursor pagination, not deep offsets. A cursor encodes the last stable sort tuple, for example updatedAt|fileId, signed or opaque to clients. Query cost is typically O(log N + pageSize) using a suitable ordered index, versus expensive skipping/scanning for deep offsets.

Search should return only candidates the caller may discover. Authorization changes race with indexing, so exact open/download authorization still happens after result selection.

# Failure table

FailureBehavior / recovery
Network dies mid-uploadSession retains verified part receipts until expiry; client asks missing parts and resumes.
Client retries completeIdempotency key/session state returns already committed version rather than duplicating it.
Object upload succeeded, receipt write failedRe-upload is safe; later reconciliation detects orphan object and cleans after grace period.
Metadata DB commit failsNo file head/version is visible; uploaded objects remain unreferenced and are garbage-collected later.
Process crashes after DB commitOutbox publisher later emits durable event.
Broker/notification failureRetry with backoff and dead-letter monitoring; metadata remains authoritative.
Stale editor completesConditional head update fails; return conflict/copy policy.
Permission revoked during uploadRe-authorize at completion; retain temporary chunks only until cleanup.
Permission revoked after signed URL issuedAccess persists only for the URL’s short TTL; future URL issuance fails.
Worker reprocesses eventConsumer idempotency key prevents duplicate notification/index corruption.

# Patterns: what they solve and what not to overuse

PatternUseful applicationCaution
RepositoryAbstract metadata, sessions, shares, chunksKeep query methods task-focused; do not make a generic data-access dumping ground.
StrategyConflict policy, storage backend, notification channelPrefer injected strategies over if chains when variation is real.
Observer / pub-subDevice sync, notifications, indexing via domain eventsNever call slow observers synchronously while holding domain locks.
FacadeFileSharingService coordinates a client-facing workflowIt must delegate; do not turn it into a God object.
StateUpload session lifecycle: initiated/uploading/completed/failed/expiredEnforce valid transitions centrally.
FactorySelect file store or chunking policy by configurationKeep creation separate from business rules.
SingletonPotentially a process-local client/configuration holderPrefer dependency injection: globals hide state and make tests flaky.
OutboxReliable mutation-to-event handoffRequires idempotent consumers and cleanup/monitoring.

# Trade-offs to articulate

ChoiceBenefitCost / alternative
Fixed chunksStraightforward resumption and part sizingLower dedupe after inserted bytes; content-defined chunks improve this.
Immutable versionsSimple reads, auditability, safe retryStorage growth; retention/GC required.
Optimistic version checksNo long write locks during network I/OClient sees conflict; conflict copy/merge policy needed.
On-demand inherited ACL evaluationRevocations apply immediately without fan-outAncestor reads; cache with invalidation/epoch.
Materialized descendant ACLsFast readsExpensive, error-prone propagation/revocation.
Signed object URLsScalable direct downloadRevocation has TTL lag; use short expiry.
Async indexing/notificationsFast write path and resilienceEventual consistency and idempotency required.
Global dedupeLower storageCross-tenant privacy and encryption complexity.

# Common follow-ups and concise answers

Follow-upAnswer
“Why not a global mutex?”It serializes unrelated files and fails across instances; use conditional DB writes and narrow local locks only where needed.
“Can the same file be uploaded twice?”Retries are idempotent per session/key; content dedupe may reuse chunks, but each explicit completed update has defined version semantics.
“What if a share is revoked?”Commit revocation in metadata, invalidate ACL cache, deny subsequent authorization; previously issued signed URLs last only their short TTL.
“How do you avoid lost updates?”Client submits base version; conditional head update accepts only matching base, otherwise conflict/copy/merge policy.
“What happens after DB commit but before queue publish?”Outbox event is in the same DB transaction and is published/retried asynchronously.
“How would you scale download?”Authorize then issue short-lived range-capable object/CDN URL; data plane bypasses app servers while control plane remains protected.
←PreviousDesign a Parking LotNext→Design Tic Tac Toe

On this page

Core requirements — must implementExtended requirements — discuss if time permitsNon-functional requirementsExplicit assumptionsSolutionEntitiesAPIsServicesSearch, listing, pagination, and indexesFailure tablePatterns: what they solve and what not to overuseTrade-offs to articulateCommon follow-ups and concise answers