Lease-Based Task Dispatch for a Pool of Human Reviewers
System DesignModel answerLast updated
Design a platform that routes skill-specific manual tasks to human operators with leases, heartbeats, fair prioritization, and safe automatic reassignment after failures.
Problem
Your infrastructure organization relies on people for jobs that cannot be automated, such as hands-on triage of suspect GPU servers, unusual hardware validation, and manual policy checks. Design a service that hands these jobs to the right person at the right time and tracks each job until it finishes.
The service must keep working through operator disconnections, expired claims, and hard completion deadlines.
Functional requirements
- Submission and priority: Upstream systems submit tasks that declare the skills needed, a priority, and a maximum time to completion (SLA).
- Matching: Operators sign in, state whether they are available, and receive only tasks they are qualified for. You may choose push, pull, or a hybrid.
- States and leases: Each task moves through
QUEUED,ASSIGNED,IN_PROGRESS,COMPLETED,FAILED, andEXPIRED. An assigned task is held under a lease that the operator must keep renewing with heartbeats. - Recovery: If an operator goes offline or fails to finish before the lease runs out, the task must return to the queue automatically and without corrupting its state.
- Auditing and metrics: Keep a full history of state changes, time until assignment, time spent actively working, and per-operator performance.
Non-functional requirements
- Reliability: At-least-once execution. A network partition or crash must never cause a task to be lost.
- Fairness: Low-priority tasks must not wait forever, and work should spread evenly across operators who are eligible.
- Consistency: Two operators must never end up legitimately working the same task at once.
Scale
- 10,000 operators online at the same time, worldwide.
- 1,000,000 new tasks per day, peaking at 100 tasks per second.
- Task durations between 30 seconds and 30 minutes.
- Assignment or pull latency must stay below 200 ms at p99.
What to cover
- Overall architecture: ingestion, queueing and scheduling, operator-facing dispatch, and the state store.
- Data model and the task state machine.
- The assignment approach: push versus pull, priority handling, and skill-based routing.
- Lease renewal, detection of unresponsive operators, and safe reassignment.
State your assumptions, show rough capacity math, and discuss trade-offs and failure modes.
Hints
Hint 1
Convert the numbers into rates first (tasks per second, completions per second, heartbeats per second). If the load turns out modest, the real difficulty is correctness and fairness rather than raw throughput.
Hint 2
Make every state change a conditional write guarded by the expected state and a lease epoch (fencing token), and write the audit record in the same transaction. This stops two operators from winning the same task and stops stale workers from overwriting newer results.
Hint 3
Pull-based assignment fits people well because they request work only when free. For fairness, combine a priority weight with an aging term that grows with wait time, plus a deadline-slack term, so low-priority work eventually surfaces.
Hint 4
A background reaper that scans an index on lease expiry can requeue abandoned tasks. Consider how a returning operator who missed the expiry is rejected, and what happens to tasks that exceed their SLA or retry limit.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
1. Capacity math
| Quantity | Estimate |
|---|---|
| Ingestion | 1M/day is about 12/s on average, 100/s at peak |
| Completions | 10k operators with roughly 5 min tasks is about 35/s, so pulls run at 35 to 100/s |
| Heartbeats | One per operator every 15 s is about 700 small writes/s |
| Storage | About 2 KB per task plus around 6 audit rows of 200 B each, roughly 3 GB/day or 1 TB/year |
The throughput is small. The hard parts are no duplicate ownership, no lost tasks, fairness, and p99 under 200 ms. A single well-indexed relational primary handles this; sharding by task id is a later option.
Clarifying questions: can an operator hold several tasks (assume a configurable cap, default 1)? What happens when the SLA passes (assume EXPIRED plus escalation)? Are tasks safe to repeat (at-least-once means occasional duplicates, so ask for idempotent work or a result-dedup key)?
2. API sketch
POST /taskswith skills, priority, SLA, payload, and anidempotency_keyso producers can retry safely.POST /operators/{id}/sessionregisters skills and concurrency.GET /operators/{id}/next?wait=20sis a long-poll returning a task,lease_id,epoch, and expiry.POST /leases/{id}/heartbeat,/start,/complete,/fail, each carrying the epoch.- A WebSocket or SSE channel per operator for control messages (revocation, wake-up).
3. Data model
- Task: id, type, canonical skill bitmask, base priority, SLA deadline, enqueue time, state, attempts, version, lease epoch, lease expiry, current operator, payload.
- Operator: id, skill bitmask, status, active count, max concurrency, last assigned time, last seen time.
- Assignment: one row per attempt with lease id, task, operator, epoch, grant/start/end times, and outcome. This doubles as performance history.
- TaskEvent: append-only record of from/to state, actor, epoch, timestamp, reason.
State machine
QUEUED -> ASSIGNED -> IN_PROGRESS -> COMPLETED. A lease expiry, retryable failure, or revocation sends the task back to QUEUED with attempts incremented. A failure beyond the retry limit goes to FAILED. Any non-terminal task past its SLA goes to EXPIRED and triggers escalation.
Two rules keep this safe:
- Each transition is a conditional update (
WHERE state = ? AND lease_epoch = ?). - The audit event is written in the same transaction as the transition.
4. Architecture
- Ingestion service (stateless): validates, dedupes on the idempotency key, inserts as
QUEUED. - State store (PostgreSQL): the source of truth. A partial index on queued tasks by skill signature and priority makes queue scans cheap; another on lease expiry for active tasks serves the reaper. One primary with synchronous replication is sufficient.
- Dispatch tier (stateless): holds operator long-polls and keeps a cached view of queue heads per skill signature (fed by change data capture). The cache is advisory only.
- Lease reaper: a leader-elected job that requeues expired leases and expires tasks past their SLA.
- Event pipeline: change data capture into a log and warehouse for time-to-assign, handle time, and operator dashboards.
- Notification channel: pushes revocations and "work available" wake-ups.
5. Assignment
Pull as the primary model. People are unpredictable and task length varies 60x. With pull, an operator asks only when free, so backpressure is natural, fast workers take more, and the server need not track exact capacity or unacknowledged deliveries. Keep push only for control messages.
Skill routing. Bucket tasks into queues by skill signature (a few hundred distinct values). An operator is eligible for a queue if they hold every required skill (task_sig & ~op_skills == 0). Cache the eligible queue list at session start.
Priority with anti-starvation. Score each task:
score = W[priority] + a * wait_seconds + b * max(0, 1 - slack / sla)
The aging term bounds starvation because enough waiting lets low-priority work overtake new high-priority work. The slack term lifts near-deadline tasks. Optionally add weighted fair queueing so each tier gets a minimum share.
Pull path (target under 20 ms server time):
- Inspect the heads of eligible queues and pick the best score.
- Claim atomically:
UPDATE tasks SET state='ASSIGNED', operator_id=$op, lease_epoch=lease_epoch+1, lease_expires_at=now()+60s, attempts=attempts+1 WHERE id=$t AND state='QUEUED'(orSELECT ... FOR UPDATE SKIP LOCKED). - If zero rows changed, another dispatcher won; try the next candidate. Only one compare-and-set can succeed.
- If nothing is available, hold the long-poll until a wake-up arrives.
Fairness among operators: enforce max_concurrency, and when several operators wait on one queue, serve the one with the oldest last_assigned_at.
6. Leases and heartbeats
- Timing: 60 s TTL, heartbeats every 15 s, so an operator survives three missed beats. Tune against how long a flaky network typically stalls.
- Fencing: each grant bumps
lease_epoch. Every heartbeat, start, complete, and fail carries the epoch and is applied only if it matches. A zombie operator returning after reassignment is rejected with a conflict and told to discard its work. - Reaper: every few seconds, find tasks in
ASSIGNEDorIN_PROGRESSwith expired leases, and conditionally move them toQUEUED(incrementing attempts) orFAILEDwhen attempts hit the cap. Because it is a conditional update, a heartbeat racing the reaper has exactly one winner. - Leader election: a lock or lease in the database ensures one active reaper. Even two reapers would be harmless thanks to conditional writes.
- Longer tasks: since tasks can take 30 minutes, the lease is renewed continuously rather than set to the full duration, which keeps failure detection fast.
- Requeue priority: reclaimed tasks keep their original enqueue time so aging favors them, avoiding a penalty for someone else's failure.
7. Failure modes and trade-offs
- Dispatcher crash: stateless, operators reconnect. The cache rebuilds from the store.
- Database failover: synchronous replication means no acknowledged claim is lost. Clients retry with the same epoch idempotently.
- Partition: an isolated operator loses its lease; its late result is fenced out. This gives at-least-once semantics, so side effects need idempotency keys.
- Poison tasks: cap attempts and send to a manual review state rather than looping forever.
- Cache staleness: harmless, because the conditional claim is the authority. The cost is an occasional wasted attempt.
- Why not a pure message broker: brokers lack rich skill and priority matching, per-task state, and audit queries. A database-backed queue at this scale is simpler and more correct.
8. Observability
Emit metrics from the event stream: time-to-assign by priority, handling time, lease expiry rate, retry rate, SLA breach count, queue depth per skill signature, and per-operator throughput and failure rate. Alert on aging queue heads and rising expiry rates.
Common mistakes
- Relying on the in-memory cache for ownership instead of a conditional write.
- Omitting fencing, so a returning zombie overwrites a newer result.
- Using strict priority with no aging, which starves low-priority work.
- Setting lease TTL equal to the task duration, which delays failure detection.
- Writing audit events outside the transition transaction, causing gaps.