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, and EXPIRED.
    • 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 million daily active users uploading 5 million attachments per day (~200 uploads/sec at peak), with images up to 25 MB, videos and archives up to 1 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

  1. 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 to 1 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, and EXPIRED.
    • 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: 20M daily active users (DAU), 5M files/day (~58/s average, ~200 uploads/s peak), images up to 25 MB, videos and archives up to 1 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 to ACTIVE.
    • 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.
  2. 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:

    1. Bytes, not JSON requests, are the load: Direct upload keeps 5 Gbit/s of peak traffic off our API servers, leaving just ~600 requests/s that a few stateless instances handle effortlessly.
    2. Video transcoding dominates CPU (~174 cores vs. ~8 cores for everything else): Videos must run on a separate slow worker queue so a 500 KB screenshot never waits behind a 1 GB video.
    3. 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.
  3. API and upload handshake

    Files up to 25 MB (all images and most documents) use a single-part upload. Larger files (> 25 MB up to 1 GB) use multipart upload (an object-storage feature that accepts fixed-size slices independently and stitches them into one object on the server) with 16 MiB parts — at most 64 parts for 1 GB, comfortably inside S3's 5 MiB minimum part size and 10,000-part ceiling.

    When initiating an upload, the client supplies a client_upload_id idempotency 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 MB to 1 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 call CompleteMultipartUpload directly; otherwise a client could assemble 10,000 oversized parts and bypass our 1 GB cap. - 202 Accepted instead of 200 OK: Completion means "bytes landed in quarantine," not "safe to view."

  4. Data model and lifecycle state machine

    We store metadata in PostgreSQL sharded by workspace_id so all channels, messages, and files for one customer live on the same database shard. Both upload_id (upl_s04_...) and file_id (fil_s04_...) embed the shard number (s04) so background workers receiving an S3 object key or download requests carrying only a file_id can route directly to shard 04 without 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 outbox table written inside the exact same SQL transaction as the files state 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) on files instead of upload_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 unpartitioned files makes idempotency airtight across days, while letting us drop old upload_sessions daily 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)
                                                  +------------+
    
  5. 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 URLs
    

    Here is how one upload flows end to end: 1. Authorize: Upload API verifies channel membership, checks workspace MIME allowlist and rate limits, writes INITIATED rows in Postgres, and returns a presigned capability. 2. Transfer: Client uploads bytes straight to the private Quarantine Bucket. 3. Confirm: S3 emits an ObjectCreated event to SQS, and the client also calls /complete. Both invoke the same idempotent confirm_upload() routine to move INITIATED -> UPLOADED. 4. Dispatch: The UPLOADED transaction writes an outbox job 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, transitions PROCESSING -> ACTIVE, and queues deletion of the quarantine copy. 6. Release: Outbox notifies the Realtime Gateway to push ACTIVE to 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.

  6. 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 PUT URL signs the target key and Content-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,400 bytes (600 KB) and sends 614,401 bytes or 1 GB, S3 immediately aborts the socket. (On Google Cloud Storage, V4 signed PUT URLs achieve the same lock via a signed x-goog-content-length-range header, and S3/GCS create-only headers If-None-Match: * / ifGenerationMatch=0 guarantee no existing object can ever be overwritten.)

    2. Batched part URLs + backend inspection for multipart uploads

    Individual S3 UploadPart URLs cannot constrain the sum of all parts. Instead: - We issue presigned UploadPart URLs in small batches of up to 16 parts at a time, each expiring in 15 minutes. - When the client calls /complete, our backend calls S3 ListParts and verifies that len(parts) == part_count, every interior part equals 16 MiB, and sum(part.size) == declared_size. If anything mismatches, the backend calls AbortMultipartUpload and marks the file FAILED without 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:GetObject exclusively 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.html to cat.png and send Content-Type: image/png. Workers perform magic-byte sniffing (inspecting the raw binary file header signatures — such as 89 50 4E 47 for PNG or 25 50 44 46 for PDF — rather than trusting filenames or HTTP headers). If the sniffed type violates workspace policy, the file moves to FAILED: 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) with X-Content-Type-Options: nosniff and Content-Disposition: attachment for non-media types, preventing stored cross-site scripting (XSS) in the chat web app.
  7. 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 ACTIVE exactly once?

    We combine convergent triggers with compare-and-set (CAS) database updates (conditional UPDATE ... WHERE statements that atomically check the current state before changing it, returning 1 row updated to the single winner and 0 to 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 PROCESSING

    Once file.process lands 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_until renewed 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):

    1. 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 gets attempt = 1.
    2. 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.webp so retries overwrite cleanly without leaking duplicates), and server-side copies the verified original to f/<ws>/<file_id>/original.
    3. Fenced commit to ACTIVE: Worker A commits UPDATE 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 for file.state_changed and quarantine.delete (deleting the quarantine copy immediately saves ~200 TB of 14-day duplicate storage!). If Worker A stalled and Worker B already claimed attempt = 2, Worker A's final UPDATE matches 0 rows and cleanly aborts.
  8. 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 -> UPLOADED
    

    Each part-urls call slides the multipart session's expires_at forward by 24 hours (capped at 7 days from 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 ListObjects API 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 keys
    

    Notice 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 runs UPDATE files SET state = 'DELETED' WHERE file_id = :id AND state = 'ACTIVE' AND attachment_count = 0. Because both touch the exact same files row lock, a message sent at the exact millisecond of cleanup either increments attachment_count to 1 (blocking deletion) or receives 409 Conflict — never a broken link!

    Mitigating presigned-URL abuse

    Even though computing an HMAC costs microseconds, each /uploads call inserts rows and reserves quota. We defend initiation with: - Token-bucket rate limits (a counter that refills at a steady rate, e.g., 60/min and 2,000/day per user, plus workspace and IP limits at the edge). - Concurrency caps: At most 20 open INITIATED sessions or 5 GB of unfinished bytes per user; workspace storage quota is reserved on INITIATED and released on EXPIRED, FAILED, or DELETED. - Completion-ratio throttling: Users who initiate dozens of sessions with near-zero completions get dynamically throttled to 1 concurrent upload at a time.

  9. 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 missing 16 MiB parts.
    S3 notification delayed, dropped, or duplicated /complete and the 5-minute reconciler also call confirm_upload(); SQL CAS WHERE state = 'INITIATED' guarantees only the first caller triggers processing.
    Worker dies mid-transcode Heartbeat stops; lease_until expires after 10 min; next worker claims processing_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 to ACTIVE); queue-age alert pages on-call; backlog drains once scanner recovers.
    Postgres shard temporarily down New initiations return 503 (clients retry with same client_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 -> UPLOADED conversion ratio, UPLOADED -> ACTIVE p50/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/s peak 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.

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/s of peak API bandwidth and long-lived mobile connections, leaving our backend with ~600/s tiny 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-range for files <= 25 MB, while keeping CompleteMultipartUpload exclusively on the backend lets us verify part counts and sizes via ListParts before assembling files up to 1 GB. This adds one /complete round 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 SQL UPDATE ... 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 ~174 cores of slow video transcoding from ~8 cores of fast image/document scanning prevents head-of-line blocking so screenshots become ACTIVE in ~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 are UPLOADED keeps conversations fluid during a 2-minute video transcode while still withholding file access until ACTIVE, 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-Type and serving uploads inline from the app domain: An attacker can declare image/png while uploading an .html or .svg script, 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 with X-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 conditional WHERE state = ... updates, uploads get stuck in INITIATED or trigger duplicate processing.
  • Using a fixed worker timeout without lease heartbeats and fencing tokens: A 1 GB video 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 monotonic processing_attempt fencing 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, UNIQUE constraints on partitioned tables must include the partition key (created_at), so a client retry across midnight creates a duplicate file unless UNIQUE (uploader_id, client_upload_id) lives on the unpartitioned files table.
  • 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 bucket AbortIncompleteMultipartUpload lifecycle rule) removes them.
  • Deleting expired INITIATED sessions without checking object storage first: If a client uploaded every byte and crashed right before /complete while the S3 event was delayed, blindly marking the row EXPIRED and deleting the key destroys a valid user upload instead of rescuing it via HEAD / 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 GB upload, the backend calls CreateMultipartUpload with a fixed 16 MiB part size (64 parts) and the client saves upload_id alongside a local file fingerprint (size, modification time, and hashes of the first and last 1 MiB) so it can recognize the file even after an app restart. After a disconnect, the client calls GET /v1/uploads/{upload_id}, where the backend queries object storage via ListParts (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 presigned UploadPart URLs only for the missing part numbers, uploads them, and calls /complete so the backend can verify all 64 part sizes before calling CompleteMultipartUpload; 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/min per user and per IP) at the API gateway, cap each user at 20 concurrent INITIATED sessions and 5 GB of unfinished declared bytes, and reserve workspace quota upon initiation (releasing it on EXPIRED, FAILED, or DELETED). Presigned capabilities expire in 15 minutes, multipart URLs are dispensed in small 16-part batches, daily upload_sessions table 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 /complete call and the 5-minute reconciler's HEAD/ListParts check on stale INITIATED rows — call the same confirm_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 updates 1 row while duplicates update 0 rows and exit. During worker verification, claiming a job increments processing_attempt, and the final promotion runs UPDATE files SET state = 'ACTIVE', version = version + 1 WHERE file_id = :id AND state = 'PROCESSING' AND processing_attempt = :my_attempt, guaranteeing that ACTIVE commits exactly once while deterministic Clean Bucket keys and (file_id, version) tags make any retried side effects idempotent.

Follow-up questions

Similar questions

More Legora interview questions

All 7 Legora questions →