Full-Stack Comment CRUD and Async Image Pipeline
System DesignModel answerLast updated
Build a comment system with sort persistence and an image-generation service that handles long-running GPU jobs with reliable ordering and status delivery.
You are building two independent systems and need to design the full stack for each.
System A: Comment Platform
Design a complete comment system that supports the following:
- Users can create, read, update, and delete comments on a resource (such as a blog post or document)
- Comments can be sorted by either creation time or author ID, in ascending or descending order
- The user's chosen sort configuration must be remembered and applied automatically when they return to the page, even after closing the browser
Specify the API endpoints, database schema, frontend-backend interaction, and how you will implement stable pagination and preference persistence.
System B: Image Generation Pipeline
Design a service that processes image-generation requests using GPU workers. Image generation is computationally expensive and takes anywhere from 10 seconds to several minutes per request.
Your design must handle:
- Accepting user requests and returning a response immediately, even though processing has not completed
- Running the generation work asynchronously on a pool of GPU workers
- Exposing job status and progress to users
- Delivering the final generated image once complete
- Preserving a stable, well-defined order of generated images in the user's gallery
Explain your architecture, data model, API design, and how you ensure reliability when workers crash or jobs fail.
Clarifying questions are encouraged. State your scale assumptions.
Hints
Hint 1
For comments, consider what happens when two rows share the same sort value — how do you avoid duplicates or gaps across pages?
Hint 2
Image jobs outlive HTTP timeouts; you need a pattern that decouples request acceptance from work execution.
Hint 3
Think about layered persistence for the sort preference: what survives a refresh? What follows the user across devices?
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Model Answer
This problem tests whether you can design clean, practical full-stack systems. The first system emphasizes correct CRUD patterns, stable pagination, and layered state persistence. The second tests your understanding of asynchronous job orchestration, queue-based architectures, and fault tolerance. Strong answers unify both with shared principles: deterministic ordering, idempotency, and clear API contracts.
System A: Comment Platform
Requirements and Scale Assumptions
State your assumptions upfront:
- Functional scope: flat comments on a resource (posts, documents, etc.). Users create, edit, and delete their own comments. Sort by
created_atoruser_id, ascending or descending. The sort preference persists across sessions. - Scale: 10 million comments total, 1,000 writes/second at peak, 20,000 reads/second. Read-heavy workload.
- Clarifications: Are comments threaded? (Assume flat for now.) Can users edit others' comments? (No, only their own.)
API Design
POST /resources/{resource_id}/comments
Body: {body: string}
Response: 201, {id, resource_id, user_id, body, created_at, updated_at}
GET /resources/{resource_id}/comments
Query: sort={created_at|user_id}, order={asc|desc}, cursor=..., limit=50
Response: {data: [...], next_cursor: "..."}
PATCH /comments/{id}
Body: {body: string, version: int}
Response: 200 | 409 Conflict
DELETE /comments/{id}
Response: 204
GET /users/me/preferences
PUT /users/me/preferences
Body: {comment_sort_field, comment_sort_order}
Data Model
PostgreSQL schema:
comments (
id BIGSERIAL PRIMARY KEY,
resource_id BIGINT NOT NULL,
user_id BIGINT NOT NULL,
body TEXT NOT NULL,
created_at TIMESTAMPTZ DEFAULT now(),
updated_at TIMESTAMPTZ DEFAULT now(),
deleted_at TIMESTAMPTZ,
version INT DEFAULT 1
);
CREATE INDEX idx_resource_time ON comments(resource_id, created_at, id) WHERE deleted_at IS NULL;
CREATE INDEX idx_resource_user ON comments(resource_id, user_id, created_at, id) WHERE deleted_at IS NULL;
user_preferences (
user_id BIGINT PRIMARY KEY,
comment_sort_field VARCHAR(32),
comment_sort_order VARCHAR(4)
);
Use a relational database because the data is structured and access patterns fit indexed range scans well.
Architecture
Request flow: React frontend → API gateway (auth, rate limiting) → stateless Comment API → Postgres primary (writes) + read replicas (reads).
Optional caching: Redis for the first page of hot resources. Invalidate on writes to that resource.
Critical Detail: Stable Pagination
Why cursor-based pagination matters:
- Sorting by
user_idalone is not unique. Many comments share the same author. Without a tie-breaker, pagination can skip or duplicate rows. - Always sort by a composite key that guarantees total order:
(sort_field, created_at, id).
Implementation:
The cursor encodes the last returned row's tuple, e.g., (user_id=42, created_at=2026-11-03T10:15:00Z, id=9847).
Query for the next page:
SELECT * FROM comments
WHERE resource_id = ?
AND (user_id, created_at, id) > (?, ?, ?)
AND deleted_at IS NULL
ORDER BY user_id, created_at, id
LIMIT 50;
For descending order, flip the comparison to < and reverse the ORDER BY.
Each (field, order) pair is served by one composite index. The database scans forward or backward without offset cost. Never use OFFSET—it degrades linearly with depth and shifts when new comments arrive.
Persisting Sort Preference
Use a three-layer strategy:
- URL query parameters (
?sort=user_id&order=desc): survives refresh, allows sharing, is the source of truth while the page is open. - localStorage: fallback when the URL has no preference. Works for anonymous users.
- Server-side
user_preferencestable: persists the choice across devices for logged-in users.
Resolution order on page load: URL → server preference → localStorage → default (created_at desc).
When the user changes the sort, the frontend updates the URL immediately and debounces a PUT to the server.
This layered approach balances immediacy, shareability, and cross-device consistency.
Updates, Deletes, and Consistency
- Authorization: verify
comment.user_id == authenticated_user_idon PATCH and DELETE. - Optimistic concurrency control: include a
versionfield.UPDATE ... WHERE id = ? AND version = ?. If no rows match, return 409 Conflict. Increment version on each update. - Soft deletes: set
deleted_atrather than removing rows. Preserves context and audit history. Use a partial index to exclude deleted rows from queries. - Optimistic UI updates: the frontend applies changes immediately and reverts if the server responds with an error.
System B: Image Generation Pipeline
Requirements and Scale
- Functional: accept image-generation requests, run them on GPU workers, expose status and progress, deliver results, and preserve stable ordering in the user's gallery.
- Timing: generation takes 10 seconds to 5 minutes—well beyond typical HTTP timeouts.
- Scale: 100,000 jobs/day, peaks around 20 jobs/second. Average generation time: 60 seconds. At steady state, you need roughly 70 concurrent GPU workers; autoscale for peaks.
- Clarifications: Do users see progress? (Yes, expose percentage.) Can they cancel? (Yes.) Retention policy? (Keep results for 30 days.)
API Design
POST /image-jobs
Body: {prompt, params}
Header: Idempotency-Key
Response: 202 Accepted, {job_id, seq, status: "queued"}
GET /image-jobs/{job_id}
Response: {job_id, status, progress, result_urls, error, created_at}
GET /image-jobs
Query: cursor=..., limit=20
Response: {data: [...], next_cursor: "..."} (ordered by seq descending)
DELETE /image-jobs/{job_id}
Response: 204 (cancels if not finished)
GET /image-jobs/events (Server-Sent Events)
Streams real-time status updates
Data Model
jobs (
job_id UUID PRIMARY KEY,
user_id BIGINT NOT NULL,
seq BIGSERIAL,
idempotency_key VARCHAR(64),
prompt TEXT,
params JSONB,
status VARCHAR(20), -- queued, running, succeeded, failed, canceled
attempts INT DEFAULT 0,
progress INT DEFAULT 0,
result_keys TEXT[],
error_message TEXT,
created_at TIMESTAMPTZ,
started_at TIMESTAMPTZ,
finished_at TIMESTAMPTZ,
lease_expires_at TIMESTAMPTZ,
UNIQUE(user_id, idempotency_key)
);
CREATE INDEX idx_user_seq ON jobs(user_id, seq DESC);
Store images in object storage (S3). Serve via CDN with presigned URLs. Never store binary data in the database.
Architecture
-
API Service:
- Validates request, enforces per-user rate limits and quotas.
- Checks idempotency key; if duplicate, returns existing job.
- Inserts job row with
status='queued'and enqueues message. - Use a transactional outbox or two-phase pattern to ensure the DB row and queue message stay consistent.
- Returns 202 Accepted immediately with
job_idandseq.
-
Message Queue: SQS or Kafka. Optional: separate queues for priority tiers.
-
GPU Worker Pool:
- Worker pulls job, updates
status='running'and setslease_expires_at. - Heartbeats periodically to extend lease and queue visibility timeout.
- Generates image, uploads to S3 with deterministic key
jobs/{job_id}/output.png. - Updates job with
status='succeeded',result_keys=[...],finished_at. - Publishes status event to Redis pub/sub.
- Pool autoscales based on queue depth.
- Worker pulls job, updates
-
Notification Service:
- Subscribes to Redis pub/sub.
- Pushes updates to clients over SSE or WebSocket.
- Clients fall back to polling
GET /image-jobs/{job_id}with exponential backoff.
Reliability and Fault Tolerance
At-least-once delivery: Messages may be delivered multiple times. Workers must be idempotent.
- Write outputs to a deterministic S3 key.
- Make status transitions conditional:
UPDATE jobs SET status='succeeded' WHERE job_id=? AND status='running'.
Worker crashes: When lease_expires_at passes, the message becomes visible again and another worker picks it up. Cap attempts (e.g., 3). After max retries, mark status='failed' and move to a dead-letter queue.
Ordering in the gallery: Use a per-user monotonic seq column. When the frontend fetches jobs, order by seq DESC. This guarantees stable display order regardless of completion time.
Trade-offs
- Polling vs. streaming: SSE/WebSocket gives instant feedback but adds connection overhead. Polling is simpler but increases latency. Offer both.
- Queue vs. DB as source of truth: The DB is authoritative. The queue is ephemeral. Workers update the DB and publish events; clients consume events but can always fall back to polling the DB.
- Idempotency keys: essential for retries and duplicate request protection. Store them with a TTL (e.g., 24 hours).
Common Mistakes
- Comment system: using OFFSET pagination, omitting tie-breakers in sort keys, hardcoding SQL field names from user input (SQL injection risk).
- Image pipeline: treating the queue as the source of truth, failing to handle duplicate processing, not planning for worker crashes, ignoring idempotency.
- Both: vague answers like "use caching" without specifying what, when, and how to invalidate; ignoring auth and rate limiting; not stating scale assumptions upfront.
Strong candidates reason through trade-offs, name specific technologies, and explain why each choice fits the problem.