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:
- 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.
- 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.
- 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
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 pxand8,000 x 8,000 px(<= 40megapixels 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), and1200 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
LIVEstate, 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.
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 burstsThree design lessons jump right out of these numbers:
- Reads outnumber writes 5,000 to 1 (
116k/svs.23/s): the public read path must go straight from viewer browsers to a CDN backed by object storage, never touchingcover-serviceor its database. That requires immutable image URLs safe to cache for a full year. - Writes are low-QPS but byte-heavy (
2 MBaverage,10 MBmax): 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.
- Reads outnumber writes 5,000 to 1 (
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
PUTone exact object key with a fixedContent-TypeandContent-Lengthwithin 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-Keyheader so retrying a timed-outPOSTreturns 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": "..."}- Pre-signed URL: a temporary, cryptographically signed object-storage URL generated by our backend that lets the client
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_coverand 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 lockWhy three subtle schema choices prevent classic bugs:
playlist_coverrows are nulled (image_id = NULL), never deleted: ifDELETE /coverdeleted the row, a later upload would resetversionback to1, causing downstream caches holdingversion = 15to reject the new cover as stale.base_versiononcover_uploadscatches overtaken uploads: when an upload session starts, it records the playlist's currentversion(0 if none). If another upload, a userDELETE, or a moderatorTAKEDOWNincrementsplaylist_cover.versionwhile this upload is still resizing, the commit check seesversion != base_versionand marks the late uploadSUPERSEDEDinstead 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.
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 toPlaylist 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 Servicemetadata and fetch pixels fromCDN Edge->Origin Shield->Public Bucketwith zero dependency oncover-service.
- Control plane (
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 playlistpl_84(currently showingimg_3d7eatversion = 14) untilimg_9a2cis 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- Session creation:
cover-servicecallsPlaylistService.CheckPermission(user_id, pl_84, EDIT_DETAILS)(100 ms timeout), validates size (<= 10 MB) and MIME type, reservesupload_idandimage_id = img_9a2c, recordsbase_version = 14, and returns the 15-minute pre-signedPUTURL. - 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. - Trigger processing: the client calls
/complete(with an object-storageObjectCreatedevent acting as an automatic fallback if the user closes the app right as thePUTfinishes). Either path moves state toUPLOADEDand enqueues a worker job via the outbox. - Write-once image generation: a worker validates and decodes the image, checks hashes against known illegal content, writes
master/img_9a2c.jpgplus all 8 files (64..1200inwebpandjpg) toc/img_9a2c/, verifies all 8 exist with non-zero byte length, and marksimages.status = READY. Throughout all of this,playlist_coverstill points toimg_3d7e. - 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_coverforpl_84. Ifplaylist_cover.version != upload.base_version(meaning a newer upload,DELETE, orTAKEDOWNalready committed), mark this uploadSUPERSEDEDand stop. - Update
playlist_covertoimage_id = img_9a2c,version = 15, and updatelast_event_hash. - Insert the
cover_eventsaudit record (before = img_3d7e,after = img_9a2c,version = 15). - Insert the
outboxevent (playlist-cover-changed,version = 15). - Mark
upload = LIVE,img_9a2c = LIVE, andimg_3d7e = REPLACEDwithretire_at = now + 24 hours.
- Lock
- 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 ifevent.version > stored_version, making retries and out-of-order messages harmless.
- Session creation:
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>:- The browser loads the embed HTML from our embed service, which reads playlist metadata (cached at the CDN for
60 sand actively purged whenplaylist-cover-changedarrives). - The HTML renders a
<picture>tag pointing athttps://img.<cdn-domain>/c/img_9a2c/300.webp(with300.jpgfallback). - 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
publicbucket.
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(orimage/jpeg) plusX-Content-Type-Options: nosniffstops browser MIME sniffing, and putting.webp/.jpgin the URL path avoids fragmenting CDN cache keys onVary: Accept.
- The browser loads the embed HTML from our embed service, which reads playlist metadata (cached at the CDN for
Deep dive 3: Audit trail, tamper resistance, and privacy erasure (Stage 2)
playlist_coveronly 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_eventsis written inside the exact same PostgreSQL transaction asplaylist_cover, it is impossible for a cover to change—via user upload, collaborator edit, user delete, or moderator takedown—without recordingoccurred_at,playlist_id,version,action,actor_type,actor_ref,before_image_id,after_image_id, andauthz_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 pxJPEG review copy lives in the privatearchivebucket. When an auditor inspectsbefore_image_id, the Audit Service mints a 5-minute signed URL toarchive/review/{image_id}.jpg.
Tamper resistance + GDPR/privacy erasure without breaking hash chains:
- WORM (Write Once, Read Many) storage and hash chains:
cover_eventsstream 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 storesevent_hash = SHA256(prev_event_hash || event_fields)usingplaylist_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
archivecopies (stored under Governance-mode lock, which permits only a dedicated, audited erasure service to delete early)—are purged. Because compliance-lockedcover_eventsfiles cannot be edited,actor_refis stored encrypted with a per-user KMS/key-store key (Enc(user_key, user_id)). Deletinguser_key(crypto-shredding) permanently anonymizes the actor while keeping every event row and hash chain 100% intact.
- Every mutation captured transactionally: because
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 -------------> CANCELLEDWhat fails What the user sees Recovery & why playlist stays safe Mobile connection drops mid- PUTUpload progress pauses with "Retry"; old cover stays live Client resumes multipart PUT(calls/renew-urlif >15 min); abandoned sessions turnEXPIREDafter 24 h and staging lifecycle deletes partial bytesCorrupt file or fake .jpgextensionImmediate clear message: "Unsupported or damaged image"Worker inspects file magic bytes (binary header signature), not Content-Type; marksFAILED_INVALIDwith zero retriesDecompression bomb (tiny PNG claiming 50,000 x 50,000 px=10 GBRGBA RAM)"Image dimensions exceed 8,000 x 8,000 limit"Worker reads width/height from file header before allocating pixel buffers and rejects > 40megapixels 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 GBRAM cap,20 sCPU limit—defending against parser CVEs like ImageTragick). After 3 crashes on oneupload_id, markFAILED_INVALIDand copy raw file to engineering quarantineObject store or DB blip during resize "Processing..."for a few extra secondsRetry up to 5 times with exponential backoff + jitter; deterministic keys ( c/{image_id}/...) make overwriting idempotent; after 5 tries ->FAILED_INTERNALDB commit fails after all 8 files are READY"Processing..."brieflyWorker retries the idempotent commit transaction; if still uncommitted after 1 h -> FAILED_INTERNALand orphan sweeper cleans upc/{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_coveris untouchedGarbage collection and split alerting:
- Orphaned object sweeper: listing 1.6 billion public objects (
200M x 8) via liveLISTcalls is expensive, so a daily batch job joins the cloud provider's daily bucket inventory manifest against PostgreSQLimagesand deletes anyc/{image_id}/prefix that is missing, failed, cancelled, superseded, or pastretire_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. TrackFAILED_INVALIDon a separate metric (normally user error, though a sudden 3x jump alerts client teams to a broken app encoder).
- Orphaned object sweeper: listing 1.6 billion public objects (
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 exact64/300/640derivative 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_coverand activecover_uploadslean in NVMe-backed PostgreSQL by archivingcover_eventspartitions older than 90 days to the analytical/WORM audit store. - Multi-region uploads: clients
PUTinto the nearest regional staging bucket and local workers write to a globally replicatedpublicbucket; 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
PUTvs. 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_idURLs 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 Servicevs. replicated ACLs: eliminates ownership drift, in exchange for failing closed on new writes whenPlaylist Serviceis down. - Transactional
cover_events+ WORM + crypto-shredding: delivers tamper-evident 7-year compliance audits while still honoring user privacy erasure requests.
- CDN egress (
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):
- Authorize & bypass API servers for bytes:
cover-serviceasksplaylist-servicewhetherusr_23may editpl_84, records uploadup_4Km2(state = CREATED,base_version = 14), and returns a pre-signed URL (a temporary signed storage link) so the appPUTs the 2 MB photo straight into private staging storage. - 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 pxin WebP and JPEG) under/c/img_9a2c/...(state = READY) while embeds everywhere continue displaying/c/img_3d7e/...uninterrupted. - Flip pointer + log audit + enqueue event atomically: after re-checking
usr_23's permission, one PostgreSQL transaction verifiesversion == 14, updatesplaylist_coverto(img_9a2c, version = 15), inserts(actor = usr_23, before = img_3d7e, after = img_9a2c)intocover_events, and writes aplaylist-cover-changedevent into a transactional outbox (a DB table relayed to Kafka so state and events never drift). - 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), whileimg_3d7estays 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 bucketObjectCreatednotifications 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 randomimage_idon every upload lets us serve images withCache-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, andoutboxtogether. 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-servicevs. caching playlist ACLs locally. Askingplaylist-serviceat 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
LIVEand 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, a1200 pxreview 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.jpgin 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-onlycover_eventstable, 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-Typeheader, 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
404broken 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_idURL, an hour-stale embed is never an image-cache collision—it means something still holds the old pointer or the upload never reachedLIVE. Common culprits are embed HTML or playlist metadata cached with a multi-hour TTL, a stalled or dropped Kafka consumer inplaylist-serviceorembed-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 onplaylist-cover-changed, publishing via a transactional outbox with monotonicversionchecks plus dead-letter alerts and daily version reconciliation, checkingbase_versionat 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_REVIEWstate betweenREADYandLIVE, and write resized derivatives into a private quarantine bucket rather than thepublicCDN 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 toc/{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 requires20,000 x 30 s = ~167reviewer-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 pxnormalized 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.1core-seconds per cover to decode the master and write WebP + JPEG, backfilling 200M live covers takes20M 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. NewPOST /cover-uploadscalls fail closed with503 Service Unavailableand aRetry-Afterheader because we never allow unauthorized writes. Uploads already inUPLOADEDorPROCESSINGfinish resizing normally and wait inREADY, retrying the commit-time permission re-check with exponential backoff and a circuit breaker; optionally, ifplaylist-servicestays down, commits within 15 minutes of session creation may proceed using the initial authorization decision taggedauthz_mode = cachedincover_eventsso any edge-case collaborator revocation during that 15-minute window remains fully auditable and reversible.
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?
- How would you adapt the pipeline if every uploaded cover had to clear automated and human content moderation prior to becoming publicly accessible?
- 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?
- How should your artwork service behave if the upstream playlist service goes down while users are initiating or finishing uploads?
Similar questions
- Rebuilding Team Momentum During a Difficult Engineering Stretch
- Session-Aware Music Playlist Recommendation Service
- Automated Podcast Episode Recap Pipeline
- Applying AI Developer Tools Responsibly and Leading Team Rollouts
- Per-Country Active Listener Rankings
- Longest Repeat-Free Substring Length
More Spotify interview questions
- Rebuilding Team Momentum During a Difficult Engineering Stretch Medium
- Applying AI Developer Tools Responsibly and Leading Team Rollouts Medium
- Longest Repeat-Free Substring Length Medium Pro
- Production Incident Triage for a Degraded Backend Host Medium Pro
- Delivering Engineering Progress Amid Ambiguous or Shifting Specs Medium Pro
- Top Three-Page Journey and Multi-Parameter Scaling Medium Pro
- Automated Podcast Episode Recap Pipeline Medium Pro
- Session-Aware Music Playlist Recommendation Service Medium Pro
- Per-Country Active Listener Rankings Medium Pro
- Weekly Listener Retention Prediction at 500M Scale Hard Pro