Sortable Comments and Async Image Service
Medium · System Design · Software Engineer · Technical Screen
Prompt
This architecture exercise covers two distinct full-stack subsystems within one session:
- Sortable Comment Threading: Architect an end-to-end comment feature spanning browser UI, HTTP APIs, and persistent storage with full create, read, edit, and delete capabilities. Viewers must be able to order comments by
timestamporuserId(either ascending or descending), and each user's chosen ordering must survive full page reloads. - Asynchronous Image Synthesis: Architect an image-generation backend where producing an output takes significantly longer than standard HTTP gateway or browser request timeouts. Detail how requests are ingested, scheduled and executed asynchronously in the background, tracked for live progress and final assets, and rendered in a stable, predictable sequence inside the client gallery.
Scope & Expectations
- CRUD APIs & indexed pagination: Define REST contracts, authorization/concurrency safeguards on edits and deletes, and database index designs that paginate cleanly under all four
timestamp/userIdsort directions. - Reload-safe sort state: Show how frontend state, URL parameters, and backend storage coordinate so a user's preferred sort order loads cleanly after a browser refresh without UI flicker.
- Fault-tolerant async job lifecycle: Cover fast non-blocking job intake, durable queuing, worker leases/retries, and status/asset delivery (polling or server push) without holding HTTP requests open.
- Deterministic UI ordering: Guarantee that generated items stay in a consistent, jump-free visual order even when later fast jobs finish ahead of earlier slow ones.
Step-by-step walkthrough
Clarify requirements for both parts
Because this interview combines two distinct system designs in a single session, spend ~3 minutes upfront confirming assumptions for both parts, then divide your remaining time evenly (~20 minutes per part).
Part 1: Full-stack sortable comment system
- Functional scope: Authenticated users can create, read, update, and delete plain-text comments (up to
5,000characters) on a parent resource (thread_id, such as a project, document, or post). Comments are flat (nested replies are a classic follow-up). Only the comment's author may edit it; the author or a moderator may delete it. - Sorting & pagination: Viewers can sort a thread's comments by
timestamp(created_at) oruserId(author_id) inascordescorder, fetched one page at a time (50comments per page). - Persisted sort preference: If a user picks
userId ascand refreshes the browser — or logs in on another laptop — the comment list opens directly inuserId ascorder. Logged-out guests fall back to browserlocalStorage. - Non-functional goals: Comment list reads
< 200 msp99; read-your-own-writes consistency (an author immediately sees their own post, edit, or delete); idempotent creation (retrying after a shaky mobile timeout never creates duplicate comments).
Part 2: Asynchronous long-running image generation
- Why synchronous HTTP fails here: Generating a batch of 4 diffusion images takes
15to120seconds (plus queue wait during traffic spikes). Standard reverse proxies and cloud load balancers drop idle HTTP connections after30–60seconds, mobile Wi-Fi handoffs break open sockets, and refreshing the browser tab would orphan an open HTTP call and lose the finished images. - Functional scope: Accept a prompt and parameters immediately (
< 300 ms), enqueue durable background GPU work, expose live status (queued,runningwith progress,succeeded,failed,canceled) and finished image URLs across page refreshes, allow cancellation, and keep the user's gallery in a strict, jump-free submission order (newest submission first, even when a fast prompt finishes ahead of an earlier slow prompt). - Non-functional goals: Zero lost jobs after
202 Accepted; each job produces at most one committed image set even if worker crashes trigger retries; bounded GPU queue wait (< 30 sp95 under normal load).
- Functional scope: Authenticated users can create, read, update, and delete plain-text comments (up to
Back-of-the-envelope capacity estimates
Assume a collaborative platform with
5,000,000daily active users (DAU). Let's calculate read QPS, write TPS, GPU fleet size, and daily storage:- Comments traffic:
5M DAU * 20 thread views/day = 100M list reads/day(100,000,000 / 86,400 ≈ 1,160 QPSaverage,~3,500 QPSpeak). New comments:5M * 0.5 = 2.5M writes/day(~29 TPSaverage,~90 TPSpeak), plus ~10% edits and deletes. - Comments storage:
2.5M comments/day * ~1 KB(text + metadata + two B-tree indexes) =~2.5 GB/day(~0.9 TB/year). - Image generation rate & GPU sizing:
200,000 jobs/day(~2.3 jobs/saverage,~7 jobs/speak). Suppose each job generates 4 images in one GPU pass taking15 sof GPU compute. By Little's Law (the rule that the average number of busy workers equals the arrival rate multiplied by the average processing time per job):- Average busy GPUs =
2.3 jobs/s * 15 s ≈ 35 GPUs. - Peak busy GPUs =
7 jobs/s * 15 s = 105 GPUs-> provision ~130 GPUs at peak (~80% utilization) so queueing delays stay low.
- Average busy GPUs =
- Image blob storage & status polling:
4 PNGs * 1.5 MB + 4 WebP thumbnails * 50 KB ≈ 6.2 MB/job->200,000 * 6.2 MB ≈ 1.24 TB/day. Polling every2 sacross a ~25 s active lifetime gives ~13 polls/job ->2.6M polls/day(~30 QPSaverage,~90 QPSpeak).
Subsystem Read / Poll QPS Write / Job TPS Storage & Compute Highlight ------------------ ----------------------- --------------------- ----------------------------------------- Comments 1,160 avg / 3,500 peak 29 avg / 90 peak ~2.5 GB/day -> 1 PostgreSQL primary + replicas Image Generation 30 avg / 90 peak (poll) 2.3 avg / 7 peak ~130 peak GPUs; ~1.24 TB/day in S3 + CDNKey takeaways: Both metadata workloads fit comfortably inside a single PostgreSQL primary with read replicas! Images (
1.24 TB/day) belong in object storage (like Amazon S3) fronted by a CDN (Content Delivery Network — global edge caches serving static images near users), while GPU scheduling, crash recovery, sorted pagination, and UI ordering are the core engineering challenges.- Comments traffic:
API design for comments, preferences, and async image jobs
Two building blocks keep these APIs clean and reliable: - Opaque cursor: a Base64-encoded server token recording the exact sort coordinates of the last item on a page so the next page resumes cleanly without shifting. - HTTP
202 Accepted: the standard HTTP status code meaning "your request was durably recorded for background execution; poll the resource URL inLocationfor status."Part 1: Comments & Persisted Sort Preference -------------------------------------------- POST /v1/threads/{thread_id}/comments Headers: Idempotency-Key: <client-generated UUID> Body: {"body": "Great layout on floor 2!"} -> 201 Created {"comment_id": 90412, "author_id": 77, "body": "...", "created_at": "...", "version": 1} GET /v1/threads/{thread_id}/comments?sort=timestamp|userId&order=asc|desc&limit=50&cursor=<token> (When sort/order are omitted on initial load, server applies the user's saved preference!) -> 200 OK {"items": [...], "next_cursor": "<token>", "applied_sort": {"sort": "userId", "order": "asc"}} PATCH /v1/comments/{comment_id} Body: {"body": "Updated measurement", "version": 1} -> 200 OK (version -> 2) | 409 Conflict (stale version) | 403 Forbidden (not author) DELETE /v1/comments/{comment_id} -> 204 No Content (idempotent soft delete) PUT /v1/me/preferences/comment-sort Body: {"sort": "userId", "order": "asc"} -> 204 No Content Part 2: Async Image Generation ------------------------------ POST /v1/generations Headers: Idempotency-Key: <client-generated UUID> Body: {"prompt": "isometric timber cabin at sunset", "count": 4, "size": "1024x1024"} -> 202 Accepted Location: /v1/generations/gen_88a1 {"generation_id": "gen_88a1", "user_seq": 102, "status": "queued", "created_at": "..."} GET /v1/generations/{generation_id} -> 200 OK {"generation_id": "gen_88a1", "user_seq": 102, "status": "running", "progress": 0.65, "images": [], "error_code": null} (When status == "succeeded", images contains [{index, url, thumb_url, width, height}]) GET /v1/generations?limit=20&cursor=<seq_cursor> -> 200 OK (User's gallery strictly ordered by user_seq DESC) POST /v1/generations/{generation_id}/cancel -> 202 Accepted GET /v1/generations/events -> Optional Server-Sent Events (SSE) live push streamNotice
author_idis always extracted from the verified authentication token on the backend — never trusted from the JSON request body!Database schema and composite B-tree indexes
We store comments, user preferences, and image job metadata in PostgreSQL, while binary PNG/WebP files live in object storage:
comments comment_id BIGINT PRIMARY KEY -- unique ID thread_id BIGINT NOT NULL author_id BIGINT NOT NULL body TEXT NOT NULL -- max 5,000 chars created_at TIMESTAMPTZ NOT NULL updated_at TIMESTAMPTZ NOT NULL deleted_at TIMESTAMPTZ NULL -- NULL = active; timestamp = soft-deleted version INT NOT NULL DEFAULT 1 -- increments on every PATCH edit idem_key UUID NOT NULL -- UNIQUE (author_id, idem_key) -- Partial composite B-tree indexes (exclude soft-deleted comments automatically): INDEX idx_comments_time (thread_id, created_at ASC, comment_id ASC) WHERE deleted_at IS NULL INDEX idx_comments_user (thread_id, author_id ASC, created_at ASC, comment_id ASC) WHERE deleted_at IS NULL user_preferences user_id BIGINT PRIMARY KEY comment_sort TEXT NOT NULL DEFAULT 'timestamp' -- 'timestamp' | 'userId' comment_order TEXT NOT NULL DEFAULT 'desc' -- 'asc' | 'desc' updated_at TIMESTAMPTZ NOT NULL users (existing accounts table, with one monotonic sequence column per user) user_id BIGINT PRIMARY KEY next_gen_seq BIGINT NOT NULL DEFAULT 0 generations generation_id UUID PRIMARY KEY user_id BIGINT NOT NULL user_seq BIGINT NOT NULL -- UNIQUE (user_id, user_seq) -> gallery display order! idem_key UUID NOT NULL -- UNIQUE (user_id, idem_key) prompt TEXT NOT NULL params JSONB NOT NULL -- count, size, deterministic random seed status TEXT NOT NULL -- queued | running | succeeded | failed | canceled priority SMALLINT NOT NULL DEFAULT 5 cancel_requested BOOLEAN NOT NULL DEFAULT false attempts INT NOT NULL DEFAULT 0 -- acts as monotonic fencing token! lease_owner TEXT NULL lease_expires_at TIMESTAMPTZ NULL error_code TEXT NULL created_at TIMESTAMPTZ NOT NULL finished_at TIMESTAMPTZ NULL INDEX idx_gen_queue (priority ASC, created_at ASC) WHERE status = 'queued' INDEX idx_gen_gallery (user_id, user_seq DESC) generation_images generation_id UUID NOT NULL REFERENCES generations(generation_id) image_index SMALLINT NOT NULL -- 0, 1, 2, 3 object_key TEXT NOT NULL -- e.g. "gen/gen_88a1/attempt-2/0.png" thumb_key TEXT NOT NULL width INT NOT NULL, height INT NOT NULL PRIMARY KEY (generation_id, image_index)Why do two indexes on
commentsserve all four sort combinations (timestamp asc/descanduserId asc/desc)? 1. Every query filters onWHERE thread_id = :thread_idfirst. Inside onethread_idslice of a B-tree (a balanced sorted tree index whose leaf pages form a doubly linked list), PostgreSQL scans forward for(created_at ASC, comment_id ASC)and scans backward at the exact same speed for(created_at DESC, comment_id DESC). 2. Appendingcomment_idas the final column provides a unique tie-breaker: when one user posts 20 comments (author_idties) or two users post in the same millisecond (created_atties), every row still has a deterministic, unique position in the index.High-level full-stack architecture
+-----------------------------------------------------------------------------------+ | Browser Single-Page App (React / TypeScript) | | - CommentList: URL ?sort override -> Server applied_sort -> localStorage guest | | - ImageGallery: renders cards sorted by user_seq DESC; polls or listens to SSE | +-------------------+-----------------------------------------------+---------------+ | HTTPS (REST + optional SSE) | GET signed image URLs v v +---------------------+ +-------------------+ | API Gateway / Auth | | CDN Edge Cache | +----------+----------+ +---------+---------+ | | +----------v----------+ | | Stateless API Pods |--------------------+ | +--+---------------+--+ | | | | v | | | +--------------------+ | | | | Redis | | | | | - Hot page-1 cache | | v v | - Job progress % | | +--------------------+ +-------------+ | - Cancel flags | | | PostgreSQL Primary |->| Read | | - SSE Pub/Sub | | | - comments, prefs | | Replicas | +---------^----------+ | | - generations | | (list GETs) | | progress/done | +---------+----------+ +-------------+ | | ^ | v | claim (SKIP LOCKED), heartbeat, commit | +-------------------+ +----------------------------------------+------+ Object Storage | | Autoscaled GPU Worker Pool | gen/{id}/attempt-n| +-----------------------------------------------+-------------------+ ^ | reclaim expired leases every 30s +--------+---------+ | Lease Reaper Job | +------------------+Deep dive 1: Keyset pagination, persisted sort preference, and CRUD sync
1. Why Keyset (Cursor) Pagination beats
OFFSETIf a user scrolls deep into a 50,000-comment thread usingOFFSET 5000 LIMIT 50, PostgreSQL still has to read and discard 5,000 index entries on every page. Worse, if someone posts a new comment at the top while you read Page 1, every row shifts down by 1 position, so Page 2 (OFFSET 50) repeats the 50th comment from Page 1!With keyset pagination, the client passes back the exact coordinates of the last comment it saw. Trace a 4-row mini-thread sorted by
userId ASC(limit = 2):Index order in idx_comments_user for thread_id = 10: Row 1: (author_id = 3, created_at = 09:00, comment_id = 501) \ Page 1 returns Rows 1 & 2; Row 2: (author_id = 3, created_at = 09:05, comment_id = 504) / next_cursor encodes (3, 09:05, 504, userId, asc) ------------------------------------------------------------ Row 3: (author_id = 3, created_at = 09:12, comment_id = 509) \ Page 2 seeks > (3, 09:05, 504) directly in B-tree Row 4: (author_id = 8, created_at = 08:50, comment_id = 499) / -> returns Rows 3 & 4 in O(log N) time!Here are the exact Page 1 and Page 2+ SQL queries for
userId:-- Page 1 (no cursor yet), sort = userId, order = asc: SELECT comment_id, author_id, body, created_at, updated_at, version FROM comments WHERE thread_id = :thread_id AND deleted_at IS NULL ORDER BY author_id ASC, created_at ASC, comment_id ASC LIMIT 50; -- Page 2+ (resuming from cursor), sort = userId, order = asc: SELECT comment_id, author_id, body, created_at, updated_at, version FROM comments WHERE thread_id = :thread_id AND deleted_at IS NULL AND (author_id, created_at, comment_id) > (:last_author_id, :last_created_at, :last_comment_id) ORDER BY author_id ASC, created_at ASC, comment_id ASC LIMIT 50; -- For order = desc: flip '>' to '<' and change all three ORDER BY columns to DESC!2. Persisting the user's sort preference across page refreshes (without UI flicker) Where should the sort preference live? We combine three layers with a strict precedence rule:
Explicit URL query (?sort=userId&order=asc) > Server user_preferences row > Browser localStorage (guests) > Default (timestamp desc).- On page refresh (logged-in user): If the URL has no
?sort=query parameters, the frontend immediately callsGET /v1/threads/{id}/comments(with nosortparam). On the backend, the handler joins/looks upuser_preferencesfor the authenticated user (1primary-key lookup), runs the comment query in that saved order, and returns{items, applied_sort: {sort: "userId", order: "asc"}}. Because everything happens in one HTTP round trip, the page renders directly in the user's saved order on the very first paint — zero flash of unsorted comments! - When the user changes the dropdown: The React state updates immediately, fetches Page 1 with the new
sortandorder, updates the URL viahistory.replaceState, caches the choice inlocalStorage(for offline/logged-out fallback), and firesPUT /v1/me/preferences/comment-sortasynchronously in the background.
3. Frontend-backend CRUD synchronization - Create: Generate
Idempotency-Keyon button click and render an optimistic"Posting..."comment (at the top if viewingtimestamp desc, or with a"Jump to your comment"toast if sorted byuserIdwhere your position is off-screen). Retries reuse the sameIdempotency-KeysoUNIQUE (author_id, idem_key)prevents duplicates. - Edit (PATCH): Send theversioninteger loaded with the comment. Backend runsUPDATE comments SET body = :body, version = version + 1, updated_at = now() WHERE comment_id = :cid AND author_id = :uid AND version = :ver AND deleted_at IS NULL. If another browser tab already edited the comment,0rows match -> return409 Conflictwith the latest server version so the user doesn't silently overwrite their other tab. - Read-your-own-writes: Because read replicas can lag by50–200 ms, when a user writes a comment the backend sets a3-second session cookie/header (recent_write_until) that routes that user'sGETrequests to the PostgreSQL primary until replicas catch up.- On page refresh (logged-in user): If the URL has no
Deep dive 2: Accepting and running long image jobs safely
1. Fast, atomic job acceptance (
202 Accepted) WhenPOST /v1/generationsarrives, the API runs a quick prompt-safety check, then executes a millisecond transaction locking that single user's row inusers:BEGIN; -- 1. Serialize submissions for this single user so quota checks and user_seq are race-free. SELECT next_gen_seq FROM users WHERE user_id = :user_id FOR UPDATE; -- 2. Idempotency check: if client retried after a mobile network drop, return existing job! SELECT generation_id, user_seq, status, created_at FROM generations WHERE user_id = :user_id AND idem_key = :idem_key; -- (If a row is found -> COMMIT and return 202 with that existing row!) -- 3. Enforce per-user fairness quota (e.g., max 20 non-terminal jobs in flight). SELECT COUNT(*) FROM generations WHERE user_id = :user_id AND status IN ('queued', 'running'); -- (If count >= 20 -> ROLLBACK and return 429 Too Many Requests.) -- 4. Allocate monotonic per-user sequence number and enqueue job atomically. UPDATE users SET next_gen_seq = next_gen_seq + 1 WHERE user_id = :user_id RETURNING next_gen_seq; INSERT INTO generations (generation_id, user_id, user_seq, idem_key, prompt, params, status, created_at) VALUES (:gen_id, :user_id, :new_seq, :idem_key, :prompt, :params_with_seed, 'queued', now()); COMMIT;2. Claiming jobs without the dual-write bug (
FOR UPDATE SKIP LOCKED) If we wrote the job to PostgreSQL and then published a message to RabbitMQ or SQS in a second network call, an API crash in between would leave the job stuck inqueuedforever (fixing that requires an extra transactional outbox table and relay worker). At~7 jobs/s, PostgreSQL'sFOR UPDATE SKIP LOCKEDlets 130 GPU workers claim jobs directly fromgenerationsin parallel without blocking one another and with one atomic source of truth:UPDATE generations SET status = 'running', lease_owner = :worker_id, attempts = attempts + 1, lease_expires_at = now() + interval '60 seconds' WHERE generation_id = ( SELECT generation_id FROM generations WHERE status = 'queued' ORDER BY priority ASC, created_at ASC LIMIT 1 FOR UPDATE SKIP LOCKED ) RETURNING generation_id, prompt, params, attempts;3. Worker leases, heartbeats, and fencing tokens against zombie workers GPU VMs crash, get preempted, or freeze during network stalls. Two mechanisms prevent both stuck jobs and double-written results: - Lease + Reaper: While running, the GPU worker renews
lease_expires_atevery15 s(UPDATE generations SET lease_expires_at = now() + interval '60 seconds' WHERE generation_id = :id AND attempts = :token AND status = 'running'). Every30 s, the Lease Reaper scans forstatus = 'running' AND lease_expires_at < now(): ifattempts < 3, it resetsstatus = 'queued'; otherwise it marksstatus = 'failed'(error_code = 'worker_lost') so a poison prompt never crashes GPUs forever. - Fencing token (attempts): What if Worker 1 did not crash, merely froze for75 s, and wakes up after Worker 2 already took over? Every worker uploads images under its own attempt folder (gen/{id}/attempt-{attempts}/{idx}.png) and commits conditionally onattempts:t = 0s Worker 1 claims gen_88a1 -> attempts = 1, lease expires at t = 60s. t = 20s Worker 1 suffers a 60-second network stall (missed heartbeats!). t = 65s Lease Reaper sees lease_expires_at < 65s -> sets status = 'queued'. t = 66s Worker 2 claims gen_88a1 -> attempts = 2! Generates images into attempt-2/ and commits: UPDATE generations SET status = 'succeeded' WHERE generation_id = 'gen_88a1' AND attempts = 2; (1 row!) t = 80s Worker 1 wakes up, uploads to attempt-1/, and tries to commit with its stale token (attempts = 1): UPDATE generations SET status = 'succeeded' WHERE generation_id = 'gen_88a1' AND attempts = 1; -> 0 rows matched! Worker 1 rolls back, leaving Worker 2's clean result untouched.Deep dive 3: Exposing status and preserving stable UI gallery order
1. Status and live progress delivery - Baseline — Adaptive HTTP Polling: While the user has active jobs on screen, the browser polls
GET /v1/generations/{id}every1 sfor the first5 s, then every2 s, backing off to5 s, and stops oncestatusreachessucceeded,failed, orcanceled. At~30 QPSaverage across 5M DAU, stateless polling is rock-solid, survives corporate firewalls, and works automatically after any page refresh (GET /v1/generationsreloads all cards). - Upgrade — Server-Sent Events (SSE) + Redis progress: During diffusion denoising steps, the GPU worker writes lightweight progress (progress = 0.45) to a short-TTL Redis key (avoiding unnecessary PostgreSQL disk writes) and publishes an event to Redis Pub/Sub channeluser:{user_id}. API pods holding an open SSE stream push instant progress updates to the browser. Because Pub/Sub can drop an event during a Wi-Fi reconnect, the browser re-fetchesGET /v1/generations?limit=20whenever an SSE connection reconnects.2. Preserving a well-defined, jump-free gallery order Suppose a user submits Job A at
10:00:00("detailed architectural blueprint", takes40 s) and Job B at10:00:03("minimalist icon", takes12 s). - If the UI ordered items by completion time (finished_at DESC), Job B would appear first at10:00:15, and 25 seconds later Job A would suddenly jump above Job B, shifting the layout right as the user clicks Download! - Why not order bycreated_at DESC? Browser clocks skew across devices, and in PostgreSQLnow()returns the transaction start timestamp rather than commit order, so two concurrent submissions can commit in reverse timestamp order. - Our solution — Per-user monotonicuser_seqassigned at submission: Every accepted job receivesuser_seq(101,102, ...), and the gallery always sorts byuser_seq DESC:Time Event Gallery UI slots (strictly ordered by user_seq DESC) --------- ------------------------------------- -------------------------------------------------------- 10:00:00 Submit Job A -> 202 (user_seq = 101) [ #101: Queued spinner ] 10:00:03 Submit Job B -> 202 (user_seq = 102) [ #102: Queued spinner ] [ #101: Running 20% ] 10:00:15 Job B finishes early (12s GPU run!) [ #102: 4 Finished PNGs ] [ #101: Running 55% ] 10:00:20 User hits browser Refresh (F5) GET /v1/generations -> returns [#102 (done), #101 (running)] 10:00:40 Job A finishes (40s GPU run) [ #102: 4 Finished PNGs ] [ #101: 4 Finished PNGs ]While an optimistic
POST /v1/generationsis still in flight (< 300 ms), the UI renders a temporary card at the very top keyed by the client'sIdempotency-Key, then snaps its permanent key touser_seqas soon as the202response arrives. Every tab and device converges on the exact sameuser_seq DESCorder!Scaling, bottlenecks, and failure handling
Scaling comments & viral threads - Read replicas easily serve
3,500 QPS. For a viral thread where 20,000 users reload Page 1 simultaneously, cache Page 1 of the default sort in Redis (30 sTTL, invalidated on write) with request coalescing (if the cache key expires, only one backend pod queries PostgreSQL while concurrent requests await that same in-flight promise, preventing a cache stampede). - If comment volume ever grows 100x, shardcommentshorizontally bythread_id(every list/create query stays single-shard) anduser_preferencesbyuser_id.Scaling GPU workers & image storage - Cold-start aware autoscaling: Booting a cloud GPU node and loading
10+ GBdiffusion model weights into VRAM takes2–4minutes. Keep a warm baseline pool and autoscale on estimated queue drain time (queued_jobs * 15s / active_gpus) rather than CPU utilization. - Fairness & admission control: In the worker claim query, skip users who already have4jobs inrunningstatus so one heavy user never monopolizes 20 GPUs. If total queue wait exceeds3minutes, return429(or display an upfront queue ETA before submission). - Cancellation & S3 cleanup:POST /cancelsetscancel_requested = truein PostgreSQL and writes a short-livedcancel:{generation_id}key in Redis checked by the GPU worker every few denoising steps so canceled jobs free GPU compute within ~1 second. An S3 lifecycle policy deletes unreferencedattempt-{n}/folders after 24 hours and moves images older than 30 days to infrequent-access storage.Failure handling summary
Failure scenario System behavior Guarantee preserved Mobile timeout on POST /commentsorPOST /generationsClient retries with same Idempotency-Key;UNIQUEindex returns original recordZero duplicate comments or duplicate GPU jobs Author edits same comment in two browser tabs Second PATCHsees staleversion->409 Conflictwith latest bodyZero silent lost edits GPU spot VM preempted mid-generation 60 slease expires; Reaper re-queues job (attempts < 3) with same random seedZero lost jobs; automatic recovery Frozen worker wakes up after lease reassignment Conditional UPDATE ... WHERE attempts = :oldmatches0rows and rolls backExactly one committed image set per job Prompt deterministically crashes GPU kernel Fails permanently after 3attempts (error_code = 'inference_error')Bounded retries; protects GPU fleet Redis cluster restarts Progress percentages pause briefly; GETendpoints still read accurate state from PostgreSQLZero data loss (Redis holds only disposable state) Summary of architectural trade-offs
Design decision Chosen approach Main alternative Why this trade-off fits best Comment pagination Keyset cursor with comment_idtie-breakerSQL OFFSET / LIMITConstant O(log N)seek at any depth; immune to duplicate/skipped rows on new insertsSort preference sync Server user_preferencesapplied insideGET /comments+ URL +localStoragelocalStorageonly, or separateGET /preferencesfirstWorks across devices and renders already sorted on first paint without an extra round trip Long-running HTTP API 202 Accepted+ durable job ID + status endpointHold HTTP connection open for 60+ sSurvives proxy timeouts, Wi-Fi drops, and page refreshes cleanly Job queue storage PostgreSQL generationstable (FOR UPDATE SKIP LOCKED)External broker (SQS/Kafka) + outbox relay At ~7 jobs/s, eliminates dual-write bugs and extra infra with one atomic tableWorker fault tolerance Time-bounded leases + Reaper + attemptsfencing tokenFire-and-forget worker execution Recovers crashed GPU jobs while preventing zombie workers from overwriting results Gallery item ordering Monotonic per-user user_seqassigned at submissionSort by finished_atorcreated_atPlaceholders never jump when fast jobs finish early; immune to clock/commit-order skew
Intuition & how it works
Think of the two parts of this system through two everyday mental models:
- Sortable comments with persisted preference work like a library card catalog with a personal bookmark. Instead of counting
"skip the first 5,000 cards"every time you turn a page, your bookmark records the exact coordinates of the last card you read — such as(author_id = 7, created_at = 10:02, comment_id = 904)— so the database jumps straight to the next card in a B-tree index (a sorted tree structure whose leaf entries are linked in both directions). Meanwhile, your preferred catalog order (timestampvs.userId, ascending vs. descending) is saved on your account profile and applied automatically inside the comment-list API response, so refreshing the page renders the right sort on the very first paint. - Async image generation with stable UI ordering works like a custom framing shop that hands out numbered claim tickets (
#101,#102). Because painting and framing take far longer than a customer can stand blocking the cash register, the cashier immediately hands back ticket#101(202 Accepted), reserves spot#101on your display wall right away, and lets workshops in the back paint asynchronously. Even if simple ticket#102finishes drying in12seconds while detailed ticket#101takes40seconds, each finished picture goes into its pre-assigned numbered frame so nothing jumps around on the wall.
Naive designs fail fast on both halves. For comments, OFFSET 5000 LIMIT 50 scans and discards 5,000 rows on every deep scroll and duplicates or skips rows whenever someone posts a new comment, while keeping sort state only in React memory loses it on refresh (and fetching preferences in a separate API call causes a visible re-sort flicker). For image generation, holding an HTTP POST open for a 45-second GPU job fails across 60 s load-balancer idle timeouts and page refreshes, while sorting the gallery by completion time causes cards to reshuffle under the user's cursor.
Trace both workflows side by side on concrete examples:
Part 1: Refreshing & paging comments (saved preference: userId ASC, page size = 2)
1. Refresh page -> GET /v1/threads/10/comments (no sort param)
-> Server looks up user_preferences (userId, asc), scans idx_comments_user forward:
returns [(user=3, id=501), (user=3, id=504)] + applied_sort={userId, asc}
2. Scroll next -> GET /v1/threads/10/comments?sort=userId&order=asc&cursor=(3, 09:05, 504)
-> Seeks > (3, 09:05, 504) in B-tree -> returns [(user=3, id=509), (user=8, id=499)]
Part 2: Two concurrent image jobs finishing out of order
1. t = 0s POST "complex castle" -> 202 Accepted (user_seq = 101). Gallery: [ #101 Queued ]
2. t = 3s POST "simple apple" -> 202 Accepted (user_seq = 102). Gallery: [ #102 Queued, #101 Running ]
3. t = 15s "simple apple" finishes first! Slot #102 updates in place: [ #102 Images, #101 Running ]
4. t = 40s "complex castle" finishes! Slot #101 updates in place: [ #102 Images, #101 Images ]
Key trade-offs
- Keyset (cursor) pagination vs.
OFFSET / LIMITpagination. Keyset pagination (resuming from the last row's indexed tuple rather than a numeric row count) runs inO(log N + page_size)time even at comment #100,000 and never skips or repeats items when new comments arrive. The trade-off is that users cannot jump directly to an arbitrary"Page 37", and every supported sort needs a matching composite index ending in a unique tie-breaker (comment_id). - Server-stored sort preference applied inline vs.
localStorage-only vs. separate preference fetch. Savingcomment_sortandcomment_orderinuser_preferencesand applying it directly insideGET /threads/{id}/commentswhen URL parameters are omitted preserves the preference across refreshes and devices in a single round trip with zero UI re-sort flash.localStoragealone costs zero backend work and supports logged-out guests, so keepingURL > server preference > localStoragecombines shareable links, cross-device sync, and guest support at the cost of a small precedence rule. - PostgreSQL
FOR UPDATE SKIP LOCKEDqueue vs. external message broker (SQS / Kafka). At~7new image jobs per second, claiming work directly from thegenerationstable withSKIP LOCKEDkeeps a single source of truth and eliminates the dual-write bug (committing a database row, crashing before publishing a broker message, and leaving a job stuck forever). High-throughput pipelines (1,000+jobs/s) or multi-consumer event streams justify an external broker paired with a transactional outbox (writing the queue event into anoutboxtable in the same SQL transaction and relaying it asynchronously). - Worker leases +
attemptsfencing tokens vs. fire-and-forget workers. Giving each worker a60 slease (a time-bounded claim renewed by15 sheartbeats) lets a reaper re-queue jobs when spot GPUs crash, while checking a monotonically increasing fencing token (WHERE attempts = :my_attempt) on commit guarantees a paused zombie worker waking up late cannot overwrite a newer worker's finished images. We accept rare duplicate GPU compute on crashes to achieve exact-once visible gallery results. - Adaptive HTTP polling + optional Server-Sent Events (SSE) vs. WebSockets. Adaptive polling (
1 s -> 2 s -> 5 s) is stateless, trivial to debug, and adds only~30 QPSat 200,000 daily jobs. Layering Server-Sent Events (SSE) (a unidirectional HTTP push stream) backed by Redis Pub/Sub delivers smooth denoising progress bars without requiring full bidirectional WebSocket state machines, provided clients re-sync viaGET /generationson reconnect. - Per-user submission counter (
user_seq) vs.created_atorfinished_atordering. Assigninguser_sequnder the user's row lock atPOSTtime guarantees gallery cards never jump around when fast prompts overtake slow prompts and avoids PostgreSQLnow()transaction-start vs. commit-order inversions, at the negligible cost of serializing a single user's ownPOST /generationscalls (~1 ms row lock).
Common mistakes
- Sorting without a unique tie-breaker column: Writing
ORDER BY author_id ASCwithout, created_at ASC, comment_id ASCproduces non-deterministic row order among comments by the same author, causing cursor pages to miss or duplicate comments. - Storing sort preference only in frontend component state (or fetching it in a second sequential call): In-memory state vanishes on refresh, while fetching
/me/preferencesafter loading default-sorted comments causes a jarring layout flash as the list re-sorts in front of the user. - Trusting
author_idfrom the request payload or skipping optimistic edit versioning: ReadinguserIdfrom JSON lets anyone spoof or delete others' comments, while unconditionalUPDATE comments SET body = ...silently clobbers concurrent edits across tabs. - Keeping an HTTP request open while waiting for GPU inference: Load balancers (
60 stimeout), mobile handoffs, and browser refreshes sever synchronous connections and lose expensive GPU work. - Dual-writing to PostgreSQL and Redis/SQS without an outbox: Updating two systems independently without a transactional link guarantees eventual orphaned jobs under pod crashes or brief network blips.
- Running background jobs without leases, bounded retries, or fenced commits: A single crashed GPU node leaves a job stuck in
"running"forever, an un-capped poison prompt crash-loops the entire GPU pool, and an unfenced late worker can overwrite canceled or already-completed outputs. - Storing multi-megabyte PNGs inside PostgreSQL
BYTEAcolumns or sorting the gallery by completion timestamp: Blobs bloat database backups and buffer caches (1.24 TB/daybelongs in S3 + CDN), and completion-time sorting makes UI cards jump unpredictably.
Follow-up questions
- How would you add nested reply threads to the comment system without breaking sorting or pagination? Add
parent_id BIGINT NULL(for immediate parent) androot_id BIGINT NULL(pointing to the top-level comment) tocomments. Keep user-selected sorting (timestamporuserId,ascordesc) on top-level comments (WHERE thread_id = :tid AND parent_id IS NULL) using the exact same composite keyset indexes, because sorting nested replies byuserIdbreaks conversational flow. Fetch replies per visible top-level comment (or batch-load the first 3 replies per root) in chronological order using a dedicated index(thread_id, root_id, created_at ASC, comment_id ASC)with a"Load more replies"cursor, and render soft-deleted parent comments that still have child replies as"[deleted]"placeholders so reply subtrees stay attached. - How do you stop one heavy user who submits hundreds of image jobs at once from starving other users? Protect the system at two layers: admission control at
POST /v1/generations(checked atomically under theusersrow lock) caps each user at say20non-terminal (queued+running) jobs and returns429 Too Many RequestswithRetry-Afterbeyond that limit, while fair scheduling in the worker claim query skipsqueuedjobs belonging to users who already have4jobs inrunningstate so one power user cannot monopolize all 130 GPUs. If enterprise customers legitimately need bulk 500-image runs, expose a dedicated/v1/batch-generationsendpoint routed to a lower-priority queue (priority = 10) running on cheaper spot GPUs with a 24-hour completion SLA. - When should job queuing move from PostgreSQL SKIP LOCKED to a dedicated broker, and how do you prevent dual-write job loss? Migrate when job creation climbs into thousands of jobs per second, when polling/locking overhead contends with core OLTP queries on the primary database, or when multiple independent downstream services need to consume job events. To prevent the dual-write bug where a job row commits in PostgreSQL but the SQS/Kafka publish fails, use the Transactional Outbox pattern: insert both the
generationsrow and anoutbox_eventsrow inside the same PostgreSQL transaction, then have a lightweight relay process (or Change Data Capture via Debezium) publishoutbox_eventsat-least-once to the broker while workers deduplicate claims idempotently on(generation_id, status = 'queued').
Follow-up questions
- How would you add nested reply threads to the comment system without breaking sorting or pagination?
- How do you stop one heavy user who submits hundreds of image jobs at once from starving other users?
- When should job queuing move from PostgreSQL SKIP LOCKED to a dedicated broker, and how do you prevent dual-write job loss?
Similar questions
- Browser-Only Threaded Comment Widget with Local Persistence
- Construct Comment Hierarchy from Flat Replies
- Diagnosing Frontend Latency and Managing Production Incidents
- Sortable and Filterable Nested Comment Threads
- Global Live Video Streaming Platform
- Multi-User Collaborative Document Editor