Design a Custom Playlist Artwork Upload and Delivery Service

Medium · System Design · Backend Engineer · Onsite

Prompt

On a large music-streaming platform, listeners customize their playlists by attaching custom cover art, swapping in updated artwork later, or reverting to the default generated cover. Once published, a playlist's custom cover must load reliably over the public web with zero viewer authentication so it renders seamlessly inside native mobile and desktop apps, third-party embedded web widgets (<iframe> players hosted on external sites), social-sharing cards, and public web pages.

Your service operates alongside established platform microservices rather than duplicating their responsibilities: an identity service already authenticates user credentials, and an authoritative playlist service manages playlist records and edit permissions.

Operating rules and open questions to clarify:

  • A playlist exhibits at most one active custom cover at any point in time.
  • The playlist service remains the sole source of truth for playlist existence, visibility, ownership, and collaborator edit rights; your service consults it rather than maintaining a local shadow copy of playlist ACLs.
  • Public image fetches never require viewer sign-in, ensuring anonymous visitors on external pages see embedded artwork immediately.
  • Traffic scale, file-size ceilings, permitted image formats, required display resolutions, content-moderation checks, and lifecycle behavior when a playlist turns private or gets deleted are left open — state the questions you would ask and the concrete numbers you assume.

Walk through the design across three progressive stages:

  1. Core upload, storage, and global serving: Define the APIs, storage schema, and service components. Trace the write flow from file selection until replacement artwork appears everywhere, the unauthenticated CDN read flow used by external embeds, integration with the identity and playlist services, and how downstream consumers learn about cover updates.
  2. Compliance and safety auditing: Design how an internal compliance or trust-and-safety reviewer inspects historical artwork changes — what immutable history and archived media they can view, how access stays strictly read-only and scoped so reviewers cannot alter or exfiltrate production data, how retention works for replaced or deleted covers, and how reviewer queries themselves are logged.
  3. Failure handling across ingest and processing: Trace what happens when mobile uploads drop mid-transfer, clients submit corrupt or hostile files, image-resizing workers crash, or database writes fail after derivatives are generated — ensuring safe retries, orphan cleanup, and an unbroken invariant that no playlist ever points to missing or partially processed files.

Scope & Expectations

  • Ingest, integration, and public delivery: Direct-to-object-storage upload flow, live authorization checks against the playlist service, immutable derivative storage, cache-friendly CDN URLs, and reliable event fan-out to downstream services.
  • Atomic pointer updates: Separating heavy binary media from the lightweight active-cover pointer so replacements and deletions cut over atomically without broken intermediate states.
  • Tamper-evident auditability: Append-only mutation history capturing actor, timestamp, and before/after artwork references, paired with isolated read-only reviewer tooling, retention locks, and access logging.
  • Resilient upload lifecycle: Explicit upload states, untrusted-image validation, idempotent worker retries, abandoned-upload garbage collection, and actionable operational alerts.

