System Design - Image Service
1. Requirements and assumptions
Initial requirement: authenticated users upload images, then view them through a URL. Start at a small scale before supporting 10 million users, large files, and a global audience.
Questions to ask: maximum size and formats; public or private images; upload and read volumes; regions and data residency constraints; expected latency and availability; retention period; transformations; target cost.
2. Minimal architecture
Question: how should the service be designed for a small number of concurrent users?
Solution: an API server, a relational database for users and metadata, and object storage for image bytes. Ideally, metadata contains a stable object key (rather than an expiring signed URL). The API exposes creation, retrieval, and authentication operations.
flowchart LR
C[Client] -->|HTTPS| A[Single API]
A -->|Users and metadata| DB[(PostgreSQL)]
A -->|Image files| OS[(Object Storage)]Possible API: POST /images, GET /images/{id}, GET /users/{id}/images. GET /images/{id} can return metadata and an access URL; downloading the bytes can be a separate operation.
Tradeoff: a simple, cost-effective architecture, but the single API is a potential point of failure and bottleneck.
3. 10 million users and large uploads
Question: how can bandwidth consumption on API servers be limited?
Initial safeguards: size limits, authentication, quotas, rate limiting, a load balancer, and stateless API instances. These protect the service and distribute load, but do not prevent image bytes from passing through the API.
Solution: direct upload with a presigned URL
sequenceDiagram
participant C as Client
participant API as API
participant DB as DB
participant S as Object Storage
C->>API: POST /images (name, size, type)
API->>API: Auth, quota, validation
API->>DB: Create PENDING image + object key
API-->>C: imageId + temporary presigned URL
C->>S: PUT image directly (signed URL)
S-->>C: Upload successful
S-->>API: ObjectCreated event (via bus/queue)
API->>DB: UPLOADED (after verification)The API remains the control plane; transfers go directly from the client to object storage (data plane). For large files, multipart/resumable uploads can resume missing parts. The signature must constrain the key, expiration, and, depending on the provider, the permitted method and properties. Actual size and content must be checked by storage/processing, rather than relying only on client declarations.
Why not use a queue for uploads? A queue is useful for processing after upload, but does not prevent the image from passing through the API if the API still receives the file.
4. Global reads and latency
Question: with hundreds of millions of reads across several continents, how can GET requests be accelerated?
Main solution: a CDN in front of object storage, with caching at geographic points of presence.
flowchart TB
EU[User in Europe] --> CDN[CDN / Edge cache]
AS[User in Asia] --> CDN
US[User in the Americas] --> CDN
CDN -->|Cache misses only| OS[(Origin Object Storage)]Cache hit: the CDN serves the image without contacting the origin. Cache miss: it retrieves the object and caches it according to the rules. Versioned URLs or immutable keys simplify invalidation. For private images: check authorization before issuing a signed CDN URL/cookie, with an appropriate TTL. Do not make a private object public simply because it is served through a CDN.
Alternative: multi-region storage replication for residency, resilience, or origin latency requirements; more costly and complex than a CDN alone.
5. Upload interrupted at 80%
Question: the database contains an image record, but the upload fails; how can consistency be preserved?
Solution: a state machine + success event + reconciliation of stalled uploads. A network interruption does not necessarily produce a reliable failure event.
stateDiagram-v2
[*] --> PENDING: Create upload intent
PENDING --> UPLOADED: Validated object present
PENDING --> FAILED: Expiration / cleanup
UPLOADED --> PROCESSING: Job started
PROCESSING --> READY: Processing successful
PROCESSING --> FAILED: Permanent failure
FAILED --> PENDING: Retry allowedflowchart LR
DB[(DB: PENDING)] --> R[Periodic reconciler]
R -->|Check age and object presence| OS[(Object Storage)]
R -->|Object missing / upload expired| F[FAILED + cleanup]
R -->|Complete and valid object| U[UPLOADED]Storage events may be delivered more than once: make transitions idempotent. Incomplete multipart uploads and orphaned objects also need cleanup. Rows do not have to be deleted immediately: retaining FAILED helps diagnosis and recovery.
6. Validation, thumbnails, metadata, and compression
Question: how can images be processed without blocking uploads?
Solution: storage events, a durable queue, and asynchronous workers. Actual file validation must precede transformations; do not trust the extension or declared MIME type. For an ordered pipeline, use an orchestrator or a sequence of steps, rather than blindly launching every operation in parallel.
flowchart TD
OS[(Object Storage)] -->|ObjectCreated| EV[Event Bus]
EV --> Q[[Processing Queue]]
Q --> W[Autoscaled workers]
W --> V{Valid image?}
V -->|No| F[FAILED / quarantine]
V -->|Yes| M[Metadata extraction]
M --> T[Thumbnails in 3 sizes]
T --> C[Optional compression]
C --> OUT[(Object Storage: variants)]
OUT --> R[DB: READY]Monitor CPU, memory, processing time, errors, and queue depth/age. Workers can specialize in validation or transformations if their load profiles diverge.
7. Crash before ACK and duplicate messages
Question: a worker writes the thumbnails, then crashes before ACK; the job is redelivered.
Solution: assume at-least-once delivery, use deterministic keys, and make progress idempotent.
sequenceDiagram
participant Q as Queue
participant W1 as Worker A
participant S as Object Storage
participant W2 as Worker B
Q->>W1: image-123
W1->>S: Write images/123/thumb-small-v1.jpg
Note over W1: Crash before ACK
Q->>W2: Redeliver image-123
W2->>S: Check / regenerate the same key
W2->>Q: ACK after persistenceBeware of race conditions: if (!exists) create is not atomic. Possible solutions: database uniqueness, conditional writes, compare-and-swap/versioning, a lock, or an atomic job claim. If transformations are deterministic, rerunning them must lead to the same final state.
8. A queue with 2 million jobs
Question: how can the backlog be detected and handled automatically?
Metrics: queue depth, age of the oldest message, incoming/outgoing throughput, average processing time, failure rate, CPU/memory saturation, and UPLOADED → READY latency.
flowchart LR
Q[[Queue]] --> MET[Metrics / Monitoring]
MET -->|Age / backlog above threshold| AS[Autoscaler]
AS --> W[Worker pool]
W -->|Consumes| Q
W --> DB[(DB)]
W --> OS[(Object Storage)]Nuance: adding workers increases pressure on the database and storage. Size capacity according to the actual bottleneck, rather than queue length alone. A broker already distributes messages to concurrent consumers; an HTTP load balancer in front of the queue is generally not the answer.
9. 500 workers saturate the database
Question: what should be done if every worker reads and writes statuses?
Diagnose before choosing a solution: repeated reads? Connections? CPU? I/O? Locks? Slow queries? Write volume?
flowchart TD
A[Saturated DB] --> B{Bottleneck identified?}
B -->|Connections| C[Connection pooling + limits]
B -->|Repeated reads| D[Cache if hit rate is sufficient]
B -->|Slow queries| E[EXPLAIN / indexes / SQL]
B -->|Many writes| F[Fewer transitions + batching if acceptable]
B -->|Concurrency| G[Backpressure / semaphore / bounded pool]
C --> H[Measure again]
D --> H
E --> H
F --> H
G --> H
H --> I{Still insufficient?}
I -->|Yes| J[Vertical scaling / partitioning / sharding based on measurements]
I -->|No| K[Keep the architecture simple]Connection pooling
Reuses connections and bounds their number; a pool is often per process, so 500 workers with a pool of 20 could theoretically request 10,000 connections. A shared proxy/pooler (such as PgBouncer) and global limits can help.
Reducing writes
Do not write every substep unless the business requires it. Example: PENDING → PROCESSING → READY/FAILED rather than seven persisted intermediate states.
Batching
Grouping independent updates can reduce round trips and transaction overhead, but adds latency and complicates failure handling. A durable flush mechanism is needed, or the potential loss of in-memory buffers must be accepted.
Concurrency limits / backpressure
Limit simultaneous database requests through pools, semaphores, batch sizes, or consumption rates. This can increase useful throughput by preventing collapse under contention.
Queries and indexes
Analyze query plans (EXPLAIN ANALYZE), avoid SELECT *, N+1 queries, and unnecessary scans; index according to actual filters and sort orders. Example: (UserId, CreatedAt DESC) for a user's latest images. Indexes have a write cost: avoid creating them without justification.
Why not immediately use several databases? Read replicas mainly help reads, rather than a primary saturated by writes. Sharding can distribute writes but significantly increases complexity.
10. Target overall architecture
flowchart TB
CLIENT[Web / Mobile clients] --> LB[Load Balancer / API Gateway]
LB --> API[Stateless API: auth, quotas, metadata]
API --> DB[(PostgreSQL: users, images, jobs)]
API -->|Presigned PUT URL| CLIENT
CLIENT -->|Direct upload| ORIGIN[(Object Storage: originals)]
CLIENT -->|GET images via signed URL if private| CDN[CDN / Edge Cache]
CDN -->|Cache miss| ORIGIN
ORIGIN -->|ObjectCreated| BUS[Event Bus]
BUS --> Q[[Processing Queue]]
Q --> WORKERS[Workers: validation, thumbnails, compression]
WORKERS --> VARIANTS[(Object Storage: variants)]
WORKERS --> DB
CDN -->|Variants origin| VARIANTS
DB --> RECON[Reconciler for expired PENDING uploads]
RECON --> ORIGIN
Q --> OBS[Metrics / Alerting]
WORKERS --> OBS
DB --> OBS
OBS --> AUTO[Autoscaler + concurrency limits]
AUTO --> WORKERSReading the diagram: the client obtains a download URL from the API if the image is private; the bytes then pass through the CDN. Presigned PUT and GET URLs have distinct permissions and lifetimes. Object storage remains private by default, with authorized access for the CDN and workers.
11. Illustrative data model
CREATE TABLE Images (
Id UUID PRIMARY KEY,
UserId UUID NOT NULL,
ObjectKey TEXT NOT NULL UNIQUE,
Status TEXT NOT NULL,
ContentType TEXT,
SizeBytes BIGINT,
CreatedAt TIMESTAMPTZ NOT NULL,
UpdatedAt TIMESTAMPTZ NOT NULL,
Version BIGINT NOT NULL DEFAULT 0
);
CREATE INDEX idx_images_user_created ON Images (UserId, CreatedAt DESC);
CREATE INDEX idx_images_pending_updated ON Images (UpdatedAt) WHERE Status = 'PENDING';Do not store an expiring presigned URL as a permanent reference: keep an object key and generate temporary access on demand. Variants can be modeled in a dedicated table (ImageVariants).
12. Illustrative API
| Endpoint | Role |
|---|---|
POST /images | Validate the request, create PENDING, return ID and upload URL |
GET /images/{id} | Read status and metadata after authorization |
GET /images/{id}/download | Generate an authorized read/CDN URL |
GET /users/{id}/images | List with pagination |
DELETE /images/{id} | Request logical/physical deletion according to policy |
Illustrative initial response:
{
"imageId": "123",
"status": "PENDING",
"uploadUrl": "https://storage.example/upload-temporary-signature",
"expiresInSeconds": 300
}13. Security, reliability, and operations
- AuthN/AuthZ: each image belongs to a user; check permissions before providing a read URL.
- Validation: size, actual format, malicious decompression, sensitive metadata, scanning if needed.
- Uploads: quotas, signature TTL, cleanup of incomplete parts and orphaned objects.
- Processing: idempotency, retries with backoff, DLQ for persistent failures, timeouts.
- Availability: health checks, multiple API instances, database backups, and a recovery strategy.
- Observability: logs correlated by
imageId, upload/processing traces, p95/p99 metrics, queue age, errors, and storage/egress costs. - Compliance: deletion, retention, location, and encryption as required.
14. Tradeoffs
| Decision | Benefit | Cost / limitation |
|---|---|---|
| Initial single API | Simplicity | Limited availability and capacity |
| Stateless API + LB | Horizontal scaling | More complex deployment/observability |
| Signed direct upload | Avoids transferring large files through the API | Asynchronous finalization and content checks |
| CDN | Lower latency and origin load | Invalidation and access control |
| Queue + workers | Decoupling, buffering | Retries, duplicates, backlog |
| Redis cache | Fewer repeated database reads | Little benefit with a low hit rate; invalidation |
| Pooling + backpressure | Protects the database | Waiting and throughput limits |
| Sharding | Distributes write load | Difficult cross-shard queries and migrations |
15. Checklist
- Clarify: who uploads, who reads, volumes, size, privacy, latency, availability.
- Propose the minimal version: API, metadata database, object storage.
- Explain the byte path: direct upload through a signed URL.
- Explain the read path: CDN, cache, permissions.
- Define the lifecycle
PENDING → UPLOADED → PROCESSING → READY/FAILED. - Handle crashes, timeouts, duplicates, retries, and reconciliation.
- Measure before scaling; protect dependencies with backpressure.
- Justify each technology through a constraint and a tradeoff.