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:

  1. 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 timestamp or userId (either ascending or descending), and each user's chosen ordering must survive full page reloads.
  2. 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 / userId sort 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

  1. 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,000 characters) 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) or userId (author_id) in asc or desc order, fetched one page at a time (50 comments per page).
    • Persisted sort preference: If a user picks userId asc and refreshes the browser — or logs in on another laptop — the comment list opens directly in userId asc order. Logged-out guests fall back to browser localStorage.
    • Non-functional goals: Comment list reads < 200 ms p99; 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 15 to 120 seconds (plus queue wait during traffic spikes). Standard reverse proxies and cloud load balancers drop idle HTTP connections after 30–60 seconds, 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, running with 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 s p95 under normal load).
  2. Back-of-the-envelope capacity estimates

    Assume a collaborative platform with 5,000,000 daily 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 QPS average, ~3,500 QPS peak). New comments: 5M * 0.5 = 2.5M writes/day (~29 TPS average, ~90 TPS peak), 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/s average, ~7 jobs/s peak). Suppose each job generates 4 images in one GPU pass taking 15 s of 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.
    • 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 every 2 s across a ~25 s active lifetime gives ~13 polls/job -> 2.6M polls/day (~30 QPS average, ~90 QPS peak).
    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 + CDN
    

    Key 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.

  3. 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 in Location for 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 stream
    

    Notice author_id is always extracted from the verified authentication token on the backend — never trusted from the JSON request body!

  4. 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 comments serve all four sort combinations (timestamp asc/desc and userId asc/desc)? 1. Every query filters on WHERE thread_id = :thread_id first. Inside one thread_id slice 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. Appending comment_id as the final column provides a unique tie-breaker: when one user posts 20 comments (author_id ties) or two users post in the same millisecond (created_at ties), every row still has a deterministic, unique position in the index.

  5. 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 |
                         +------------------+
    
  6. Deep dive 1: Keyset pagination, persisted sort preference, and CRUD sync

    1. Why Keyset (Cursor) Pagination beats OFFSET If a user scrolls deep into a 50,000-comment thread using OFFSET 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 calls GET /v1/threads/{id}/comments (with no sort param). On the backend, the handler joins/looks up user_preferences for the authenticated user (1 primary-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 sort and order, updates the URL via history.replaceState, caches the choice in localStorage (for offline/logged-out fallback), and fires PUT /v1/me/preferences/comment-sort asynchronously in the background.

    3. Frontend-backend CRUD synchronization - Create: Generate Idempotency-Key on button click and render an optimistic "Posting..." comment (at the top if viewing timestamp desc, or with a "Jump to your comment" toast if sorted by userId where your position is off-screen). Retries reuse the same Idempotency-Key so UNIQUE (author_id, idem_key) prevents duplicates. - Edit (PATCH): Send the version integer loaded with the comment. Backend runs UPDATE 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, 0 rows match -> return 409 Conflict with the latest server version so the user doesn't silently overwrite their other tab. - Read-your-own-writes: Because read replicas can lag by 50–200 ms, when a user writes a comment the backend sets a 3-second session cookie/header (recent_write_until) that routes that user's GET requests to the PostgreSQL primary until replicas catch up.

  7. Deep dive 2: Accepting and running long image jobs safely

    1. Fast, atomic job acceptance (202 Accepted) When POST /v1/generations arrives, the API runs a quick prompt-safety check, then executes a millisecond transaction locking that single user's row in users:

    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 in queued forever (fixing that requires an extra transactional outbox table and relay worker). At ~7 jobs/s, PostgreSQL's FOR UPDATE SKIP LOCKED lets 130 GPU workers claim jobs directly from generations in 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_at every 15 s (UPDATE generations SET lease_expires_at = now() + interval '60 seconds' WHERE generation_id = :id AND attempts = :token AND status = 'running'). Every 30 s, the Lease Reaper scans for status = 'running' AND lease_expires_at < now(): if attempts < 3, it resets status = 'queued'; otherwise it marks status = '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 for 75 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 on attempts:

    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.
    
  8. 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} every 1 s for the first 5 s, then every 2 s, backing off to 5 s, and stops once status reaches succeeded, failed, or canceled. At ~30 QPS average across 5M DAU, stateless polling is rock-solid, survives corporate firewalls, and works automatically after any page refresh (GET /v1/generations reloads 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 channel user:{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-fetches GET /v1/generations?limit=20 whenever 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", takes 40 s) and Job B at 10:00:03 ("minimalist icon", takes 12 s). - If the UI ordered items by completion time (finished_at DESC), Job B would appear first at 10: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 by created_at DESC? Browser clocks skew across devices, and in PostgreSQL now() returns the transaction start timestamp rather than commit order, so two concurrent submissions can commit in reverse timestamp order. - Our solution — Per-user monotonic user_seq assigned at submission: Every accepted job receives user_seq (101, 102, ...), and the gallery always sorts by user_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/generations is still in flight (< 300 ms), the UI renders a temporary card at the very top keyed by the client's Idempotency-Key, then snaps its permanent key to user_seq as soon as the 202 response arrives. Every tab and device converges on the exact same user_seq DESC order!

  9. 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 s TTL, 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, shard comments horizontally by thread_id (every list/create query stays single-shard) and user_preferences by user_id.

    Scaling GPU workers & image storage - Cold-start aware autoscaling: Booting a cloud GPU node and loading 10+ GB diffusion model weights into VRAM takes 2–4 minutes. 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 have 4 jobs in running status so one heavy user never monopolizes 20 GPUs. If total queue wait exceeds 3 minutes, return 429 (or display an upfront queue ETA before submission). - Cancellation & S3 cleanup: POST /cancel sets cancel_requested = true in PostgreSQL and writes a short-lived cancel:{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 unreferenced attempt-{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 /comments or POST /generations Client retries with same Idempotency-Key; UNIQUE index returns original record Zero duplicate comments or duplicate GPU jobs
    Author edits same comment in two browser tabs Second PATCH sees stale version -> 409 Conflict with latest body Zero silent lost edits
    GPU spot VM preempted mid-generation 60 s lease expires; Reaper re-queues job (attempts < 3) with same random seed Zero lost jobs; automatic recovery
    Frozen worker wakes up after lease reassignment Conditional UPDATE ... WHERE attempts = :old matches 0 rows and rolls back Exactly one committed image set per job
    Prompt deterministically crashes GPU kernel Fails permanently after 3 attempts (error_code = 'inference_error') Bounded retries; protects GPU fleet
    Redis cluster restarts Progress percentages pause briefly; GET endpoints still read accurate state from PostgreSQL Zero data loss (Redis holds only disposable state)
  10. Summary of architectural trade-offs

    Design decision Chosen approach Main alternative Why this trade-off fits best
    Comment pagination Keyset cursor with comment_id tie-breaker SQL OFFSET / LIMIT Constant O(log N) seek at any depth; immune to duplicate/skipped rows on new inserts
    Sort preference sync Server user_preferences applied inside GET /comments + URL + localStorage localStorage only, or separate GET /preferences first Works across devices and renders already sorted on first paint without an extra round trip
    Long-running HTTP API 202 Accepted + durable job ID + status endpoint Hold HTTP connection open for 60+ s Survives proxy timeouts, Wi-Fi drops, and page refreshes cleanly
    Job queue storage PostgreSQL generations table (FOR UPDATE SKIP LOCKED) External broker (SQS/Kafka) + outbox relay At ~7 jobs/s, eliminates dual-write bugs and extra infra with one atomic table
    Worker fault tolerance Time-bounded leases + Reaper + attempts fencing token Fire-and-forget worker execution Recovers crashed GPU jobs while preventing zombie workers from overwriting results
    Gallery item ordering Monotonic per-user user_seq assigned at submission Sort by finished_at or created_at Placeholders 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:

  1. 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 (timestamp vs. 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.
  2. 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 #101 on your display wall right away, and lets workshops in the back paint asynchronously. Even if simple ticket #102 finishes drying in 12 seconds while detailed ticket #101 takes 40 seconds, 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 / LIMIT pagination. Keyset pagination (resuming from the last row's indexed tuple rather than a numeric row count) runs in O(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. Saving comment_sort and comment_order in user_preferences and applying it directly inside GET /threads/{id}/comments when URL parameters are omitted preserves the preference across refreshes and devices in a single round trip with zero UI re-sort flash. localStorage alone costs zero backend work and supports logged-out guests, so keeping URL > server preference > localStorage combines shareable links, cross-device sync, and guest support at the cost of a small precedence rule.
  • PostgreSQL FOR UPDATE SKIP LOCKED queue vs. external message broker (SQS / Kafka). At ~7 new image jobs per second, claiming work directly from the generations table with SKIP LOCKED keeps 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 an outbox table in the same SQL transaction and relaying it asynchronously).
  • Worker leases + attempts fencing tokens vs. fire-and-forget workers. Giving each worker a 60 s lease (a time-bounded claim renewed by 15 s heartbeats) 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 QPS at 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 via GET /generations on reconnect.
  • Per-user submission counter (user_seq) vs. created_at or finished_at ordering. Assigning user_seq under the user's row lock at POST time guarantees gallery cards never jump around when fast prompts overtake slow prompts and avoids PostgreSQL now() transaction-start vs. commit-order inversions, at the negligible cost of serializing a single user's own POST /generations calls (~1 ms row lock).

Common mistakes

  • Sorting without a unique tie-breaker column: Writing ORDER BY author_id ASC without , created_at ASC, comment_id ASC produces 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/preferences after loading default-sorted comments causes a jarring layout flash as the list re-sorts in front of the user.
  • Trusting author_id from the request payload or skipping optimistic edit versioning: Reading userId from JSON lets anyone spoof or delete others' comments, while unconditional UPDATE comments SET body = ... silently clobbers concurrent edits across tabs.
  • Keeping an HTTP request open while waiting for GPU inference: Load balancers (60 s timeout), 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 BYTEA columns or sorting the gallery by completion timestamp: Blobs bloat database backups and buffer caches (1.24 TB/day belongs 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) and root_id BIGINT NULL (pointing to the top-level comment) to comments. Keep user-selected sorting (timestamp or userId, asc or desc) on top-level comments (WHERE thread_id = :tid AND parent_id IS NULL) using the exact same composite keyset indexes, because sorting nested replies by userId breaks 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 the users row lock) caps each user at say 20 non-terminal (queued + running) jobs and returns 429 Too Many Requests with Retry-After beyond that limit, while fair scheduling in the worker claim query skips queued jobs belonging to users who already have 4 jobs in running state so one power user cannot monopolize all 130 GPUs. If enterprise customers legitimately need bulk 500-image runs, expose a dedicated /v1/batch-generations endpoint 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 generations row and an outbox_events row inside the same PostgreSQL transaction, then have a lightweight relay process (or Change Data Capture via Debezium) publish outbox_events at-least-once to the broker while workers deduplicate claims idempotently on (generation_id, status = 'queued').

Follow-up questions

Similar questions

More Bobyard interview questions

All 5 Bobyard questions →