Design an Asynchronous Job Service for Batch File Operations
System DesignModel answerLast updated
Design an HTTP API and backend system to process large batches of files asynchronously, handling long-running work, job tracking, and failures.
You're building a backend service for a cloud file storage platform that needs to run operations on user files—think thumbnail generation, optical character recognition, or content analysis.
Your task is to design the HTTP API and high-level system architecture.
Phase 1: Basic synchronous endpoint
Begin with a straightforward case:
- A client sends a batch of file identifiers (IDs or paths belonging to the authenticated user)
- Your service processes all of them and returns the complete results in one HTTP response
- Assume each file takes less than a second to process, so the entire request completes well within normal timeout windows
Design a REST endpoint such as POST /processFiles that handles this scenario. Include:
- How clients specify which files to operate on
- The shape of the response: per-file outcomes, any output data, error details
- Basic failure handling when individual files cannot be processed
Sketch the main backend components and request flow at a high level.
Phase 2: Supporting long-running batch jobs
Now make it realistic: each file may take seconds or minutes to process, and batches can be large. A blocking HTTP request will hit timeout limits and create a poor user experience.
Redesign the system to handle work asynchronously.
Updated requirements:
- Clients submit a batch and receive an immediate response, even if processing will take many minutes
- Clients can poll or query to learn:
- Current job status (queued, running, done, failed)
- Results for each file once available
- The system must tolerate:
- Server crashes and restarts without losing work
- Duplicate submission attempts from clients (idempotency)
- Scaling to handle many concurrent jobs
What to address
Provide a design covering:
-
API contract
- Endpoints for submitting a job, checking its status, and fetching results
- High-level structure of requests and responses
-
Core architecture
- How you persist job state (outline the data model)
- How processing work actually gets done (workers, task queues, etc.)
- How the system scales horizontally
-
Handling long-running operations
- Decoupling submission from execution to avoid tying up connections
- Ensuring clients can safely retry without creating duplicate jobs
- Dealing with partial outcomes (some files succeed, others fail)
-
Reliability and scale
- Making sure jobs survive crashes and eventually complete or are marked failed
- Strategies for idempotency and deduplication
- Key performance bottlenecks and how you'd address them
You don't need to write production code—just explain the design clearly enough that an engineer could build it from your description.
Hints
Hint 1
Think about how to decouple the HTTP request lifecycle from the actual work duration—what pattern separates submission from execution?
Hint 2
Consider what makes a retry safe: how can you tell whether a request with the same parameters has already been accepted?
Hint 3
For partial failures, decide whether to fail the entire job or track per-file outcomes independently—which gives better visibility and recovery options?
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Model Answer: Asynchronous Job Service for Batch File Operations
What this question evaluates
The interviewer wants to see whether you can design a practical API that evolves gracefully as latency grows. The synchronous case tests basic REST modeling. The async case tests your understanding of job orchestration, durability, idempotency, and failure modes. Strong candidates quantify assumptions, recognize the dual-write problem, and spend time on partial failures and recovery.
Clarify scope and assumptions
Before diving in, ask about scale and operation characteristics:
- Operation type: CPU-intensive per-file work (thumbnail, OCR, scan). Each file is independent. Results are small metadata or a reference to output stored elsewhere.
- Scale estimates: ~5M active users, ~1M jobs/day, averaging 25 files per job, max 1,000 files. That's roughly 25M file operations per day, ~300/sec average, maybe 1,500/sec peak.
- Latency: 10 seconds to 3 minutes per file. If average processing time is 45 seconds, sustaining 1,500 tasks/sec needs ~67,500 CPU-seconds, so many horizontally scaled workers.
- Guarantees: At-least-once execution is acceptable as long as operations are idempotent. Results must be durable once marked complete.
- Authorization: Users can only process files they own.
State these assumptions early to anchor the design discussion.
Phase 1: Synchronous batch endpoint
API design
POST /v1/process
Authorization: Bearer <token>
Content-Type: application/json
{
"operation": "thumbnail",
"parameters": {"width": 512, "height": 512},
"fileIds": ["file:abc123", "file:def456"]
}
Use stable file identifiers rather than paths, since paths can change on rename. If possible, include revision IDs (file:abc123@r5) to pin exactly which version was processed.
Response structure
Return 200 OK even when some files fail—this is a batch operation, so partial success is valid:
{
"operation": "thumbnail",
"results": [
{
"fileId": "file:abc123",
"status": "success",
"output": {
"url": "https://cdn.example.com/thumbs/abc123",
"sizeBytes": 14320
}
},
{
"fileId": "file:def456",
"status": "error",
"error": {
"code": "UNSUPPORTED_TYPE",
"message": "File format not supported for thumbnail generation",
"retriable": false
}
}
]
}
Use non-2xx status codes for request-level problems:
400for malformed input or batch size over limit (cap at ~50–100 files)401/403for auth failures429for rate limiting413if payload is too large
Per-file errors (not found, access denied, processing failure) go inside the results array. The retriable flag helps clients decide whether to resubmit.
Backend flow
- Load balancer routes to stateless API servers
- API server authenticates, validates file ownership via a metadata service, then fans out requests to a worker pool with limited concurrency per request
- Each worker fetches file bytes from object storage and performs the operation
- API server collects responses and returns the aggregated result
This works only when total time stays under typical LB/proxy timeouts (30–90 seconds).
Phase 2: Asynchronous job model
API endpoints
Submit a job:
POST /v1/jobs
Idempotency-Key: <client-generated-UUID>
Authorization: Bearer <token>
{
"operation": "ocr",
"parameters": {},
"fileIds": ["file:xyz", ...]
}
→ 202 Accepted
Location: /v1/jobs/job_k7m3n
{
"jobId": "job_k7m3n",
"status": "pending",
"createdAt": "2026-11-03T10:15:00Z"
}
The Idempotency-Key header (a UUID generated by the client) ensures that retries don't create duplicate jobs.
Check status:
GET /v1/jobs/job_k7m3n
→ 200 OK
{
"jobId": "job_k7m3n",
"status": "in_progress",
"progress": {
"total": 400,
"completed": 180,
"failed": 2,
"pending": 218
},
"createdAt": "...",
"updatedAt": "...",
"retryAfter": 5
}
Status values: pending, in_progress, completed, completed_with_errors, failed, cancelled.
Fetch results:
GET /v1/jobs/job_k7m3n/results?cursor=<opaque>&limit=100
→ 200 OK
{
"results": [
{ "fileId": "...", "status": "success", "output": {...} },
{ "fileId": "...", "status": "error", "error": {...} }
],
"nextCursor": "..."
}
Separate status and results endpoints: status is lightweight and polled frequently; results can be large (thousands of entries) so they're paginated and fetched once or streamed incrementally.
Optional: cancel a job:
POST /v1/jobs/job_k7m3n/cancel
→ 202 Accepted
Data model
jobs table (sharded by job_id, secondary index on user_id):
| Column | Purpose |
|---|---|
job_id (PK) | Unique identifier |
user_id | Owner |
idempotency_key | Client-provided UUID |
operation, parameters | What to do |
status | Current state |
total, completed, failed | Progress counters |
created_at, updated_at, expires_at | Lifecycle timestamps |
Enforce a unique constraint on (user_id, idempotency_key) to prevent duplicate job creation.
tasks table (one row per file, sharded by job_id):
| Column | Purpose |
|---|---|
job_id, file_id (composite PK) | Task identifier |
status | pending, running, succeeded, failed |
attempt_count | Retry tracking |
lease_owner, lease_expires_at | Worker coordination |
result_blob_key, error_code | Outcome (large outputs stored externally) |
Use a strongly consistent database (sharded PostgreSQL, MySQL, or Spanner) for atomic conditional updates.
Architecture
Client
│
└─► Load Balancer
│
└─► API Servers (stateless)
│
├─► Jobs/Tasks DB (sharded)
│
└─► Task Queue (Kafka / SQS / RabbitMQ)
│
└─► Worker Fleet (auto-scaled)
│
├─► Object Storage (read files)
└─► Result Blob Store (write outputs)
Background: Lease Reaper (reschedules expired tasks)
Expiration Sweeper (archives old jobs)
Request flow
Job submission:
- Validate the request and check file ownership
- Open a database transaction:
- Insert the job row (or return existing if idempotency key matches)
- Insert task rows for each file
- Write messages to an outbox table
- Commit transaction and return
202 Accepted - A separate outbox relay reads the outbox and publishes task messages to the queue
This transactional outbox pattern avoids the dual-write problem where the DB commit succeeds but queue publish fails.
Worker execution:
- Pull a message from the queue
- Attempt to claim the task with a conditional update:
UPDATE tasks SET status = 'running', lease_owner = 'worker-7', lease_expires_at = now() + interval '3 minutes', attempt_count = attempt_count + 1 WHERE job_id = ? AND file_id = ? AND (status = 'pending' OR lease_expires_at < now()) - If the update succeeds (1 row affected), proceed; otherwise skip (another worker claimed it)
- Extend the lease periodically via heartbeat while working
- Fetch file bytes from object storage
- Perform the operation and write output to blob storage using a deterministic key:
{job_id}/{file_id} - Update the task to
succeededorfailed, increment job counters, ack the message - If this was the last task (
completed + failed == total), transition the job to a terminal state and optionally send a webhook
Handling failures and retries
Worker crashes: If a worker dies, its message becomes visible again after the queue's visibility timeout, and its lease expires. Another worker can claim the task. Cap retries at ~3 attempts, then move the task to a dead-letter queue and mark it failed.
Idempotency: The Idempotency-Key ensures that if a client retries the POST, it gets back the existing job. File operations should be idempotent (writing to the same blob key is safe).
Partial failure: Each file outcome is tracked independently. The job completes even if some files fail, giving clients full visibility.
Lease expiration: A background reaper periodically scans for tasks with expired leases and re-enqueues them.
Job expiration: Archive completed jobs after 30 days to control storage costs.
Scalability considerations
- API servers: Stateless, scale horizontally behind the load balancer
- Workers: Auto-scale based on queue depth and CPU utilization. Use separate worker pools per operation type if resource needs differ
- Database: Shard by
job_id. Hot spots on status checks can be mitigated with read replicas or a cache layer (Redis) for recent job status - Queue: Partition by
job_idto maintain ordering within a job - Bottleneck: If workers are I/O-bound fetching files, add caching or edge distribution. If CPU-bound, add more worker nodes.
Observability
Expose metrics:
- Job submission rate, latency, idempotent collision rate
- Queue depth per operation type
- Worker utilization, task success/failure rates, P99 task duration
- Lease expiration and retry counts
Log job state transitions and task failures with context for debugging.
Common mistakes
- Not addressing idempotency: Clients will retry; duplicate jobs waste resources and confuse users.
- Dual writes: Writing to the DB and then publishing to the queue separately creates a race. Use an outbox or a transactional queue.
- Coarse error handling: Failing the entire job because one file is corrupt loses information. Track per-file outcomes.
- No lease mechanism: Without leases, crashed workers leave tasks stuck forever.
- Unbounded retries: Poison messages can loop indefinitely. Cap retries and use a DLQ.
Extensions for further discussion
- Webhooks: Allow clients to register a callback URL to receive notifications when jobs complete
- Priority queues: Support high-priority jobs for premium users
- Cost optimization: Compress task rows, use cheaper storage tiers for archived results
- Multi-region: Replicate jobs DB and route work to the nearest region for lower latency