Step-by-step walkthrough

  1. Clarify requirements and boundaries

    Playlist covers have a lopsided workload—very few writes compared with billions of public reads—and our service sits between two existing platform services it must integrate with rather than rebuild: the identity service (which authenticates who the caller is) and the playlist service (which owns who may edit each playlist). Start by pinning down the open product rules and stating concrete assumptions:

    • Who may change a cover? Anyone the playlist service authorizes to edit that playlist's details (the owner, plus collaborators when shared-editing permissions allow it). Our image service queries the playlist service on every write and never keeps a shadow copy of playlist ownership.
    • What happens when a playlist is deleted vs. made private?
      • Deleted: hard unpublish—clear the active pointer, delete all public image sizes, purge them from the CDN within minutes, and retain a restricted review copy solely for compliance audits.
      • Made private: playlist metadata stops returning the cover to unauthenticated callers, so third-party embeds and shared links immediately render "unavailable." The random, unguessable image URL stays live for the owner's signed-in app (or, if strict policy requires, private playlists move covers behind short-lived signed URLs just like deleted ones).
    • Accepted formats, dimensions, and safety: accept JPEG, PNG, and WebP up to 10 MB (mobile clients convert HEIC to JPEG locally before uploading), between 300 x 300 px and 8,000 x 8,000 px (<= 40 megapixels total). Reject SVG (an XML format that can embed executable JavaScript) and animated images. Covers are square (client sends crop coordinates; server center-crops otherwise). During re-encoding, apply EXIF orientation (rotation tags set by phone cameras) and strip all EXIF metadata so a user's home GPS coordinates never leak in a public image.
    • Generated display sizes: 64 px (compact rows), 300 px (grids and standard embeds), 640 px (playlist header and large embeds), and 1200 px (social link previews), each saved in both WebP and JPEG (8 public files per cover).
    • Content checks: run a fast cryptographic/perceptual hash check against known illegal material before publishing, and run broader ML policy classification asynchronously right after publishing (with instant takedown). Pre-publication gating is covered in the follow-ups.

    Functional requirements: upload, replace, and remove a playlist cover; poll upload progress; serve covers publicly at low latency to apps and third-party embeds without sign-in; emit change events to downstream services; provide tamper-evident audit history (Stage 2); and recover cleanly from upload or worker failures (Stage 3).

    Non-functional requirements:

    • Public reads: P95 < 100 ms from the CDN (Content Delivery Network)—edge cache servers distributed close to viewers—continuing to work even if our backend service is completely down.
    • Write-to-live speed: P95 < 10 seconds from completed byte upload to LIVE state, propagating across embeds and app surfaces within ~1-2 minutes.
    • Atomicity: a playlist must never point to a missing, corrupt, or half-resized image.
    • Auditability: every state change records who did it, when, and both the before and after images.
  2. Back-of-the-envelope numbers

    Playlists and traffic (assumed platform scale)
      Total playlists                     4B total; 5% have a custom cover -> 200M live custom covers
      Uploads (new + replacements)        2M/day  -> ~23 uploads/s avg, ~120 uploads/s peak (5x)
      Retirements (replaced + deleted)    ~2.2M/day
      Public image views                  10B/day -> ~116,000 views/s avg, ~350,000 views/s peak (3x)
    
    Per-cover file sizes
      Raw uploaded photo                  ~2 MB average (10 MB max)
      Normalized master (<= 2048 px)      ~0.6 MB (kept privately while live to generate future sizes)
      Public derivatives (4 sizes x 2)    ~0.75 MB total across the 8 WebP + JPEG files
    
    Storage footprint
      Live covers (masters + public)      200M x (0.6 + 0.75) MB = ~270 TB (~120 TB masters + ~150 TB public)
      Raw originals (kept 30 days)        2M/day x 2 MB x 30 d   = ~120 TB (restricted bucket)
      Audit review copies (kept 1 year)   2.2M/day x ~0.3 MB (1200 px JPEG) x 365 d = ~241 TB/year (cold)
      Audit event rows                    2.2M/day x ~500 B      = ~1.1 GB/day
    
    Network & compute
      CDN egress (avg ~40 KB served)      10B x 40 KB = ~400 TB/day (~37 Gbit/s avg, ~111 Gbit/s peak)
      Origin storage misses (>=99% hit)   <= 3,500 req/s at peak across all regions
      Peak ingest bandwidth               120/s x 2 MB = ~240 MB/s directly into object storage
      Image resize CPU (~0.5 core-s/img)  120/s x 0.5 s = ~60 CPU cores at peak -> run ~100 cores for bursts
    

    Three design lessons jump right out of these numbers:

    • Reads outnumber writes 5,000 to 1 (116k/s vs. 23/s): the public read path must go straight from viewer browsers to a CDN backed by object storage, never touching cover-service or its database. That requires immutable image URLs safe to cache for a full year.
    • Writes are low-QPS but byte-heavy (2 MB average, 10 MB max): streaming raw bytes through application servers wastes connections on slow mobile uploads, so clients should upload directly to object storage.
    • Metadata fits a single relational cluster: 200M pointer rows (~25 GB) and ~120 peak uploads/s (~1,000 small row updates/s across lifecycle steps) fit comfortably on one primary PostgreSQL instance with synchronous standbys—no database sharding needed.
  3. API design and immutable image URLs

    Two patterns keep the upload API fast and retry-safe:

    • Pre-signed URL: a temporary, cryptographically signed object-storage URL generated by our backend that lets the client PUT one exact object key with a fixed Content-Type and Content-Length within 15 minutes—without routing file bytes through our API servers. (Files > 5 MB receive multipart pre-signed URLs so dropped mobile connections resume individual chunks.)
    • Idempotency key: a client-generated UUID sent in the Idempotency-Key header so retrying a timed-out POST returns the existing upload session instead of creating duplicates.
    1) Start upload session (authenticated via API Gateway)
       POST /v1/playlists/{playlist_id}/cover-uploads
            Authorization: Bearer <token>
            Idempotency-Key: 6c8e4a10-...
            {"content_type": "image/jpeg", "size_bytes": 1948210, "sha256": "a4f1...",
             "crop": {"x": 0, "y": 80, "w": 2400, "h": 2400}}
       -> 201 Created
            {"upload_id": "up_4Km2", "state": "CREATED", "expires_at": "2026-11-30T16:15:00Z",
             "upload_url": "https://<staging-store>/staging/up_4Km2?<sig>", "method": "PUT",
             "required_headers": {"Content-Type": "image/jpeg", "Content-Length": "1948210"}}
       (Errors: 403 NOT_ALLOWED | 413 TOO_LARGE | 415 UNSUPPORTED_TYPE | 503 PERMISSION_CHECK_UNAVAILABLE)
    
    2) Upload raw bytes directly to object storage
       PUT <upload_url>   (binary image body)
    
    3) Mark bytes uploaded & poll status (or renew expired PUT URL)
       POST /v1/playlists/{playlist_id}/cover-uploads/{upload_id}/complete  -> 202 {"state": "PROCESSING"}
       GET  /v1/playlists/{playlist_id}/cover-uploads/{upload_id}           -> 200 {"state": "LIVE", "cover": {...}}
       POST /v1/playlists/{playlist_id}/cover-uploads/{upload_id}/renew-url -> 200 {"upload_url": "..."}
    
    4) Remove custom cover (optimistic concurrency via If-Match)
       DELETE /v1/playlists/{playlist_id}/cover    If-Match: "15"           -> 204 No Content
    
    5) Public cover lookup (cached 60 s at CDN; most surfaces read URLs directly from playlist metadata)
       GET /v1/playlists/{playlist_id}/cover
       -> 200 {"playlist_id": "...", "image_id": "img_9a2c...", "version": 15,
               "urls": {"64": "https://img.<cdn>/c/img_9a2c.../64.webp", "300": "...", "640": "...", "1200": "..."},
               "jpeg_urls": {"64": "https://img.<cdn>/c/img_9a2c.../64.jpg", ...}}
    

    Public CDN image URLs and downstream Kafka events:

    Image URL:  https://img.<cdn-domain>/c/{image_id}/{64|300|640|1200}.{webp|jpg}
    Headers:    Cache-Control: public, max-age=31536000, immutable
                X-Content-Type-Options: nosniff    (served from a cookie-less static domain)
    
    Kafka topic: playlist-cover-changed   (partition key = playlist_id to preserve per-playlist order)
    Payload:     {"playlist_id": "pl_84", "version": 15, "action": "SET | REPLACE | REMOVE | TAKEDOWN | UNPUBLISH",
                  "image_id": "img_9a2c...", "previous_image_id": "img_3d7e...",
                  "actor": {"type": "user", "id": "usr_23"}, "occurred_at": "..."}
    
  4. Data model: separating heavy bytes from the tiny pointer

    Two core invariants shape our data layout: separate immutable image bytes from the mutable playlist pointer, and store an append-only event log alongside current state. To publish Kafka messages reliably without dual-write bugs, we also include a transactional outbox—a table written inside the same database transaction as playlist_cover and drained asynchronously to Kafka by a background relay.

    PostgreSQL tables
      playlist_cover      Current pointer (1 row per playlist that ever had a cover; NEVER deleted)
        playlist_id PK, image_id (NULL when removed), version BIGINT (+1 per change),
        updated_at, updated_by, last_event_hash
    
      cover_uploads       Upload state machine (1 row per upload session)
        upload_id PK, playlist_id, user_id, UNIQUE (user_id, idempotency_key),
        image_id (128-bit random ID reserved up front), base_version BIGINT,
        state, declared_type, declared_size, sha256, crop, attempts, error_code, created_at, expires_at
    
      images              Immutable processed image metadata
        image_id PK (128-bit random hex), playlist_id, upload_id, uploader_id, master_sha256,
        width, height, status (READY | LIVE | REPLACED | REMOVED | TAKEN_DOWN | PURGED),
        created_at, retire_at
    
      cover_events        Append-only audit log (written in the SAME transaction as playlist_cover)
        event_id PK, playlist_id, version, action, actor_type (user | moderator | system),
        actor_ref (encrypted per-user key), before_image_id, after_image_id,
        authz_mode (checked | cached), request_id, occurred_at, prev_event_hash, event_hash
    
      outbox              Transactional Kafka relay queue
        outbox_id PK, topic, partition_key, payload, created_at, published_at
    
    Object storage buckets
      staging    (private)     staging/{upload_id}           auto-deleted after 24 h
      originals  (restricted)  orig/{image_id}               auto-deleted after 30 days
      masters    (private)     master/{image_id}.jpg         retained while cover is LIVE
      public     (CDN origin)  c/{image_id}/{size}.{fmt}     write-once; deleted 24 h after retirement
      archive    (restricted)  review/{image_id}.jpg         1200 px JPEG under 1-year retention lock
    

    Why three subtle schema choices prevent classic bugs:

    • playlist_cover rows are nulled (image_id = NULL), never deleted: if DELETE /cover deleted the row, a later upload would reset version back to 1, causing downstream caches holding version = 15 to reject the new cover as stale.
    • base_version on cover_uploads catches overtaken uploads: when an upload session starts, it records the playlist's current version (0 if none). If another upload, a user DELETE, or a moderator TAKEDOWN increments playlist_cover.version while this upload is still resizing, the commit check sees version != base_version and marks the late upload SUPERSEDED instead of resurrecting an unwanted image.
    • 128-bit random image_ids: prevents scrapers from enumerating all covers (img_1, img_2, ...) or guessing URLs of private/retired playlists.
  5. High-level architecture

      Mobile / Web App                                   Third-Party Site with Embedded Player
         | 1. POST /cover-uploads, /complete                | <iframe>
         v                                                  v
      API Gateway (verifies JWT locally via              Embed Service (renders player HTML)
      Identity Service public signing keys)                 | reads playlist metadata (60 s CDN cache,
         |                                                  | purged on playlist-cover-changed)
         v                                                  v
      cover-service (stateless) ---CheckPermission---> Playlist Service (source of truth for ownership)
         |      |                                           | emits: playlist-deleted / made-private
         |      | returns pre-signed PUT URL                v
         |      |                                        Kafka
         |  2. PUT raw bytes -------> Staging Bucket
         |                               | (object-created event as backup trigger)
         v                               v
      PostgreSQL                     Job Queue ---> Sandboxed Image Workers
      (pointer, uploads, images,                     (magic-byte check, crop, EXIF strip,
       cover_events, outbox)                          8 derivatives + master + hash check)
         |                                                  | write-once
         | Outbox Relay                                     v
         v                                          Public Bucket: c/{image_id}/...
      Kafka: playlist-cover-changed                         ^
         |--> Playlist Service (updates cover URLs)         | cache misses only (<1%)
         |--> Search, Recommendations, Share Previews       |
         |--> CDN Purge Worker (purges 60 s metadata)   Origin Shield (1 per region)
         |--> WORM Audit Store <--- Audit Service           ^
                                        ^                   |
                              Internal Auditor (SSO+MFA)  CDN Edge <--- Public Viewers (no login)
    

    Notice the clean separation:

    • Control plane (cover-service): handles tiny JSON requests, delegates authentication to the API Gateway + Identity keys, and delegates edit authorization to Playlist Service.
    • Data plane (ingest): bytes move straight from client -> Staging Bucket -> Image Workers -> Public Bucket.
    • Data plane (public delivery): viewers and third-party embeds read cover URLs already embedded in Playlist Service metadata and fetch pixels from CDN Edge -> Origin Shield -> Public Bucket with zero dependency on cover-service.
  6. Deep dive 1: End-to-end write path and atomic pointer flip (Stage 1)

    Walk through what happens from the moment a user picks a photo (up_4Km2) on playlist pl_84 (currently showing img_3d7e at version = 14) until img_9a2c is live everywhere:

    Client          cover-service      Playlist Svc     Staging / Workers       PostgreSQL          CDN / Consumers
      |--create upload-->|--CheckPerm------>|                 |                     |                     |
      |<--pre-signed URL-|<--Allowed--------|                 |                     | (state=CREATED,     |
      |                                                       |                     |  base_version=14)   |
      |================ PUT 2 MB bytes ======================>|                     |                     |
      |--complete------->|----------------------------------->| resize 8 files      |                     |
      |                  |                                    | under c/img_9a2c/.. |                     |
      |                  |                  |<--CheckPerm-----|--all 8 written----->| SINGLE TRANSACTION: |
      |                  |                  |---Allowed------>|                     |  pointer -> img_9a2c|
      |                  |                                    |                     |  version -> 15      |
      |                  |                                    |                     |  + cover_events row |
      |                  |                                    |                     |  + outbox row       |
      |                  |                                    |                     |--------relay------->| metadata updated
    
    1. Session creation: cover-service calls PlaylistService.CheckPermission(user_id, pl_84, EDIT_DETAILS) (100 ms timeout), validates size (<= 10 MB) and MIME type, reserves upload_id and image_id = img_9a2c, records base_version = 14, and returns the 15-minute pre-signed PUT URL.
    2. Direct byte upload: the client uploads straight to staging/up_4Km2. On a slow 1 Mbit/s cellular link, a 10 MB upload takes ~80 seconds—object storage absorbs that idle socket instead of our API servers.
    3. Trigger processing: the client calls /complete (with an object-storage ObjectCreated event acting as an automatic fallback if the user closes the app right as the PUT finishes). Either path moves state to UPLOADED and enqueues a worker job via the outbox.
    4. Write-once image generation: a worker validates and decodes the image, checks hashes against known illegal content, writes master/img_9a2c.jpg plus all 8 files (64..1200 in webp and jpg) to c/img_9a2c/, verifies all 8 exist with non-zero byte length, and marks images.status = READY. Throughout all of this, playlist_cover still points to img_3d7e.
    5. Atomic pointer switch: the worker re-checks CheckPermission (in case a collaborator was removed or the playlist was deleted during resizing) and executes one PostgreSQL transaction:
      • Lock playlist_cover for pl_84. If playlist_cover.version != upload.base_version (meaning a newer upload, DELETE, or TAKEDOWN already committed), mark this upload SUPERSEDED and stop.
      • Update playlist_cover to image_id = img_9a2c, version = 15, and update last_event_hash.
      • Insert the cover_events audit record (before = img_3d7e, after = img_9a2c, version = 15).
      • Insert the outbox event (playlist-cover-changed, version = 15).
      • Mark upload = LIVE, img_9a2c = LIVE, and img_3d7e = REPLACED with retire_at = now + 24 hours.
    6. Downstream propagation: the outbox relay publishes to Kafka (at-least-once). Downstream services (Playlist Service, Embed Service, search, share-link previews) only apply an event if event.version > stored_version, making retries and out-of-order messages harmless.
  7. Deep dive 2: Public CDN delivery for embeds and untrusted-file safety (Stage 1)

    When a fan opens a third-party blog containing an embedded playlist <iframe>:

    1. The browser loads the embed HTML from our embed service, which reads playlist metadata (cached at the CDN for 60 s and actively purged when playlist-cover-changed arrives).
    2. The HTML renders a <picture> tag pointing at https://img.<cdn-domain>/c/img_9a2c/300.webp (with 300.jpg fallback).
    3. On a CDN edge hit (>99% of views), pixels return in ~20-50 ms with zero authentication. On a cold edge miss (for instance, right after a celebrity shares a playlist), the edge fetches through a regional origin shield—a shared mid-tier CDN cache that collapses thousands of simultaneous edge misses for the same URL into one read against the public bucket.

    Why old cover files wait 24 hours before deletion (except on takedowns):

    t = 0 s       DB transaction flips pointer to img_9a2c (v15); outbox relays Kafka event
    t = 1-60 s    Playlist metadata & embed HTML caches purge/expire; new viewers load /c/img_9a2c/...
    t = 0-24 h    Browsers still viewing HTML rendered at t = -5 s still load /c/img_3d7e/... without 404s!
    t = 24 h      Sweeper deletes /c/img_3d7e/* from public bucket (policy TAKEDOWN skips the 24 h wait)
    

    Hardening public hosting of user-uploaded files:

    • Cookie-less domain (img.<cdn-domain>): browsers never attach main-app session cookies, neutralizing cross-site scripting / cookie-theft risks.
    • Zero pass-through bytes: we never serve the user's raw uploaded bytes; every public file is freshly encoded from raw pixel buffers after stripping EXIF GPS/camera tags, and SVG is banned outright.
    • Explicit headers and URL-encoded format: Content-Type: image/webp (or image/jpeg) plus X-Content-Type-Options: nosniff stops browser MIME sniffing, and putting .webp/.jpg in the URL path avoids fragmenting CDN cache keys on Vary: Accept.
  8. Deep dive 3: Audit trail, tamper resistance, and privacy erasure (Stage 2)

    playlist_cover only answers "what cover is live right now?" (state). An internal compliance or trust-and-safety auditor investigating an abusive cover, a compromised account, or a legal takedown SLA needs complete, uneditable history:

    • Every mutation captured transactionally: because cover_events is written inside the exact same PostgreSQL transaction as playlist_cover, it is impossible for a cover to change—via user upload, collaborator edit, user delete, or moderator takedown—without recording occurred_at, playlist_id, version, action, actor_type, actor_ref, before_image_id, after_image_id, and authz_mode.
    • Isolated, read-only auditor surface: auditors never use the public API or production DB credentials. They use an internal-network Audit Service behind corporate SSO + MFA, requiring a time-boxed role (e.g., 7-day grant tied to a ticket/case ID). Its database user has SELECT-only privileges on replicas and the analytical audit store, and zero write endpoints exist on the service.
    • Preventing auditor data leaks: every search requires a case_id, actors display as pseudonymous tokens unless an explicit logged "unmask actor" permission is invoked, bulk exports (>1,000 rows) require secondary approval and embed a traceable watermark, and every auditor query, image view, and export writes to an independent security-owned access log.
    • Viewing retired covers safely: replaced and deleted covers are removed from the public CDN bucket, while a single 1200 px JPEG review copy lives in the private archive bucket. When an auditor inspects before_image_id, the Audit Service mints a 5-minute signed URL to archive/review/{image_id}.jpg.

    Tamper resistance + GDPR/privacy erasure without breaking hash chains:

    • WORM (Write Once, Read Many) storage and hash chains: cover_events stream from Kafka into object storage configured with Compliance-mode Object Lock (nobody, not even a root cloud administrator, can overwrite or delete files before the 7-year retention date). Each event stores event_hash = SHA256(prev_event_hash || event_fields) using playlist_cover.last_event_hash, and a daily Merkle/digest hash of all events is signed via KMS into a separate security AWS/GCP account so any tampered or missing row is mathematically detectable.
    • Reconciling 7-year immutable logs with user account deletion ("crypto-shredding"): when a user deletes their account and has no active legal hold, their cover images—including 1-year archive copies (stored under Governance-mode lock, which permits only a dedicated, audited erasure service to delete early)—are purged. Because compliance-locked cover_events files cannot be edited, actor_ref is stored encrypted with a per-user KMS/key-store key (Enc(user_key, user_id)). Deleting user_key (crypto-shredding) permanently anonymizes the actor while keeping every event row and hash chain 100% intact.
  9. Deep dive 4: Upload state machine, failures, and orphan cleanup (Stage 3)

    Giving each upload an explicit state machine—enforced with atomic conditional SQL updates (UPDATE cover_uploads SET state = 'PROCESSING' WHERE upload_id = $1 AND state = 'UPLOADED')—guarantees that duplicate queue deliveries, user retries, and worker crashes are completely safe:

    CREATED ---(bytes in staging + complete/webhook)---> UPLOADED ---(worker claims)---> PROCESSING
       |                                                                                   |     |
       | (no bytes after 24 h)                      transient storage/DB timeout           |     | corrupt bytes, >40 MP,
       v                                            (exp. backoff + jitter, max 5) --------+     | or 3 worker crashes
    EXPIRED                                         then -> FAILED_INTERNAL                      v
                                                                                           FAILED_INVALID
    PROCESSING ---(8 public files + master verified)---> READY
       |--> commit (permission OK & version == base_version) ---> LIVE
       |--> playlist_cover.version moved ahead -----------------> SUPERSEDED
       +--> permission revoked or playlist deleted -------------> CANCELLED
    
    What fails What the user sees Recovery & why playlist stays safe
    Mobile connection drops mid-PUT Upload progress pauses with "Retry"; old cover stays live Client resumes multipart PUT (calls /renew-url if >15 min); abandoned sessions turn EXPIRED after 24 h and staging lifecycle deletes partial bytes
    Corrupt file or fake .jpg extension Immediate clear message: "Unsupported or damaged image" Worker inspects file magic bytes (binary header signature), not Content-Type; marks FAILED_INVALID with zero retries
    Decompression bomb (tiny PNG claiming 50,000 x 50,000 px = 10 GB RGBA RAM) "Image dimensions exceed 8,000 x 8,000 limit" Worker reads width/height from file header before allocating pixel buffers and rejects > 40 megapixels immediately (FAILED_INVALID)
    Malicious file crashes C/C++ image decoder "Processing..." briefly, then "Unsupported image" Decoding runs in an isolated sandbox process (no network, 1 GB RAM cap, 20 s CPU limit—defending against parser CVEs like ImageTragick). After 3 crashes on one upload_id, mark FAILED_INVALID and copy raw file to engineering quarantine
    Object store or DB blip during resize "Processing..." for a few extra seconds Retry up to 5 times with exponential backoff + jitter; deterministic keys (c/{image_id}/...) make overwriting idempotent; after 5 tries -> FAILED_INTERNAL
    DB commit fails after all 8 files are READY "Processing..." briefly Worker retries the idempotent commit transaction; if still uncommitted after 1 h -> FAILED_INTERNAL and orphan sweeper cleans up c/{image_id}/...
    Collaborator removed or playlist deleted mid-resize "You no longer have permission to edit this playlist" Commit re-check fails -> mark CANCELLED; playlist_cover is untouched

    Garbage collection and split alerting:

    • Orphaned object sweeper: listing 1.6 billion public objects (200M x 8) via live LIST calls is expensive, so a daily batch job joins the cloud provider's daily bucket inventory manifest against PostgreSQL images and deletes any c/{image_id}/ prefix that is missing, failed, cancelled, superseded, or past retire_at—only once the objects are older than 48 hours so it can never race an in-flight upload.
    • Actionable alerts: page on-call if FAILED_INTERNAL > 1% over 15 minutes, processing P95 > 30 s, queue age > 2 min, or outbox lag > 60 s. Track FAILED_INVALID on a separate metric (normally user error, though a sudden 3x jump alerts client teams to a broken app encoder).
  10. Scaling bottlenecks and trade-off summary

    • CDN egress (~400 TB/day) is the #1 dollar cost: prioritizing WebP (25-35% smaller than JPEG), picking the exact 64/300/640 derivative per UI slot, and collapsing cold misses through regional origin shields save far more money than micro-optimizing backend servers.
    • Elastic worker pool: stateless sandboxed workers autoscale on queue oldest-message age (target < 15 s), absorbing playlist-sharing campaigns or year-end recap spikes smoothly.
    • Database longevity: keep playlist_cover and active cover_uploads lean in NVMe-backed PostgreSQL by archiving cover_events partitions older than 90 days to the analytical/WORM audit store.
    • Multi-region uploads: clients PUT into the nearest regional staging bucket and local workers write to a globally replicated public bucket; only the tiny pointer commit crosses to the primary PostgreSQL region (~50-100 ms off the critical user-blocking path).

    Summary of core trade-offs:

    • Direct pre-signed PUT vs. API proxy: keeps slow 10 MB uploads off backend servers, in exchange for a 3-step client handshake (create -> PUT -> complete) plus an object-created fallback trigger.
    • Immutable per-upload image_id URLs vs. fixed /playlists/{id}/cover.jpg: unlocks 1-year browser + CDN caching with zero image purges on replacement, in exchange for a 60-second metadata lookup and a 24-hour retirement grace period.
    • Live permission checks against Playlist Service vs. replicated ACLs: eliminates ownership drift, in exchange for failing closed on new writes when Playlist Service is down.
    • Transactional cover_events + WORM + crypto-shredding: delivers tamper-evident 7-year compliance audits while still honoring user privacy erasure requests.

Intuition & how it works

Think of managing public playlist cover images like running a poster printing shop for millions of storefronts whose window displays are also embedded on partner websites worldwide. Instead of running around trying to scrape off and repaint existing posters while crowds are looking at them, you print every new upload in all required sizes under a brand-new, unguessable serial number (img_9a2c), verify every print is dry on the shelf, and then flip one tiny index card (playlist_84 -> img_9a2c, version 15) inside the same locked ledger transaction that records who swapped img_3d7e for img_9a2c and when. Because no published image file is ever overwritten in place, browsers and global caches can keep every image file for a full year without ever serving a half-written or corrupted picture.

The naive approach—POSTing 10 MB photos through your web servers, resizing them synchronously, and overwriting a fixed path like https://cdn.example.com/playlists/84/cover.jpg—breaks down across ingest, auditing, and failure recovery. First, slow cellular uploads hold application connections open for tens of seconds while overwriting a fixed URL forces an awful choice between hours-old cached images on embeds or constant cache misses at 350,000 views per second. Second, updating only a current_image_url column destroys the history an auditor needs to investigate an offensive cover that a collaborator uploaded and deleted ten minutes later, while decoding untrusted files inside your API process exposes servers to crashes and memory-exhaustion bombs.

Trace one concrete replacement end to end when user usr_23 updates playlist pl_84 (currently showing img_3d7e at version = 14):

  1. Authorize & bypass API servers for bytes: cover-service asks playlist-service whether usr_23 may edit pl_84, records upload up_4Km2 (state = CREATED, base_version = 14), and returns a pre-signed URL (a temporary signed storage link) so the app PUTs the 2 MB photo straight into private staging storage.
  2. Process in a sandbox under a fresh ID: a sandboxed worker verifies binary file headers, strips camera GPS tags, and writes 8 resized files (64, 300, 640, 1200 px in WebP and JPEG) under /c/img_9a2c/... (state = READY) while embeds everywhere continue displaying /c/img_3d7e/... uninterrupted.
  3. Flip pointer + log audit + enqueue event atomically: after re-checking usr_23's permission, one PostgreSQL transaction verifies version == 14, updates playlist_cover to (img_9a2c, version = 15), inserts (actor = usr_23, before = img_3d7e, after = img_9a2c) into cover_events, and writes a playlist-cover-changed event into a transactional outbox (a DB table relayed to Kafka so state and events never drift).
  4. Serve globally & archive safely: playlist and embed metadata caches refresh within 60 seconds to emit /c/img_9a2c/... (cached for 1 year at the CDN, edge servers near viewers), while img_3d7e stays readable for a 24-hour grace period before moving solely to a restricted 1-year audit archive.

Key trade-offs

  • Pre-signed direct-to-storage uploads vs. proxying bytes through backend servers. Streaming raw image bytes directly from clients to object storage keeps 80-second cellular uploads off application RAM and threads, letting storage scale independently. The trade-off is a three-step client flow (create -> PUT -> complete), URL expiration handling (/renew-url), and listening to bucket ObjectCreated notifications as a backup when mobile apps close right after uploading.
  • Immutable per-upload URLs (/c/{image_id}/...) vs. a single mutable URL per playlist. Minting a fresh random image_id on every upload lets us serve images with Cache-Control: public, max-age=31536000, immutable, eliminating image-level CDN purges and browser-cache staleness on replacements. In exchange, surfaces must resolve the current URL through playlist metadata (cached for 60 s) and retired public files stay live for a 24-hour grace window (skipped on policy takedowns).
  • Separate pixel writing from an atomic pointer transaction. Workers write all 8 derivatives before a single database transaction updates playlist_cover, cover_events, and outbox together. This guarantees zero half-processed covers and 100% consistent audit logs and Kafka events, at the cost of maintaining an explicit upload state machine and a daily orphan-cleanup job for failed uploads.
  • Live permission queries to playlist-service vs. caching playlist ACLs locally. Asking playlist-service at session creation and again at commit ensures there is only one source of truth for ownership and collaborator revocation takes effect immediately. The price is write-path availability coupling, mitigated by failing closed on new sessions and retrying in-flight commits with a bounded fallback.
  • Post-publication ML moderation (with pre-publication hash matching) vs. full pre-publication review. Blocking on fast known-bad hash checks before LIVE and running heavier ML classifiers asynchronously seconds later keeps legitimate uploads under the 10-second target, trading a brief seconds-long exposure window for newly created policy-violating images against slower publish latency and human-review queues.
  • Tiered audit retention + crypto-shredding vs. keeping raw files forever. Retaining raw 2 MB uploads forever would add 2M x 2 MB x 365 = ~1.46 PB/year; keeping raw originals 30 days, a 1200 px review JPEG 1 year (~241 TB/year) in governance-locked storage, and hash-chained event logs 7 years in WORM (Write Once, Read Many) compliance storage (where files cannot be altered or deleted before expiry) balances cost, auditability, and privacy—using crypto-shredding (deleting a user's per-user encryption key) to anonymize erased accounts without breaking hash chains.

Common mistakes

  • Streaming multi-megabyte uploads through API servers and decoding images inside the web process, where slow mobile connections exhaust worker pools and malformed files or decompression bombs (tiny compressed files expanding to gigabytes of pixels) crash the service.
  • Overwriting /playlists/{id}/cover.jpg in place, which traps embeds behind stale browser caches (which CDN purges cannot reach) or destroys CDN hit rates at 350k views/s.
  • Switching the playlist pointer before all 8 sizes exist (or letting an older slow upload overwrite a newer upload or DELETE), leaving certain screens or embeds broken or showing deleted art.
  • Storing only current state (playlist_cover) without an append-only cover_events table, making it impossible for an auditor to see who uploaded a removed image or what preceded it.
  • Updating the database and publishing to Kafka outside a single transaction (dual writes), so a crash in between leaves embeds and search indexes permanently out of sync with the database.
  • Trusting the client's Content-Type header, allowing SVG uploads, or leaving EXIF metadata intact, which risks stored XSS via SVG scripts and leaks users' home GPS coordinates in public photos.
  • Letting auditors query production tables or user-facing APIs directly, creating accidental write paths and leaving zero immutable audit trail of what the auditor inspected or exported.
  • Deleting the old cover's public files the millisecond a replacement commits, causing HTTP 404 broken images on third-party pages rendered seconds earlier.

Follow-up questions

  • Suppose a creator updates their playlist cover, yet an embedded player on an external blog still renders the previous artwork 60 minutes later. Which failure modes could explain this staleness, and how does your architecture prevent them? Because every upload gets a brand-new image_id URL, an hour-stale embed is never an image-cache collision—it means something still holds the old pointer or the upload never reached LIVE. Common culprits are embed HTML or playlist metadata cached with a multi-hour TTL, a stalled or dropped Kafka consumer in playlist-service or embed-service, a race where a slower earlier upload overwrote the newer one, or a third-party chat/social platform that scraped the OpenGraph preview image once and cached it on their own servers. Our design prevents every server-side cause by capping metadata TTL at 60 s with active CDN cache purges on playlist-cover-changed, publishing via a transactional outbox with monotonic version checks plus dead-letter alerts and daily version reconciliation, checking base_version at commit, and surfacing explicit upload states in the UI.
  • How would you adapt the pipeline if every uploaded cover had to clear automated and human content moderation prior to becoming publicly accessible? Insert a PENDING_REVIEW state between READY and LIVE, and write resized derivatives into a private quarantine bucket rather than the public CDN bucket so zero bytes are publicly reachable before approval. An automated vision classifier clears or rejects ~99% of uploads in seconds, routing ambiguous cases to human moderators; only upon approval does a worker copy the 8 files to c/{image_id}/ and run the atomic pointer commit (while the previous cover remains live to the public and the uploader sees a signed preview labeled "Under review"). Size human ops explicitly: if even 1% of 2M daily uploads (20,000/day) needs a 30-second human check, that requires 20,000 x 30 s = ~167 reviewer-hours/day—roughly 21 full-time shifts per day before breaks, weekends, and appeals.
  • If a future client redesign introduces a new thumbnail resolution that does not exist for hundreds of millions of already-published covers, how would you roll it out? Generate it from the private <= 2048 px normalized masters (~120 TB) kept specifically for live covers, combining an origin on-demand resizer (triggered on CDN misses only for an explicit allowlist of dimensions so attackers cannot request arbitrary sizes) with an offline popularity-ordered backfill. At ~0.1 core-seconds per cover to decode the master and write WebP + JPEG, backfilling 200M live covers takes 20M core-seconds = ~5,556 core-hours, finishing in ~11 hours across 500 spot workers. Running the backfill before enabling the new client flag ensures the CDN warms smoothly instead of hammering the on-demand resizer at 350,000 views/s.
  • How should your artwork service behave if the upstream playlist service goes down while users are initiating or finishing uploads? Public image viewing and embeds are 100% unaffected because they read from the CDN and cached metadata without calling cover-service. New POST /cover-uploads calls fail closed with 503 Service Unavailable and a Retry-After header because we never allow unauthorized writes. Uploads already in UPLOADED or PROCESSING finish resizing normally and wait in READY, retrying the commit-time permission re-check with exponential backoff and a circuit breaker; optionally, if playlist-service stays down, commits within 15 minutes of session creation may proceed using the initial authorization decision tagged authz_mode = cached in cover_events so any edge-case collaborator revocation during that 15-minute window remains fully auditable and reversible.

Follow-up questions

Similar questions

More Spotify interview questions

All 12 Spotify questions →