File Storage and Sync (Google Drive)
The object upload succeeds, but finalize times out and the client retries.
Topic tools
Layout updated
Problem statement
Design a file storage service like Google Drive. Users can upload and download files, access the latest version from multiple devices, and catch up on changes when a device comes back online.
Functional requirements
- Upload, download, list, rename and delete files.
- Resume transfers and sync changes across devices.
- Detect conflicting edits.
Non-functional requirements
- Aim for metadata under 200 ms.
- Publish a file version only after its bytes are durable.
Back-of-the-envelope estimates
| Illustrative estimate |
|---|
| 10M active users × 20 metadata actions/day ≈ 2.3k/s average |
| 1M uploads/day × 10 MB = 10 TB/day of new bytes |
Entities
| Entity / logical owner |
|---|
| File(fileId, ownerId, currentManifest, version, deleted) |
| (manifestId, chunkHashes, sizes, totalChecksum) |
| Change(accountId, sequence, fileId, version, type) |
API design
| Operation / input | Response and retry contract |
|---|---|
POST/uploads {fileId, expectedVersion, size} | Return upload session and scoped signed chunk URLs. |
POST/uploads/{id}/finalize {manifest, requestId, expectedVersion} | Verify chunks, then atomically publish pointer/change; return 409 on stale base version. |
GET/changes?cursor=... | Bounded ordered changes plus next cursor; expired cursors trigger a consistent baseline resync. |
High-level design
How to draw this design
- Transfer file bytesClient, signed upload , and object storage
- Commit file metadataMetadata service and PostgreSQL versions
- Publish file changesAccount change log, Kafka, and folder index projector
- Sync and recoverSync service, device cursors, and regional copies
Transfer chunks directly, then commit the verified and change row. Other devices pull changes by cursor.
- State ownership
- Object storage holds bytes. PostgreSQL owns the visible version and change log.
- Scale
- Keep byte traffic off application servers and partition metadata by access pattern.
- Correctness
- Compare the expected file version and commit the change row atomically.
- Failure and recovery
- Retry interrupted uploads and verify both metadata and bytes before regional recovery.
- Edge
- Compute
- State
- Messaging
━━ Synchronous┄┄ Asynchronous···· Recovery / control▧ Fault
Each arrow is one interaction. Request, background and recovery branches are not one linear transaction.
Read the 13 flow steps
High-level design component walkthrough
Client Devices
Chunk upload/download; local sync cursor
Why, tradeoff and connected operations
An application or user-facing endpoint starts or receives this flow.
Tradeoff: Offline divergence and retry logic
Connected operations: Request upload, metadata or sync; Return signed transfer URLs; Transfer chunks directly
API Gateway / Auth
Authorize files and requests
Why, tradeoff and connected operations
Centralize admission and routing while keeping business-state ownership downstream.
Tradeoff: Central auth adds latency
Connected operations: Request upload, metadata or sync; Create transfer session; Commit file ; Request changes since cursor
Upload / Download API
Issue scoped signed URLs + sessions
Why, tradeoff and connected operations
Isolate this operation so it can scale and fail independently from storage.
Tradeoff: Signed URL expiry / upload cleanup
Connected operations: Create transfer session; Return signed transfer URLs
Metadata Service
current-version pointer + manifests
Why, tradeoff and connected operations
Isolate this operation so it can scale and fail independently from storage.
Tradeoff: version checks may conflict
Connected operations: Commit file ; Commit version and change row
Sync Service
Cursor pull; notifications are hints
Why, tradeoff and connected operations
Isolate this operation so it can scale and fail independently from storage.
Tradeoff: Devices can lag or miss notifications
Connected operations: Request changes since cursor; Read change log and index
Object Storage
Immutable checksum-verified chunks
Why, tradeoff and connected operations
Object storage keeps large immutable file chunks cheaply and durably. Checksums and stable object IDs support retries and content reuse. It stores bytes, not relational metadata; keeping blobs outside avoids bloating transactional tables.
Tradeoff: Orphaned chunks and storage bills
Connected operations: Transfer chunks directly; Replicate verified chunks
Cross-region Durability
Protect committed versions on region loss
Why, tradeoff and connected operations
Cross-region object copies preserve the same committed file chunks through a regional loss. They support restoring access near surviving metadata services. This is a durability copy of object storage, not another database model; replication timing defines the loss window.
Tradeoff: Cross-region commit latency and cost
Connected operations: Replicate verified chunks; Meet metadata durability policy
PostgreSQL: Metadata, Change Log and Folder Index
Store file versions, sync changes and folder index rows under the same metadata authority.
Why, tradeoff and connected operations
PostgreSQL commits a file’s metadata version and sync change together. Indexes support folder listings and permission lookups without inventing separate authorities. suits linked metadata; large file bytes belong in object storage.
Tradeoff: can reduce write availability
Connected operations: Commit version and change row; Read change log and index; Meet metadata durability policy; Relay committed metadata; Update folder index
Kafka: Committed Metadata Changes
Carry committed metadata changes to the folder projection worker.
Why, tradeoff and connected operations
Kafka retained partitioned stream. Key events by the domain ordering key; replay and independent consumers motivate this choice. rows remain in the source database; a relay publishes after commit. Buffer independent producers and consumers, with bounded and replay semantics.
Tradeoff: Events arrive late or duplicate
Connected operations: Relay committed metadata; Consume versioned updates
Folder Index Projector
Maintain the folder view from committed metadata events.
Why, tradeoff and connected operations
Apply versioned updates to index rows in the same PostgreSQL metadata database.
Tradeoff: Folder listings may briefly lag the authoritative file record.
Connected operations: Consume versioned updates; Update folder index
Engineering control room
Deep dives — decisions, failures and recovery
Open a deep dive to follow the steps, try an example and see how recovery works.
Tradeoffs and alternatives
| Decision | Tradeoff / alternative and recovery implication |
|---|---|
| Publish only complete file versions | Unreferenced uploads can be removed after a grace period. Referenced chunks must remain until version and recovery rules allow deletion. |
| Preserve both users' edits | Automatic merging depends on the file format. For arbitrary files, keep a conflict copy rather than silently discard someone else's work. |
| Recover changes missed while a device was offline | Keeping history costs storage. When a device's cursor is too old, it needs a fresh and catch-up rather than an incomplete replay. |
| What happens if a region fails? | Waiting for remote chunk durability before publication reduces loss risk but increases upload-finalization latency and bandwidth cost. |
Production scars & failure modes
The object upload succeeds, but finalize times out and the client retries.
Look for: Inspect upload identity, object checksum and committed metadata version.
Recovery and invariant: Finalize idempotently against the upload/version identity; publish metadata and change event atomically. Garbage-collect unreferenced uploads after a grace period.
| Component / failure | Impact | Recovery mechanism | Alternative / tradeoff |
|---|---|---|---|
| Upload connection lost | Some chunks exist but no complete file is visible. | Resume by checksums/session state; finalize idempotently, then clean abandoned chunks after grace. | Extra temporary storage avoids partial-file visibility. |
| Metadata writer crashes | Finalization may have committed despite missing response. | Retry requestId and inspect durable version; promote a fenced replica with a safe log position. | Async replica promotion can lose acknowledged versions unless stronger durability was chosen. |
| Change projection lags | Folder listings or device notifications appear stale. | Read authoritative file version for critical checks and replay /change records to repair projections. | Fast eventual listings do not guarantee immediate read-your-writes without an overlay. |
| Cursor older than | The server cannot replay the missing history. | Return an explicit reset requirement and enumerate a consistent , then tail later changes. | A full resync costs bandwidth; silently advancing the cursor loses edits/deletes. |
90-second interview summary
I would separate immutable file bytes from transactional file metadata. Devices upload chunks directly to object storage under a stable upload identity. Finalization verifies chunk checksums and required durability, then PostgreSQL commits the new file-version pointer and account change record together. Upload success by itself does not publish a usable file version.
Concurrent edits carry the version they started from. The metadata transaction compares that expected version with the current version and either commits, creates a conflict copy or enters an explicit merge workflow. Arbitrary binary files cannot safely use a generic merge rule.
Devices synchronize through a durable ordered account log and advance their cursor only after applying changes locally. Push notifications just wake the device; missed pushes are repaired by pulling the log. An expired cursor requires a consistent followed by catch-up, including deletions.
Regional durability covers metadata and every referenced chunk. I would fence metadata promotion, track asset replication completeness and avoid claiming a complete recovered file from a metadata copy alone. Metrics include finalize latency, conflict rate, oldest sync cursor and orphan bytes. The tradeoff is more versioning and synchronization state in exchange for resumable transfer, offline recovery and a clear publication boundary.
Explain it without looking
Explain publish only complete file versions
Reveal answer
Verify the uploaded chunks before saving the new file pointer and change record.
Publishing metadata first can expose a version whose bytes are missing after a failure.
Unreferenced uploads can be removed after a grace period. Referenced chunks must remain until version and recovery rules allow deletion.
Explain preserve both users' edits
Reveal answer
Require the version an edit started from; report a conflict if it changed.
The last network response to arrive is not necessarily the edit the user meant to keep.
Automatic merging depends on the file format. For arbitrary files, keep a conflict copy rather than silently discard someone else's work.
Explain recover changes missed while a device was offline
Reveal answer
Use a durable change log; push notifications only tell the device to check it.
A lost push message must not leave a device permanently out of date.
Keeping history costs storage. When a device's cursor is too old, it needs a fresh and catch-up rather than an incomplete replay.
Explain what happens if a region fails?
Reveal answer
Check that the recovery region has both file metadata and all its bytes.
The file's durability guarantee spans metadata and object bytes together.
Waiting for remote chunk durability before publication reduces loss risk but increases upload-finalization latency and bandwidth cost.
Revision checklist
Revision checklist
- Reconstruct publish only complete file versions: Verify the uploaded chunks before saving the new file pointer and change record.
- Reconstruct preserve both users' edits: Require the version an edit started from; report a conflict if it changed.
- Reconstruct recover changes missed while a device was offline: Use a durable change log; push notifications only tell the device to check it.
- Reconstruct what happens if a region fails?: Check that the recovery region has both file metadata and all its bytes.
- Name the authoritative state, boundary, retry identity and failure-domain durability guarantee.
- Explain one alternative and exactly which guarantee you would relax.
- Redraw the request and recovery paths without looking; mark what required a hint.
60-minute interview outline
60-minute interview walkthrough
| Time | Focus | What to cover |
|---|---|---|
| 0–5 min | Introductions | Introduce yourself briefly and confirm the interview format. |
| 5–15 min | Scope and scale | Scope uploads, downloads, and multi-device sync. Estimate object traffic separately from metadata writes. |
| 15–30 min | High-level design | Trace a direct chunk upload, metadata commit, and a second device pulling changes by cursor. |
| 30–45 min | Deep dives | Explain why the file version and change row commit together. Walk through two devices editing the same version. |
| 45–55 min | Failure and recovery | Recover an interrupted upload or a lagging device. Explain what must replicate before another region can serve the file. |
| 55–60 min | Wrap-up | Summarize the design and its main tradeoff. Leave time for questions. |
On this page
- Problem statement
- Functional requirements
- Non-functional requirements
- Back-of-the-envelope estimates
- Entities
- API design
- High-level design
- High-level design component walkthrough
- Engineering control room
- Deep dives — decisions, failures and recovery
- Tradeoffs and alternatives
- Production scars & failure modes
- 90-second interview summary
- Explain it without looking
- Revision checklist
- 60-minute interview walkthrough