Building an Asynchronous Job Platform for LLM Requests
System DesignModel answerLast updated
Design an asynchronous backend that accepts LLM requests, queues and routes them fairly, runs them reliably, and returns results, with cost, security and SLA controls.
Problem
Your company wants to offer an asynchronous service for running large language model requests. A client sends a request to an HTTP API, immediately receives a job handle, and later retrieves the outcome either by polling or through a callback to a URL they supply.
Design the backend for this service.
What to cover
- API surface: endpoints, request and response shapes, and the job lifecycle states.
- Queueing and priorities: how jobs are enqueued, how tiers (for example interactive, standard, batch) are scheduled, and how you keep one heavy tenant from starving the others.
- Workers and model routing: how worker pools are organized and how a request is mapped to a model pool.
- Prompt versioning: how templates are stored, changed and referenced so that in-flight jobs stay stable.
- Idempotency: how client retries and duplicate queue deliveries avoid duplicate effects.
- Failure handling: retry policy, error classification, dead-letter queues and redrive.
- Result storage: where outputs live, how long they are kept, and how they are protected.
- Observability: metrics, logs, traces and alerts you would put in place.
- Cross-cutting concerns: scaling, cost control, rate limiting, PII and security, and SLAs.
Follow-up
Extend the design to support streaming partial output to the client and cancellation of jobs that are queued or already running.
Expectations
State your assumptions and rough scale numbers, justify the main trade-offs, point out edge cases, and explain how you would verify that the system meets its goals.
Hints
Hint 1
Size the system in tokens rather than requests: a few very long prompts can consume as much GPU time as thousands of short ones, so admission control and autoscaling should be token-aware.
Hint 2
Separate the two kinds of duplication: client-side retries are handled by an idempotency key tied to a request hash, while duplicate queue deliveries are handled by leases plus a conditional, attempt-numbered commit of the result.
Hint 3
Resolve prompt aliases to an immutable version at submit time and store the concrete version on the job, so promotions and rollbacks never alter work already accepted.
Hint 4
For the follow-up, think about where the stream is produced versus where it is served, how a client reconnects mid-stream, and how a cancel signal reaches a worker that is already generating tokens.
Model answer
Hard Try it yourself first — then compare your approach, complexity and edge cases.
1. Requirements and scale
Functional: submit a job (raw messages or template plus variables), receive a job ID immediately, fetch results by polling or callback, support several models, priority tiers, prompt versions, retries and cancellation.
Non-functional:
- No lost jobs and no duplicate side effects.
- Tenant isolation, cost control, PII protection.
- Tiered SLAs: interactive p99 queue wait of about 2 s, standard within minutes, batch within 24 h at a discount.
Assumed scale: 10M jobs/day is about 115 jobs/s on average and about 600/s at peak. At roughly 2K input and 500 output tokens per job, that is about 25B tokens/day. Payloads of about 10 KB give about 100 GB/day, or about 3 TB at 30-day retention. The bottleneck is GPU capacity, so plan in tokens, not requests.
2. API and lifecycle
POST /v1/jobswithIdempotency-Keyheader. Body: model or routing policy, messages or{template_id, version|alias, variables},max_tokens,priority, optionalcallback_url,deadline. Returns202 {job_id, status}.GET /v1/jobs/{id}returns status, result, usage, error and attempt count.POST /v1/jobs/{id}/cancelis idempotent.POST /v1/batchesaccepts bulk JSONL.GET /v1/jobs/{id}/streamserves server-sent events (follow-up).
States: QUEUED → RUNNING → SUCCEEDED | FAILED | CANCELLED; RUNNING → RETRY_WAIT → QUEUED for retryable failures; DEAD_LETTERED once retries are exhausted.
3. Architecture
- Gateway: authentication, per-tenant limits on both requests/s and tokens/min, payload validation.
- Job service: checks idempotency, resolves the prompt version, estimates cost, writes the job row, and publishes to the queue through a transactional outbox so the database and queue cannot diverge.
- Queues: partitioned by
(model_pool, priority). - Dispatcher: weighted fair scheduling that admits work according to free GPU token capacity.
- Worker pools: one per model class, pulling under a lease and calling inference servers with continuous batching and prefix caching.
- Result writer: stores output, then commits status with a fenced conditional update.
- Notifier: HMAC-signed webhooks with backoff and its own DLQ.
- Observability and DLQ tooling.
Data: a jobs table (unique on tenant_id, idempotency_key; fields for status, attempt, lease, deadline, prompt version, result reference, usage), immutable prompt_versions, a results store (inline when small, encrypted object storage with per-tenant TTL when large) and an append-only usage_ledger.
4. Deep dives
Idempotency. On submit, the same key and same request hash returns the existing job; the same key with a different hash returns 409. Keep keys at least 24 h. On execution, the queue is at-least-once, so correctness comes from leases and fencing: each attempt has an increasing number and the commit is UPDATE ... WHERE job_id=? AND attempt=? AND status='RUNNING'. A stale worker cannot overwrite a newer attempt. Because generation is non-deterministic, the guarantee is one committed result, not one execution; state the billing policy for wasted attempts.
Prioritization and fairness. Separate queues per tier with weighted draining (for example 70/25/5, batch also using idle capacity). Within a tier use deficit round robin measured in tokens across tenants, plus aging and earliest-deadline-first ordering. Batch is preemptible when interactive load spikes.
Model routing. A policy engine uses requested model, context length, tenant tier and pool health. Fall back to a replica of the same pinned model in another region before anything else, and never switch model silently unless the request opts in. Log the decision on the job.
Prompt versioning. Templates are immutable and content-hashed; aliases like prod and canary are mutable pointers resolved at submit time. This gives safe A/B tests, rollbacks and audits.
Retries and DLQ. Retryable: worker crash, lease timeout, GPU OOM, upstream 5xx/429. Non-retryable: validation errors, context too long, policy refusal, budget exceeded. Use exponential backoff with jitter, 3 to 5 attempts, bounded by the deadline. Exhausted jobs go to the DLQ with full error history, with alerting and an idempotent bulk redrive. Quarantine poison-pill jobs that repeatedly crash workers.
Scaling and cost. Stateless services scale horizontally; shard the database and partition queues. Autoscale GPU pools on queued tokens and predicted drain time, not CPU. Control cost with per-tenant token budgets enforced at admission, routing to smaller models where allowed, prefix caching, batch discounts for off-peak work, and max_tokens caps.
Rate limiting. Token-bucket limits per tenant on both requests and estimated tokens, with a concurrency cap. Return 429 with Retry-After.
Security and PII. TLS everywhere, encryption at rest with per-tenant keys, short retention TTLs, optional PII redaction before logging, no prompt bodies in logs or metrics, strict tenant scoping on every read, SSRF protection and allow-listing for callback URLs, and audit logs.
Observability. Track queue depth and age per pool and tier, token throughput, time-to-first-token, end-to-end latency, error rate by class, retry and DLQ rates, lease expirations, cost per tenant and SLA attainment. Propagate a trace ID from API to worker to webhook. Alert on SLA burn rate and DLQ growth.
5. Follow-up: streaming and cancellation
Streaming. The worker publishes token deltas with sequence numbers to a short-lived stream (for example a per-job Redis stream or pub/sub channel). A stream gateway serves them over SSE. Clients reconnect with Last-Event-ID and replay from the buffer. The final, complete result is still committed through the normal fenced path, so streaming is a best-effort view and the stored result is authoritative. If a retry occurs mid-stream, emit a reset event so the client discards partial text.
Cancellation. Cancel on a QUEUED job is a conditional state change to CANCELLED; the dispatcher skips it. For a RUNNING job, set a cancel flag and notify the worker (pub/sub or heartbeat response). The worker aborts generation, which frees the GPU slot, and commits CANCELLED with partial usage. Race conditions are resolved by the conditional update: whichever of "succeeded" or "cancelled" commits first wins, and the other is a no-op. Bill only for tokens actually generated.
6. Validation and common mistakes
Validate with load tests that replay peak traffic, chaos tests that kill workers mid-job to confirm no duplicate commits, and fairness tests with one dominant tenant.
Common mistakes: sizing by request count instead of tokens, claiming exactly-once execution, resolving prompt aliases at run time, retrying non-retryable errors, using one shared FIFO queue, and logging raw prompts.