Direct-to-Storage Media Upload Pipeline for Messaging
Medium · System Design · Software Engineer · Onsite
Prompt
Architect a direct-to-object-storage attachment pipeline for a real-time workplace messaging application. Because streaming terabytes of screenshots, PDFs, archive bundles, and gigabyte-scale video clips through backend web servers wastes memory, doubles network egress charges, and breaks easily on flaky mobile connections, clients must push bytes straight to cloud blob storage (such as S3 or GCS) while your backend retains tight control over authorization, content inspection, and lifecycle tracking.
Design for the following functional, security, and scale targets:
- Core capabilities:
- Issue short-lived, byte-bounded upload tokens (such as presigned URLs or policies) without ever revealing master cloud storage keys.
- Track every attachment durably through explicit states:
INITIATED,UPLOADED,PROCESSING,ACTIVE,FAILED, andEXPIRED. - Inspect uploaded bytes asynchronously—verifying cryptographic hashes, true binary file types, and malware status while generating thumbnails or video transcodes—before exposing the attachment to channel members.
- Reconcile and purge orphaned cloud blobs and stale metadata whenever uploads are abandoned mid-flight or fail verification.
- Scale & reliability assumptions:
20 milliondaily active users uploading5 millionattachments per day (~200 uploads/secat peak), with images up to25 MB, videos and archives up to1 GB, and indefinite retention for active channel attachments until removed by user deletion or workspace retention rules. Uploads must support idempotent retries and resumable large transfers, while preventing file-type spoofing, object overwrites, and cross-channel unauthorized reads.
Scope & Expectations
- Client–backend–storage handshake: Define the API contracts and protocol flows for both single-request small uploads and resumable multipart large uploads.
- Metadata & state schema: Model upload sessions, attachment records, channel bindings, and guarded lifecycle transitions.
- Asynchronous verification & delivery: Detail how storage completion triggers background inspection/transcoding workers and notifies chat clients when an attachment becomes safe to view.
- Failure recovery & garbage collection: Explain how interrupted transfers, hash/size mismatches, lost or duplicated storage events, and orphaned blobs are handled cleanly.
Step-by-step walkthrough
Clarify requirements and system boundaries
When users share 1 GB videos or millions of screenshots in a chat app, sending the raw file bytes through your backend API servers is an expensive trap: a single 1 GB upload over a slow mobile connection holds an API socket and memory buffer open for nearly seven minutes, and you pay for network transfer twice (client to API, then API to storage). Instead, we separate the control plane (our lightweight API servers, which decide who may upload what and track file state) from the data plane (cloud object storage such as Amazon S3 or Google Cloud Storage, which stores immutable files as flat key-value blobs and absorbs heavy byte streams directly from clients).
Functional requirements
- Scoped upload permission: An authenticated channel member requests permission to upload a file and receives a presigned capability (a temporary, cryptographically signed upload ticket that grants permission to write one specific storage key of one exact byte size and content type without ever exposing master cloud credentials).
- Resumable large uploads: Small files (
<= 25 MB) upload in a single HTTP request; larger files (up to1 GB) split into fixed-size parts so an interrupted mobile connection can resume without re-uploading completed parts. - Durable lifecycle tracking: Every file moves cleanly through six explicit states:
INITIATED,UPLOADED,PROCESSING,ACTIVE,FAILED, andEXPIRED. - Verification before release: Asynchronous background workers check byte size, cryptographic hash, true file type, and malware — and generate thumbnails or video renditions — inside an isolated quarantine area before any other user can open the file.
- Orphan cleanup: Abandoned upload sessions, incomplete multipart chunks, and failed uploads are automatically detected and purged from both object storage and the database.
Non-functional requirements and scope assumptions
- Scale:
20Mdaily active users (DAU),5Mfiles/day (~58/saverage,~200 uploads/speak), images up to25 MB, videos and archives up to1 GB. - Security: Clients cannot pick storage keys, overwrite existing objects, exceed their declared byte size, or read unscanned files across channels.
- Idempotency: Retrying an upload initiation or completion request never creates duplicate database rows or duplicate stored blobs.
- Decoupled chat UX: Once bytes finish uploading (
UPLOADED), the sender can immediately post their chat message; channel recipients see a safe "Processing attachment..." placeholder with no download link until verification succeeds and transitions the file toACTIVE. - Retention: Active channel files persist indefinitely until every referencing message is deleted (followed by a 30-day soft-delete recovery grace period) or a workspace retention rule expires them. End-to-end encryption is out of scope because server-side malware scanning and transcoding must inspect the file bytes.
Back-of-the-envelope numbers
Let's translate the traffic assumptions into concrete bandwidth, compute, database, and storage numbers so we know where the real bottlenecks sit.
Upload traffic & bandwidth Daily uploads 5,000,000 / 86,400 s = ~58 uploads/s avg, ~200 uploads/s peak (~3.5x avg) Assumed payload mix 70% images/screenshots (3.50M/day x 0.5 MB avg) = 1.75 TB/day 25% documents/PDFs (1.25M/day x 1.0 MB avg) = 1.25 TB/day 5% large files (0.25M/day x 50 MB avg) = 12.50 TB/day -> half videos (~125k/day), half archives (~125k/day) Total ingress bytes 1.75 + 1.25 + 12.50 = 15.5 TB/day Byte rate 15.5 TB / 86,400 s = ~180 MB/s (~1.44 Gbit/s) avg Peak (~3.5x avg) = ~630 MB/s (~5.0 Gbit/s) One 1 GB video @ 20 Mbit/s 8,000 Mbit / 20 Mbit/s = 400 seconds (~6.7 minutes) on an open connection Control-plane load (what our API and database actually touch) API calls per upload initiate + complete (+ ~4 part-URL batch calls for large files) Peak ~200/s x 3 = ~600 small JSON requests/s Presigning cost Local HMAC-SHA256 hash (~microseconds of CPU; 0 network calls to S3 for single-part) Metadata DB writes ~6 row writes per upload (session, file, ~4 state updates) -> ~1,200 writes/s peak Long-term metadata growth 5M files/day x 365 days = ~1.82B file rows/year Asynchronous worker compute Image thumbnails 3.5M/day x 0.1 CPU-s = 350,000 CPU-s/day / 86,400 s = ~4 CPU cores avg Malware + SHA-256 stream 15.5 TB/day @ 50 MB/s per core = 310,000 core-s/day = ~4 CPU cores avg Video transcoding 125,000 videos/day x 2 core-min / 1,440 min/day = ~174 CPU cores avg Persistent storage Clean originals 15.5 TB/day x 365 = ~5.66 PB/year (+ ~10% for thumbnails/renditions)Three design decisions jump directly out of this math:
- Bytes, not JSON requests, are the load: Direct upload keeps
5 Gbit/sof peak traffic off our API servers, leaving just~600 requests/sthat a few stateless instances handle effortlessly. - Video transcoding dominates CPU (
~174 coresvs.~8 coresfor everything else): Videos must run on a separate slow worker queue so a500 KBscreenshot never waits behind a1 GBvideo. - Storage dominates dollar cost (
~5.7 PB/year): Invisible leaked bytes — abandoned multipart chunks, uncleaned quarantine copies, or composer uploads the user never sent — cost real money every month, making automated reconciliation mandatory.
- Bytes, not JSON requests, are the load: Direct upload keeps
API and upload handshake
Files up to
25 MB(all images and most documents) use a single-part upload. Larger files (> 25 MBup to1 GB) use multipart upload (an object-storage feature that accepts fixed-size slices independently and stitches them into one object on the server) with16 MiBparts — at most64parts for1 GB, comfortably inside S3's5 MiBminimum part size and10,000-part ceiling.When initiating an upload, the client supplies a
client_upload_ididempotency key (a unique random token generated on the client when the user selects a file, reused on retries so network timeouts never create duplicate upload sessions). Signing a presigned URL uses an HMAC (Hash-based Message Authentication Code — a fast cryptographic signature computed locally in memory using a temporary signing key, requiring zero round trips to S3 for single-part uploads).Single-part flow (
<= 25 MB)1. Client -> Upload API: POST /v1/uploads { "client_upload_id": "cu_4d9b...", "channel_id": "ch_19", "filename": "wireframe.png", "size_bytes": 614400, "declared_type": "image/png", "sha256_base64": "m3K8..." } <- 201 Created { "upload_id": "upl_s04_6c1a8e20", "file_id": "fil_s04_31f9d04b", "mode": "SINGLE", "post_url": "https://chat-quarantine.s3.amazonaws.com/", "form_fields": { "key": "q/6c/upl_s04_6c1a8e20/blob", "Content-Type": "image/png", "policy": "<base64-json-policy>", "x-amz-signature": "<hmac-hex>" }, "expires_at": "2026-10-18T09:15:00Z" // 15-minute TTL } (Errors: 403 NOT_IN_CHANNEL | 413 FILE_TOO_LARGE | 415 DISALLOWED_TYPE | 429 RATE_LIMITED) 2. Client -> Quarantine Object Store: HTTP POST bytes + form_fields directly to post_url 3. Client -> Upload API: POST /v1/uploads/upl_s04_6c1a8e20/complete <- 202 Accepted { "file_id": "fil_s04_31f9d04b", "state": "UPLOADED" } 4. Client -> Chat API: POST /v1/channels/ch_19/messages { "text": "Sharing the latest UI wireframe", "file_ids": ["fil_s04_31f9d04b"] } (Allowed once state is UPLOADED, PROCESSING, or ACTIVE; shows a placeholder until ACTIVE) 5. Realtime WebSocket -> Channel Members: event file.state_changed { "file_id": "fil_s04_31f9d04b", "state": "ACTIVE", "version": 3 }Multipart flow (
> 25 MBto1 GB)1. POST /v1/uploads { ..., "size_bytes": 1073741824, "declared_type": "video/mp4" } (Backend calls S3 CreateMultipartUpload and keeps S3's internal uploadId private in the DB) <- 201 { "upload_id": "upl_s04_8a2d...", "file_id": "fil_s04_55e1...", "mode": "MULTIPART", "part_size": 16777216, "part_count": 64 } 2. POST /v1/uploads/upl_s04_8a2d.../part-urls { "part_numbers": [1, 2, ..., 16] } <- 200 { "parts": [ { "part_number": 1, "put_url": "https://...", "expires_at": "..." }, ... ] } 3. Client PUTs 4-6 parts in parallel directly to S3; records each response's ETag header (an ETag is the per-part content digest returned by object storage upon storing a chunk). 4. On resume after disconnect: GET /v1/uploads/upl_s04_8a2d... (Backend queries S3 ListParts — the ground truth — and returns already-stored part numbers) 5. POST /v1/uploads/upl_s04_8a2d.../complete { "parts": [ { "part_number": 1, "etag": "\"d41d8...\"" }, ... ] } (Backend verifies part count + byte sizes via ListParts, calls CompleteMultipartUpload) <- 202 { "file_id": "fil_s04_55e1...", "state": "UPLOADED" }Notice three security invariants built into this contract: - Server-generated keys: User filenames stay in database metadata (
wireframe.png), never in S3 keys (q/6c/upl_s04_6c1a8e20/blob), blocking path-traversal tricks and cross-user overwrites. - Backend-only multipart completion: Clients never get permission to callCompleteMultipartUploaddirectly; otherwise a client could assemble 10,000 oversized parts and bypass our1 GBcap. -202 Acceptedinstead of200 OK: Completion means "bytes landed in quarantine," not "safe to view."Data model and lifecycle state machine
We store metadata in PostgreSQL sharded by
workspace_idso all channels, messages, and files for one customer live on the same database shard. Bothupload_id(upl_s04_...) andfile_id(fil_s04_...) embed the shard number (s04) so background workers receiving an S3 object key or download requests carrying only afile_idcan route directly to shard04without a global lookup table.To guarantee we never update a database row and then crash before queuing its background job, we use a transactional outbox (an
outboxtable written inside the exact same SQL transaction as thefilesstate update, tailed asynchronously by a relay process that pushes jobs to the queue).files (sharded by workspace_id) file_id PK e.g. 'fil_s04_31f9d04b' workspace_id shard key uploader_id, channel_id who uploaded and in which channel client_upload_id UNIQUE (uploader_id, client_upload_id) -- enforces idempotent POST /uploads state 'INITIATED'|'UPLOADED'|'PROCESSING'|'ACTIVE'|'FAILED'|'EXPIRED'|'DELETED' version INT monotonic counter bumped on every state change (dedups client WebSocket events) processing_attempt INT fencing token bumped each time a worker claims the file lease_until TIMESTAMP when the current worker's processing lease expires attachment_count INT number of live chat messages referencing this file (DEFAULT 0) filename, declared_type, sniffed_type, size_bytes, declared_sha256, verified_sha256 quarantine_key, clean_key, failure_reason created_at, updated_at, uploaded_at, activated_at, deleted_at INDEX (state, updated_at) -- fast sweeps for stuck or expired rows upload_sessions (partitioned by created_at day; whole daily partitions dropped after 30 days) upload_id PK e.g. 'upl_s04_6c1a8e20' file_id, workspace_id, user_id, channel_id mode 'SINGLE' | 'MULTIPART' storage_key 'q/6c/upl_s04_6c1a8e20/blob' storage_upload_id NULL S3 internal multipart uploadId (hidden from client) declared_size, declared_type, part_size, part_count, expires_at, created_at file_derivatives PK (file_id, kind) -- 'thumb_360', 'video_720p', 'poster', 'pdf_preview' message_attachments PK (message_id, file_id), channel_id, INDEX (file_id) file_events (file_id, seq, from_state, to_state, actor, reason, created_at) outbox (id PK, file_id, topic, payload_json, created_at, published_at)Why put
UNIQUE (uploader_id, client_upload_id)onfilesinstead ofupload_sessions? PostgreSQL requires every unique index on a partitioned table to include the partition column (created_at), which would fail to catch a retry that crossed midnight. Putting the unique constraint on unpartitionedfilesmakes idempotency airtight across days, while letting us drop oldupload_sessionsdaily partitions instantly without vacuum overhead.Lifecycle state machine
HEAD / ListParts matches +-----------+ -----------------------------> +----------+ | INITIATED | | UPLOADED | +-----------+ ----+ +---> +----------+ | | bad size / parts | | | TTL past v | | worker acquires lease | (no data) +--------+ | v (processing_attempt + 1) v | FAILED | <---------+ +------------+ +-----------+ +--------+ malware, bad | PROCESSING | --+ lease expired & | EXPIRED | ^ hash/MIME, or +------------+ <-+ attempts < 5 +-----------+ +------ 5 crashes | | all checks pass + copied to clean bucket v +------------+ last message deleted | ACTIVE | -----------------------> (DELETED -> purged 30d) +------------+High-level architecture
Client (Web / Mobile / Desktop) | (1) POST /uploads, /part-urls, /complete ^ (6) WebSocket: file.state_changed v | +-------------------------+ +---------------------+ +----------------------+ | Stateless Upload API |------->| Sharded Postgres DB |<-------| Realtime Chat Gateway| | auth, channel check, | | files, sessions, | | pushes state updates | | rate limit, HMAC sign | | attachments, outbox | +----------------------+ +-------------------------+ +----------+----------+ ^ | (2) Direct HTTP POST / PUT | outbox relay | v with presigned capability v | +-------------------------+ (3) +---------------------+ (4) enqueue | | Quarantine Bucket (S3) |------->| Storage Event |--------+ | | PRIVATE, no public/CDN, | S3->SQS| Consumer | v | | 14d object expire rule, | | confirm_upload() | +--------------------------+ | 10d multipart abort rule| +---------------------+ | Verification Workers | +-------------------------+ | - Fast pool: hash, MIME, | ^ | (5) stream bytes once | malware, thumbnails | | +-------------------------------------------->| - Slow pool: video 720p | | +-------------+------------+ +-------------------------+ | server-side copy + | Scheduled Reconciler | v CAS -> ACTIVE | - Every 5m: stale rows | +--------------------------+ +-----+ | - Daily: S3 Inventory |-------------------------------->| Clean Bucket (Private) |<----| CDN | +-------------------------+ purges orphaned objects | f/<ws>/<file_id>/... | +-----+ +--------------------------+ 5-min signed read URLsHere is how one upload flows end to end: 1. Authorize: Upload API verifies channel membership, checks workspace MIME allowlist and rate limits, writes
INITIATEDrows in Postgres, and returns a presigned capability. 2. Transfer: Client uploads bytes straight to the private Quarantine Bucket. 3. Confirm: S3 emits anObjectCreatedevent to SQS, and the client also calls/complete. Both invoke the same idempotentconfirm_upload()routine to moveINITIATED -> UPLOADED. 4. Dispatch: TheUPLOADEDtransaction writes anoutboxjob routed to the fast pool (images/docs) or slow pool (videos). 5. Verify & promote: A worker streams the quarantine object, checks SHA-256, sniffs the real file type, scans for malware, writes thumbnails/renditions and a clean copy to the Clean Bucket, transitionsPROCESSING -> ACTIVE, and queues deletion of the quarantine copy. 6. Release: Outbox notifies the Realtime Gateway to pushACTIVEto channel viewers; downloads thereafter go through a CDN (Content Delivery Network — edge caches around the world that serve files close to users) gated by 5-minute signed read URLs after an API channel-membership check.Deep dive 1: Scoped capabilities and quarantine isolation
How do we give an untrusted client direct write access to cloud storage without letting them upload a 50 GB file, overwrite a coworker's contract, or plant browser-executable JavaScript?
1. Exact-size presigned POST policies for single-part uploads
In S3, a presigned
PUTURL signs the target key andContent-Type, but cannot express a byte-size range condition. An S3 presigned POST policy is a signed JSON document that S3 evaluates before accepting the upload, letting us lock the minimum and maximum byte length to the exact byte count declared at initiation:{ "expiration": "2026-10-18T09:15:00Z", "conditions": [ {"bucket": "chat-quarantine"}, {"key": "q/6c/upl_s04_6c1a8e20/blob"}, {"Content-Type": "image/png"}, ["content-length-range", 614400, 614400] ] }If a client declares
614,400bytes (600 KB) and sends614,401bytes or1 GB, S3 immediately aborts the socket. (On Google Cloud Storage, V4 signedPUTURLs achieve the same lock via a signedx-goog-content-length-rangeheader, and S3/GCS create-only headersIf-None-Match: */ifGenerationMatch=0guarantee no existing object can ever be overwritten.)2. Batched part URLs + backend inspection for multipart uploads
Individual S3
UploadPartURLs cannot constrain the sum of all parts. Instead: - We issue presignedUploadPartURLs in small batches of up to16parts at a time, each expiring in15minutes. - When the client calls/complete, our backend calls S3ListPartsand verifies thatlen(parts) == part_count, every interior part equals16 MiB, andsum(part.size) == declared_size. If anything mismatches, the backend callsAbortMultipartUploadand marks the fileFAILEDwithout ever assembling the object.3. Physical quarantine + magic-byte sniffing + safe download headers
- Two buckets, never one: The quarantine bucket has Block Public Access enabled, has no CDN attached, and grants
s3:GetObjectexclusively to the background worker IAM role. Even a bug in download-URL signing cannot leak an unscanned file because the download service only has credentials for the Clean Bucket. - Magic-byte sniffing: Anyone can rename
exploit.htmltocat.pngand sendContent-Type: image/png. Workers perform magic-byte sniffing (inspecting the raw binary file header signatures — such as89 50 4E 47for PNG or25 50 44 46for PDF — rather than trusting filenames or HTTP headers). If the sniffed type violates workspace policy, the file moves toFAILED: TYPE_NOT_ALLOWED. - Safe delivery: Rendered chat previews use server-re-encoded WebP thumbnails (which also strip GPS EXIF metadata). Raw original downloads are served from a separate cookieless domain (
chat-files-cdn.example) withX-Content-Type-Options: nosniffandContent-Disposition: attachmentfor non-media types, preventing stored cross-site scripting (XSS) in the chat web app.
- Two buckets, never one: The quarantine bucket has Block Public Access enabled, has no CDN attached, and grants
Deep dive 2: Asynchronous processing and exactly-once state transitions
Object-store event notifications (S3 -> SQS) are at-least-once: messages can arrive twice, arrive minutes late, or occasionally be missed if a queue retention window is exceeded. How do we guarantee every valid upload reaches
ACTIVEexactly once?We combine convergent triggers with compare-and-set (CAS) database updates (conditional
UPDATE ... WHEREstatements that atomically check the current state before changing it, returning1row updated to the single winner and0to every duplicate caller).Client POST /complete --------+ S3 ObjectCreated SQS event ---+---> confirm_upload(upload_id) 5-min Reconciler sweep -------+ | v 1. Verify bytes in S3 (HEAD or ListParts) 2. SQL CAS: UPDATE files SET state='UPLOADED' WHERE file_id=... AND state='INITIATED' -> 1 row updated: insert outbox('file.process') -> 0 rows updated: already handled! Ack & stop.Here is the exact confirmation logic in Python:
def confirm_upload(db, store, upload_id): """Idempotently confirm single-part or assembled multipart uploads.""" session = db.get_session(upload_id) # Ask object storage directly; never trust caller claims alone. head = store.head_object(session.storage_key) if head is None and session.mode == "MULTIPART": # If the client uploaded all parts and disconnected before /complete, # check ListParts and assemble on its behalf. parts = store.list_parts(session.storage_key, session.storage_upload_id) total_bytes = sum(p.size for p in parts) if len(parts) == session.part_count and total_bytes == session.declared_size: store.complete_multipart(session.storage_key, session.storage_upload_id, parts) head = store.head_object(session.storage_key) if head is None: return "NOT_UPLOADED_YET" if head.size != session.declared_size: store.delete_object(session.storage_key) db.fail_file_cas(session.file_id, expected_state="INITIATED", reason="SIZE_MISMATCH") return "FAILED" # Atomic compare-and-set: at most one caller transitions INITIATED -> UPLOADED. with db.transaction(): rows_updated = db.execute( """ UPDATE files SET state = 'UPLOADED', size_bytes = %s, uploaded_at = now(), version = version + 1 WHERE file_id = %s AND state = 'INITIATED' """, (head.size, session.file_id), ) if rows_updated == 1: db.insert_event(session.file_id, "INITIATED", "UPLOADED", actor="confirm") db.insert_outbox(session.file_id, "file.process", {"file_id": session.file_id}) return "CONFIRMED" # If the session already expired or failed before late bytes landed, clean up quarantine. current_state = db.get_file_state(session.file_id) if current_state in ("EXPIRED", "FAILED"): store.delete_object(session.storage_key) return "PURGED_LATE_UPLOAD" return "ALREADY_CONFIRMED"Worker leases and fencing tokens during
PROCESSINGOnce
file.processlands on the worker queue, what if a worker starts transcoding a 1 GB video, stalls during a network pause for 12 minutes, and a second worker picks up the retry? Without protection, both workers would finish and overwrite each other.We solve this with a lease (a temporary lock expiration timestamp
lease_untilrenewed by a heartbeat every 2 minutes while the worker is healthy) paired with a fencing token (processing_attempt, an integer incremented every time a worker claims the file):- Claim: Worker runs
UPDATE files SET state = 'PROCESSING', processing_attempt = processing_attempt + 1, lease_until = now() + interval '10 minutes' WHERE file_id = :id AND (state = 'UPLOADED' OR (state = 'PROCESSING' AND lease_until < now())) AND processing_attempt < 5 RETURNING processing_attempt. Suppose Worker A getsattempt = 1. - Stream & deterministic keys: Worker A streams the quarantine object once (computing SHA-256, sniffing magic bytes, and piping to ClamAV/malware engine), writes derivatives to deterministic Clean Bucket keys (
f/<ws>/<file_id>/thumb_360.webpso retries overwrite cleanly without leaking duplicates), and server-side copies the verified original tof/<ws>/<file_id>/original. - Fenced commit to
ACTIVE: Worker A commitsUPDATE files SET state = 'ACTIVE', clean_key = :key, verified_sha256 = :hash, version = version + 1 WHERE file_id = :id AND state = 'PROCESSING' AND processing_attempt = 1— plus outbox rows forfile.state_changedandquarantine.delete(deleting the quarantine copy immediately saves~200 TBof 14-day duplicate storage!). If Worker A stalled and Worker B already claimedattempt = 2, Worker A's finalUPDATEmatches0rows and cleanly aborts.
- Claim: Worker runs
Deep dive 3: Resumable multipart uploads and orphan reconciliation
Resuming interrupted 1 GB video uploads
Suppose a mobile user uploads a
1 GB(64-part) video and loses cellular signal partway through:Client local state: { upload_id: "upl_s04_8a2d", file_fingerprint: "1073741824:mtime:head_tail_hash" } t = 00:00 Parts 1..40 PUT to S3 -> S3 stores parts 1..40; parts 41..64 fail when signal drops t = 00:12 Signal returns (or app restarts and hashes first/last 1 MiB -> matches saved session) Client calls GET /v1/uploads/upl_s04_8a2d Backend calls S3 ListParts -> returns stored parts [1..40] with sizes & ETags t = 00:13 Client calls POST /v1/uploads/upl_s04_8a2d/part-urls { part_numbers: [41..56] }, then [57..64] (Only the 24 missing parts are uploaded; 640 MiB already in S3 is never re-sent!) t = 00:16 POST /complete -> Backend verifies 64 parts = 1 GiB -> CompleteMultipartUpload -> UPLOADEDEach
part-urlscall slides the multipart session'sexpires_atforward by24 hours(capped at7 daysfrom creation), giving slow connections plenty of time while bounding abandoned uploads.Orphan cleanup and scheduled reconciliation
Orphans appear whenever reality in S3 diverges from metadata in Postgres. Every 5 minutes, a scheduled reconciler scans stale database rows, supplemented by a daily batch job over S3 Inventory (a daily CSV/Parquet manifest file generated natively by S3 listing every stored object without making millions of slow
ListObjectsAPI calls):Orphan scenario How we detect & safely clean it ----------------------------------------------- ------------------------------------------------------------ 1. Abandoned INITIATED upload 5-min sweep finds state='INITIATED' AND expires_at < now()-10m: (user closed tab mid-upload) First runs HEAD / ListParts! - Complete & valid? -> confirm_upload() (rescues lost event!) - Incomplete/empty? -> AbortMultipartUpload + CAS -> EXPIRED 2. Unrecorded S3 multipart upload Daily ListMultipartUploads > 24h old with no DB session -> (API crashed right after CreateMultipart) AbortMultipartUpload (+ 10-day S3 lifecycle rule backstop) 3. Processing crash loop 5-min sweep finds state='PROCESSING', lease expired, processing_attempt >= 5 -> CAS -> FAILED, delete quarantine 4. Unsent composer attachment Daily sweep finds state='ACTIVE', created_at < now()-24h, (file uploaded & scanned, message cancelled) attachment_count = 0 -> CAS ACTIVE->DELETED WHERE count=0 5. Orphaned Clean Bucket object Daily S3 Inventory diff vs. Postgres ACTIVE rows (with 48h (copied to clean, then DB transaction died) grace window for in-flight workers) -> delete unreferenced keysNotice the crucial race-condition guard on #4: posting a message runs
UPDATE files SET attachment_count = attachment_count + 1 WHERE file_id = :id AND state IN ('UPLOADED', 'PROCESSING', 'ACTIVE'), while the unattached-file sweeper runsUPDATE files SET state = 'DELETED' WHERE file_id = :id AND state = 'ACTIVE' AND attachment_count = 0. Because both touch the exact samefilesrow lock, a message sent at the exact millisecond of cleanup either incrementsattachment_countto1(blocking deletion) or receives409 Conflict— never a broken link!Mitigating presigned-URL abuse
Even though computing an HMAC costs microseconds, each
/uploadscall inserts rows and reserves quota. We defend initiation with: - Token-bucket rate limits (a counter that refills at a steady rate, e.g.,60/minand2,000/dayper user, plus workspace and IP limits at the edge). - Concurrency caps: At most20openINITIATEDsessions or5 GBof unfinished bytes per user; workspace storage quota is reserved onINITIATEDand released onEXPIRED,FAILED, orDELETED. - Completion-ratio throttling: Users who initiate dozens of sessions with near-zero completions get dynamically throttled to1concurrent upload at a time.Failure modes, scaling, and trade-off summary
Failure scenario System behavior & recovery Network drops mid-upload Single-part retries with the same presigned POST; multipart queries GET /uploads/{id}(ListParts) and uploads only missing16 MiBparts.S3 notification delayed, dropped, or duplicated /completeand the 5-minute reconciler also callconfirm_upload(); SQL CASWHERE state = 'INITIATED'guarantees only the first caller triggers processing.Worker dies mid-transcode Heartbeat stops; lease_untilexpires after 10 min; next worker claimsprocessing_attempt + 1, overwrites deterministic Clean Bucket keys, and fences out the dead worker.Malware scanner service outage Workers fail closed (files stay in PROCESSING, never promoted toACTIVE); queue-age alert pages on-call; backlog drains once scanner recovers.Postgres shard temporarily down New initiations return 503(clients retry with sameclient_upload_id); in-flight byte uploads to S3 still succeed, and S3 events buffer safely in SQS (14-day retention) until DB recovers.Key observability metrics:
INITIATED -> UPLOADEDconversion ratio,UPLOADED -> ACTIVEp50/p99 latency per worker pool (fast vs. slow), oldest job age in queues, count of files rescued by the reconciler (a spike reveals broken S3 event delivery!), quarantine byte volume, and incomplete multipart bytes.Summary of core trade-offs
- Direct-to-S3 control/data split vs. API proxy: Saves
~5 Gbit/speak API bandwidth and double transfer fees, in exchange for a 3-step handshake and cross-system reconciliation. - Separate Quarantine + Clean buckets vs. single bucket with object tags: Costs one fast server-side copy per file, but makes unscanned-file isolation structural rather than dependent on IAM tag-policy perfection.
- Convergent triggers + SQL CAS + fencing tokens vs. trusting queue delivery: Guarantees exactly-once state transitions despite lost or duplicate cloud events, at the cost of running a 5-minute reconciler.
- Immediate placeholder messages vs. blocking message send on scan/transcode: Keeps chat snappy even on 1 GB videos while still blocking file access until
ACTIVE, at the cost of rendering placeholder and failure states in the UI.
- Direct-to-S3 control/data split vs. API proxy: Saves
Intuition & how it works
Think of this system like a hotel luggage check-in desk with a screened security room. If every guest shoved giant trunks through the narrow front-desk window (your chat API servers), the lobby would jam up immediately. Instead, the receptionist checks your room key, prints a tamper-proof barcode tag valid for 15 minutes and one exact suitcase weight — a presigned capability (a temporary, cryptographically signed upload ticket that lets a client write one specific cloud object without seeing master cloud credentials) — and directs you straight to the loading dock, an isolated quarantine bucket in object storage (cloud blob storage like Amazon S3 or Google Cloud Storage). Backstage, security staff X-ray the bag for contraband and verify its contents before moving it into the guest pickup lounge (clean bucket) and ringing your room phone so everyone in the chat channel can open it.
Why do simpler approaches fail? Proxying 15.5 TB/day (~5 Gbit/s at peak) through API servers ties up memory and open sockets for minutes on slow mobile links, doubles cloud bandwidth charges, and forces a 1 GB video to restart from zero if Wi-Fi drops at 95%. Conversely, letting clients upload directly into a public bucket or trusting a user-declared Content-Type: image/png header allows attackers to upload multi-gigabyte junk, overwrite other users' files, or plant malicious HTML/JavaScript that executes inside coworkers' browsers. Finally, relying solely on cloud storage event notifications leaves files stuck forever when an event is delayed or triggers duplicate transcodes when an event is delivered twice.
Here is a concrete 5-step trace of a 600 KB screenshot (wireframe.png) shared in channel ch_19:
t = 0.0 s 1. Initiate Client sends POST /v1/uploads (size=614400, client_upload_id="cu_4d9b").
API checks ch_19 membership, inserts file fil_s04_31f9 (state=INITIATED),
and locally HMAC-signs a 15-min S3 POST policy locked to 614,400 bytes.
t = 0.4 s 2. Upload Client POSTs the 614,400 bytes straight to S3 key q/6c/upl_s04_6c1a/blob.
t = 0.5 s 3. Confirm Client calls POST /complete AND S3 fires an ObjectCreated event to SQS.
Both run SQL compare-and-set (CAS):
UPDATE files SET state='UPLOADED' WHERE file_id=... AND state='INITIATED'
The first caller updates 1 row and queues 'file.process' via the outbox;
the second updates 0 rows and exits harmlessly.
t = 0.6 s 4. Placeholder Sender posts their chat message; viewers see a safe placeholder card.
t = 1.4 s 5. Release Fast-pool worker claims attempt=1, verifies SHA-256 + PNG magic bytes +
malware scan, writes thumbnail + clean copy to Clean Bucket, runs fenced CAS
PROCESSING (attempt=1) -> ACTIVE, deletes quarantine blob, and pushes ACTIVE
over WebSocket so channel viewers immediately see the rendered image.
Key trade-offs
- Direct-to-object-store vs. API byte proxying: Offloading byte transfers to S3/GCS eliminates
~5 Gbit/sof peak API bandwidth and long-lived mobile connections, leaving our backend with~600/stiny JSON requests. The trade-off is split state between PostgreSQL and object storage, which requires a multi-step handshake and a reconciler (a scheduled background worker that repairs drift between database rows and stored objects). - Presigned POST policy (single-part) + backend-completed multipart vs. raw presigned PUT: An S3 presigned POST policy pins an exact
content-length-rangefor files<= 25 MB, while keepingCompleteMultipartUploadexclusively on the backend lets us verify part counts and sizes viaListPartsbefore assembling files up to1 GB. This adds one/completeround trip compared to client-completed uploads, but prevents size-limit bypasses. - Physical quarantine bucket + copy vs. single bucket with object tags: Storing unscanned uploads in a locked-down quarantine bucket with no CDN (Content Delivery Network — edge caches that serve files close to users) and copying verified files to a separate clean bucket briefly stores bytes twice and pays for one server-side copy, but makes accidental exposure of malware or unverified files structurally impossible.
- Convergent triggers + SQL compare-and-set vs. trusting storage events alone: Triggering
confirm_upload()from/complete, S3 events, and the 5-minute reconciler — serialized by an atomic SQLUPDATE ... WHERE state = 'INITIATED'and a transactional outbox (a queue table written in the same database transaction as the state change) — guarantees no lost or duplicate transitions, at the cost of operating the reconciler and outbox relay. - Separate fast and slow worker pools vs. one shared queue: Isolating
~174cores of slow video transcoding from~8cores of fast image/document scanning prevents head-of-line blocking so screenshots becomeACTIVEin ~1 second, at the cost of managing two autoscaling worker deployments. - Decoupled message placeholders vs. blocking message send until
ACTIVE: Allowing users to send a chat message as soon as bytes areUPLOADEDkeeps conversations fluid during a 2-minute video transcode while still withholding file access untilACTIVE, at the cost of building placeholder and failure states in the chat client.
Common mistakes
- Letting clients choose the object key or embedding raw filenames in keys: Allows attackers to overwrite another user's object, trigger key collisions, or exploit
../path confusion. Always generate opaque server keys (q/6c/<upload_id>/blob) and store sanitized filenames in the database. - Trusting client-declared
Content-Typeand serving uploads inline from the app domain: An attacker can declareimage/pngwhile uploading an.htmlor.svgscript, stealing chat session cookies via stored cross-site scripting (XSS). Always perform magic-byte sniffing (checking binary header signatures in the raw file bytes) and serve downloads from a separate cookieless domain withX-Content-Type-Options: nosniff. - Treating S3/GCS notifications as instant and exactly-once: Cloud storage events are at-least-once and occasionally delayed by a minute or more; without
/complete+ reconciler fallbacks and conditionalWHERE state = ...updates, uploads get stuck inINITIATEDor trigger duplicate processing. - Using a fixed worker timeout without lease heartbeats and fencing tokens: A
1 GBvideo transcode that legitimately takes 12 minutes will expire a static 10-minute lock, causing a second worker to start the same job and overwrite results unless workers renew their lease heartbeat and guard their final commit with a monotonicprocessing_attemptfencing token (a counter ensuring an older, stalled worker's late write is rejected). - Placing cross-day idempotency constraints on a day-partitioned table: In PostgreSQL,
UNIQUEconstraints on partitioned tables must include the partition key (created_at), so a client retry across midnight creates a duplicate file unlessUNIQUE (uploader_id, client_upload_id)lives on the unpartitionedfilestable. - Forgetting to abort incomplete multipart uploads: Uploaded parts of an abandoned multipart session do not appear in standard bucket object listings, yet cloud providers bill full storage price for them indefinitely until
AbortMultipartUpload(or a bucketAbortIncompleteMultipartUploadlifecycle rule) removes them. - Deleting expired
INITIATEDsessions without checking object storage first: If a client uploaded every byte and crashed right before/completewhile the S3 event was delayed, blindly marking the rowEXPIREDand deleting the key destroys a valid user upload instead of rescuing it viaHEAD/ListParts.
Follow-up questions
- Walk through how a mobile client uploading a 1 GB video over spotty Wi-Fi splits the file into chunks and resumes after a disconnect without resending finished chunks. When initiating a
1 GBupload, the backend callsCreateMultipartUploadwith a fixed16 MiBpart size (64parts) and the client savesupload_idalongside a local file fingerprint (size, modification time, and hashes of the first and last1 MiB) so it can recognize the file even after an app restart. After a disconnect, the client callsGET /v1/uploads/{upload_id}, where the backend queries object storage viaListParts(the authoritative source of truth for stored chunks) and returns the completed part numbers and ETags (per-part content digests). The client then requests fresh 15-minute presignedUploadPartURLs only for the missing part numbers, uploads them, and calls/completeso the backend can verify all64part sizes before callingCompleteMultipartUpload; a sliding 24-hour session TTL (up to 7 days) plus a 10-day bucket abort lifecycle rule clean up truly abandoned sessions. - What safeguards stop an abusive client from exhausting database capacity or storage quotas by requesting millions of upload URLs and never sending any bytes? Generating a single-part presigned policy is a local HMAC calculation that makes zero calls to S3, so the real resource to protect is database metadata and workspace storage quota. We enforce token-bucket rate limits (counters that refill steadily, e.g.,
60/minper user and per IP) at the API gateway, cap each user at20concurrentINITIATEDsessions and5 GBof unfinished declared bytes, and reserve workspace quota upon initiation (releasing it onEXPIRED,FAILED, orDELETED). Presigned capabilities expire in15minutes, multipart URLs are dispensed in small 16-part batches, dailyupload_sessionstable partitions are dropped wholesale after 30 days so dead rows never bloat indexes, and users with a high initiated-to-completed ratio are dynamically throttled. - Cloud storage event queues can delay, duplicate, or drop notifications—how do you ensure every valid upload still reaches the ACTIVE state once and only once? If a queue notification is dropped, two redundant paths — the client's
POST /completecall and the 5-minute reconciler'sHEAD/ListPartscheck on staleINITIATEDrows — call the sameconfirm_upload()function to advance the file. If notifications are duplicated, every state step uses an atomic SQL compare-and-set (UPDATE files SET state = 'UPLOADED' WHERE file_id = :id AND state = 'INITIATED') inside the same transaction as the transactional outbox insert, so only one caller updates1row while duplicates update0rows and exit. During worker verification, claiming a job incrementsprocessing_attempt, and the final promotion runsUPDATE files SET state = 'ACTIVE', version = version + 1 WHERE file_id = :id AND state = 'PROCESSING' AND processing_attempt = :my_attempt, guaranteeing thatACTIVEcommits exactly once while deterministic Clean Bucket keys and(file_id, version)tags make any retried side effects idempotent.
Follow-up questions
- Walk through how a mobile client uploading a 1 GB video over spotty Wi-Fi splits the file into chunks and resumes after a disconnect without resending finished chunks.
- What safeguards stop an abusive client from exhausting database capacity or storage quotas by requesting millions of upload URLs and never sending any bytes?
- Cloud storage event queues can delay, duplicate, or drop notifications—how do you ensure every valid upload still reaches the ACTIVE state once and only once?
Similar questions
- Tamper-Evident Multi-Tenant Audit Trail Architecture
- Architectural Walkthrough of a Past Engineering System
- Multi-Cloud Object Storage Upload Client
- Multi-Cloud Direct Upload Layer
- Architectural Deep Dive on a Complex Engineering Project
- Senior Engineering Project Deep Dive: Architecture, Scale, and Trade-Offs
More Legora interview questions
- Senior Engineering Project Deep Dive: Architecture, Scale, and Trade-Offs Medium
- Architectural Walkthrough of a Past Engineering System Medium
- Multi-Cloud Direct Upload Layer Medium Pro
- Multi-Cloud Object Storage Upload Client Medium Pro
- Tamper-Evident Multi-Tenant Audit Trail Architecture Hard Pro
- Architectural Deep Dive on a Complex Engineering Project Medium Pro