Secure Client-Direct Attachment Uploads for a Messaging Product
System DesignModel answerLast updated
Design a pipeline where clients send files straight to object storage using scoped signed URLs, with a tracked lifecycle, async scanning and processing, and cleanup of abandoned uploads.
Context
A team messaging product lets people attach everything from small screenshots and avatars to large video clips and archives. Pushing all of that data through the regular API tier would strain memory, inflate bandwidth bills, and make long transfers fragile on flaky connections.
Design an upload system in which clients send bytes directly to a cloud object store (S3 or GCS style), while the backend still controls who may upload, checks what was uploaded, and tracks each file's lifecycle.
What the system must do
Functional
- Hand clients short-lived, narrowly scoped upload permissions (for example presigned URLs) without ever exposing the storage account's main credentials.
- Persist each file's state through these stages:
INITIATED,UPLOADED,PROCESSING,ACTIVE,FAILED,EXPIRED. - Verify files (checksum, content-type detection, malware scanning) and build derivatives (thumbnails, video transcodes) asynchronously, so a file only becomes usable in chat after it passes.
- Find and delete leftovers: uploads that were started but never finished, and files whose processing failed.
Non-functional
- Security: block disallowed file types, prevent overwriting existing objects, and prevent access across channels the user does not belong to.
- Scalability: handle peak upload starts while using very little backend compute.
- Reliability: retries and resuming large uploads must not create duplicate objects or database rows.
Scale
- 20 million daily active users
- 5 million uploads per day, roughly 200 per second at peak
- Images up to 25 MB; videos and archives up to 1 GB
- Files in active channels are kept indefinitely unless a user or retention policy deletes them
Cover in your answer
- The request/response flow between client, backend, and object store for both single-request and multipart uploads.
- The data model for upload sessions, file records, channel associations, and state.
- The event pipeline: storage notifications, background workers, and how the client learns about progress and completion.
- Failure handling and garbage collection: interrupted uploads, checksum mismatches, and storage events that arrive late or never.
Hints
Hint 1
Keep the rule 'file bytes never pass through API servers' central: the backend only authorizes, records state, and decides. Let the server choose the object key and bake size, content type, and checksum constraints into the signed request.
Hint 2
Treat the file record as a state machine where every transition is a conditional update (compare-and-set on the current state). That makes duplicate or out-of-order storage events harmless, and an idempotency key on session creation makes client retries safe.
Hint 3
Upload into a private quarantine location first, and only copy to permanent storage after verification. Add a periodic reconciler that checks storage directly, so lost events and abandoned multipart uploads are both caught.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
1. Requirements and sizing
Core principle: file bytes never touch the API servers. The backend issues capabilities, records state, and makes decisions.
- Control-plane load: 5M/day is about 58/s average and about 200/s peak. That is trivial for a small stateless service plus a database.
- Data volume: assuming a 2 MB average with a long tail of 1 GB files, expect about 10 TB/day, or several PB/year before derivatives. This motivates storage tiering (move to infrequent access after 30 to 90 days) and optional per-tenant dedup by content hash.
- Upload modes: images up to 25 MB use a single presigned PUT/POST; anything above roughly 50 MB uses multipart.
- Assumptions to confirm: files can be attached to multiple channels; no end-to-end encryption (so server-side scanning is possible); images visible in seconds, video within minutes.
2. API and handshake
Initiate
POST /v1/uploads
{ channel_id, filename, size_bytes, declared_mime, sha256, idempotency_key }
-> 201 { upload_id, file_id, mode, single{url, fields, expires_at} | multipart{part_size, parts[]} }
Before signing anything the server checks:
- The user is a member of the channel and may post.
- The MIME type is allowlisted and the size fits that class's limit.
- Per-user and per-tenant quotas are not exceeded.
(user_id, idempotency_key)is unique, so a retry returns the existing session rather than creating another.
Hardening the signed capability
- The server picks the key, e.g.
quarantine/{tenant}/{upload_id}. Clients never choose paths, so they cannot overwrite anything. - Signed conditions: exact key, content-length equal to the declared size, exact content type, the declared SHA-256 as the required checksum (storage rejects corrupted bodies itself), and create-only semantics (
If-None-Match: *) where supported. - TTL around 15 minutes, signed by a role limited to
PutObjectonquarantine/*. - The quarantine bucket is private, not a CDN origin, and has a lifecycle rule expiring objects after about 7 days.
Multipart
- Server calls
CreateMultipartUploadand stores the storage-side upload ID. - Use ~16 MB parts (64 parts for 1 GB); hand out part URLs in batches via
POST /uploads/{id}/parts. GET /uploads/{id}/partsreturns confirmed parts fromListParts, which is what enables resume after a crash or network change.POST /uploads/{id}/completelets the server callCompleteMultipartUpload, after checking part count and total size against the session.
Sending and viewing
- The client can post the message immediately with
attachments: [file_id]; the UI shows "processing" until the file isACTIVE. Upload completion is decoupled from message delivery. - Downloads go through
GET /v1/files/{id}, which re-checks channel membership and returns a short-lived signed CDN URL.
3. Data model (relational, sharded by tenant)
upload_sessions(upload_id PK, file_id, user_id, tenant_id, channel_id,
idempotency_key, mode, storage_upload_id, declared_size, declared_mime,
declared_sha256, part_size, expires_at, created_at,
UNIQUE(user_id, idempotency_key))
files(file_id PK, tenant_id, owner_id, state, version, storage_key,
quarantine_key, size, sniffed_mime, sha256, scan_result,
failure_reason, created_at, activated_at, deleted_at)
file_derivatives(file_id, kind, storage_key, state, PK(file_id, kind))
attachments(message_id, file_id, channel_id, PK(message_id, file_id))
processed_events(file_id, event_key, PK(file_id, event_key))
Transitions: INITIATED -> UPLOADED -> PROCESSING -> ACTIVE; FAILED from UPLOADED or PROCESSING; EXPIRED from INITIATED.
Each move is a compare-and-set:
UPDATE files SET state='PROCESSING', version=version+1
WHERE file_id=? AND state='UPLOADED';
Zero rows affected means another worker already advanced it, which gives idempotency for free. Authorization always flows through attachments.channel_id; knowing a file_id grants nothing.
4. Event pipeline
Client -PUT-> quarantine bucket -ObjectCreated-> queue/Kafka -> verifier workers (+DLQ)
verifier -> derivative queue -> thumbnail / transcode workers
-> state=ACTIVE + outbox row -> relay -> realtime gateway ("file.ready")
Verifier steps, in order:
HEADthe object; size and SHA-256 must match the session.- Sniff magic bytes; if they disagree with the declared type, mark
FAILED(stops renamed executables and polyglots). - Malware scan, with a separate pool for archives enforcing timeouts and zip-bomb limits (ratio and nesting depth).
- Promote: server-side copy to
files/{tenant}/{file_id}, optionally dedup by hash with reference counting, then delete the quarantine copy. - Derive: strip EXIF and make thumbnails for images; enqueue transcodes for video.
- Activate once required derivatives exist (thumbnail required; full adaptive-bitrate ladder can finish later).
- Notify: write
file.readyto an outbox in the same transaction as the state change; a relay publishes it to the gateway, which pushes to channel members. Clients can pollGET /files/{id}as a fallback.
Upload progress is measured client-side from bytes sent; transcode progress is published on the same per-file channel.
5. Failures and cleanup
| Failure | Handling |
|---|---|
| Client abandons upload | A reconciler (every ~10 min) scans INITIATED sessions past expires_at plus grace. It checks storage: if the object exists, it enqueues verification (the event was lost); otherwise it aborts the multipart upload and marks EXPIRED. |
| Lost or delayed storage event | Same reconciler covers sessions stuck in INITIATED/UPLOADED; the CAS transition makes duplicate delivery harmless. |
| Checksum mismatch | Storage rejects it at upload time; if it slips through, verifier marks FAILED, deletes the object, and notifies the client to retry. |
| Worker crash mid-processing | Visibility timeout returns the message to the queue; jobs are idempotent. Rows stuck in PROCESSING too long are re-enqueued, and after N attempts go to the DLQ and FAILED. |
| Orphaned multipart parts | Bucket lifecycle rule to abort incomplete multipart uploads after a few days, as a backstop to the reconciler. |
| Orphan permanent objects | Periodic sweep comparing storage listings (or inventory reports) against files; delete objects with no row after a grace period. |
6. Trade-offs and common mistakes
- Letting the client choose the key enables overwrites; always generate it server-side.
- Trusting declared MIME type is unsafe; sniff content and serve downloads with a forced content type and
nosniff. - Relying only on storage events loses files; always pair events with a reconciler.
- Making message send wait on processing hurts latency; decouple them.
- Unbounded presigned URLs (long TTL, no size condition) turn into free storage for attackers.
- Dedup saves storage for forwarded files but complicates deletion; use reference counts and delayed hard deletes.
- Deletion and retention: soft delete first, then purge objects and derivatives asynchronously.