Full answer
Requirements
Functional:
- Enqueue a task (type, payload) to a named queue, optionally delayed ("send reminder in 2 hours") or with a priority.
- Workers fetch, process and acknowledge tasks; failed tasks retry with backoff.
- Dead-letter queue (DLQ) for tasks that keep failing; operators can inspect and replay them.
- Visibility into queue depth, age of the oldest task and failure rates.
Non-functional:
- Durable: an accepted task is never lost.
- At-least-once execution; duplicates are rare but possible.
- Scales horizontally for bursts (for example, end-of-term report generation).
Capacity estimates
Assumptions: 100M tasks per day; bursts up to 10,000 enqueues per second; average payload 2 KB; completed tasks kept 7 days for debugging; average processing time 500 ms.
- Average rate: 100M / 86,400 = about 1,160 per second; bursts are about 9x the average, so the queue must buffer them.
- Storage: 100M x 2 KB = 200 GB per day; 7 days = 1.4 TB.
- Workers: by Little's Law, sustaining 1,160 tasks per second at 0.5 s each needs about 580 tasks running at once; at 10 concurrent tasks per worker process, about 58 workers on average. During a burst the backlog grows and drains as workers autoscale.
API
enqueue(queue="reports", type="build_report_card", payload={...},
delay_s=0, priority=5, idempotency_key="term2-student-77") -> task_id
lease(queue="reports", max_tasks=10, visibility_timeout_s=60) -> [{task_id, lease_token, payload, attempt}]
ack(task_id, lease_token)
nack(task_id, lease_token, retry_after_s) # explicit failure
extend(task_id, lease_token, visibility_timeout_s) # long-running task heartbeat
Data model
tasks: task_id, queue, partition, state (ready, leased, done, dead), priority, available_at, lease_owner, lease_until, attempts, max_attempts, payload, idempotency_key (unique per queue), last_error.
Index on (queue, partition, state, priority, available_at) so the next ready task is an index seek.
High-level design
flowchart LR
P[Producers] --> API[Queue API]
API --> ST[(Partitioned task store)]
W1[Worker pool A] -->|lease / ack| API
W2[Worker pool B] -->|lease / ack| API
REAP[Lease reaper] --> ST
API --> DLQ[(Dead-letter queue)]
API --> MET[Metrics: depth, oldest age, failures]Leasing safely
With a relational store, a lease is one statement (PostgreSQL syntax, shown for illustration, not run here):
UPDATE tasks
SET state = 'leased', lease_owner = $1,
lease_until = now() + interval '60 seconds', attempts = attempts + 1
WHERE task_id IN (
SELECT task_id FROM tasks
WHERE queue = $2 AND state = 'ready' AND available_at <= now()
ORDER BY priority DESC, available_at
LIMIT 10
FOR UPDATE SKIP LOCKED
)
RETURNING task_id, payload, attempts;SKIP LOCKED lets many workers lease concurrently without blocking on each other's rows. A reaper sets expired leases (lease_until < now()) back to ready. Ack checks the lease_token so a slow worker whose lease already expired cannot acknowledge a task that another worker now holds.
For higher throughput than one database can give, split each queue into partitions on different shards (workers lease from partitions in rotation), or build on a broker such as SQS, RabbitMQ or Kafka and keep only scheduling and DLQ logic in your own service.
Retries, delays and priorities
- Retry: on failure set
available_at = now() + backoff(attempt)with exponential backoff and jitter; aftermax_attempts, state becomesdeadand the task is copied to the DLQ with its last error. - Delay: just a future
available_at. For very long delays, a separate timer store (time-bucketed) moves tasks into the ready set when due. - Priority: ordering by priority within a queue, or separate queues per priority with workers weighted toward high priority so low priority is not starved forever.
Bottlenecks and trade-offs
- Poison tasks that crash workers are caught by the attempt limit.
- Visibility timeout too short causes duplicate processing of slow tasks; too long delays recovery after a worker crash. Use
extendheartbeats for long tasks. - Exactly-once is not offered; use idempotency keys and idempotent handlers (for example, "generate report card for term 2 if not already generated").
- Strict FIFO across many workers conflicts with throughput; offer ordering only within a partition key when needed.
- Database-backed vs broker-backed: a database queue is transactional with your business data (enqueue in the same transaction as the change) but limited in throughput; a broker scales further but needs the outbox pattern for the same guarantee.
By level
Fresher: Explain producers, a queue and workers, why tasks are acknowledged after processing, and why failed tasks are retried. A fresher should explain what a dead-letter queue is for.
Mid: Design leasing with visibility timeouts, retries with backoff, DLQ, delays and priorities, and estimate worker count and storage. Expect Little's Law to size the worker pool.
Senior: Address partitioning for throughput, fairness across tenants, transactional enqueue with the outbox, observability and autoscaling on queue age, and choosing between database and broker backends. Expect a fairness plan so one tenant cannot starve others.
Key points
- Lease with visibility timeout; expired leases become visible again
- At-least-once delivery, so handlers must be idempotent
- Retries with exponential backoff and jitter, then a dead-letter queue
- Delays via available_at; priorities via ordering or separate queues
- Little's Law sizes the worker pool
Common mistakes
- Deleting tasks on fetch, which loses them if the worker crashes
- Letting an expired lease holder acknowledge the task
- Retrying forever without a DLQ
- Promising exactly-once execution
Follow-ups
- How would you guarantee a task is enqueued only if the database transaction commits?
- How would you support cron-style recurring tasks?
- How do you keep one tenant from starving others?
Tips
- Explain the lease and visibility timeout clearly
- Size workers with Little's Law
- Mention idempotency as the consumer's responsibility
Evaluation rubric
- Requirements include durability, retries, delays and observability
- Correct throughput, storage and worker math
- Correct leasing mechanics and failure handling
- Trade-offs on timeouts, ordering and storage choice