Design a Resilient In-Memory Task Queue with Worker Failure Handling
Data Structure DesignModel answerLast updated
Build a thread-safe, in-process job queue that handles worker crashes, lease timeouts, late reports, and retry bounds using deterministic testing mechanics.
Construct an in-process, thread-safe work queue designed to guarantee that no submitted job is lost when processing workers crash, hang, or emit errors.
Your queue implementation must satisfy the following requirements:
- Job Lifecycle Management: Producers can enqueue new work units, and worker threads can request available work.
- Lease Expiration: When a job is dispatched to a worker, it receives a fixed time window (
lease_duration) to complete execution. If the worker fails to complete the job within this window, the system must treat the job as abandoned and make it eligible for reprocessing. - Bounded Retries: If a job fails explicitly or times out, it should be re-enqueued up to a defined maximum attempt threshold (
max_attempts). Once this limit is reached, the job must transition to a dead-letter state rather than returning to the active queue. - Stale Signal Rejection: If a worker suffers a delay and its lease expires, any subsequent attempt by that worker to complete or report failure on the original job must be ignored to prevent race conditions and duplicate completion accounting.
- Deterministic Time Testing: Internal time checks (such as lease expiration evaluations) must accept a configurable clock interface to allow unit tests to verify time-sensitive scenarios without relying on actual sleep calls.
Expected API Interface
Implement a class ResilientWorkQueue (or language equivalent) providing:
submit(job_id, payload): Enqueues a new job item.claim_next(worker_id): Dispatches the next available job toworker_idand registers an active lease.complete(job_id, worker_id): Marks a job as successfully finished by the assigned worker.report_failure(job_id, worker_id): Explicitly signals that processing failed for a job.sweep_expired_leases(): Checks active leases and reclaims timed-out jobs back to the ready pool or dead-letter destination.
Detail your choices around synchronization, algorithm complexity, and task ordering guarantees.
Hints
Hint 1
Define explicit state transitions (e.g., READY, IN_FLIGHT, SUCCEEDED, DEAD_LETTER) to prevent invalid state operations.
Hint 2
Maintain a min-heap keyed by lease expiration timestamp so that reclaiming timed-out jobs takes sub-linear time instead of scanning every active job.
Hint 3
Track a unique token or current worker assignment per lease to safely reject late completions from workers whose leases have already expired.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Architectural Overview
To build a reliable in-memory task execution queue, we map each job through a well-defined state machine:
- READY: Eligible to be pulled by an available worker.
- IN_FLIGHT: Claimed by a worker with an active time lease.
- SUCCEEDED: Terminal state reached when processed successfully within the lease window.
- DEAD_LETTER: Terminal state reached after exceeding max retry attempts due to failures or timeouts.
┌───────────────┐
│ READY │◄──────────────┐
└───────┬───────┘ │
│ claim_next │ lease timeout / failure
▼ │ (attempts < max_attempts)
┌───────────────┐ │
┌────►│ IN_FLIGHT ├───────────────┘
│ └───────┬───────┘
│ │ complete
│ ├─────────────────────────► ┌───────────┐
│ │ │ SUCCEEDED │
│ │ lease timeout / failure └───────────┘
│ │ (attempts >= max_attempts)
│ ▼
│ ┌───────────────┐
└─────┤ DEAD_LETTER │
└───────────────┘
Core Data Structures:
- Job Registry: A dictionary mapping
job_idto its state, payload, attempt count, assigned worker ID, and lease metadata. - Ready FIFO Queue: A standard double-ended queue holding
job_ids ready for worker acquisition. - Expiration Priority Queue: A min-heap storing tuples of
(expiration_timestamp, job_id, lease_generation). This allows $O(1)$ inspection of the oldest unexpired lease. - Clock Abstraction: A callable returning the current timestamp (seconds), enabling deterministic testing without relying on
time.sleep().
Python Reference Implementation
import heapq
from collections import deque
from enum import Enum, auto
from threading import Lock
from typing import Optional, Dict, Any, Tuple
class JobState(Enum):
READY = auto()
IN_FLIGHT = auto()
SUCCEEDED = auto()
DEAD_LETTER = auto()
class JobRecord:
def __init__(self, job_id: str, payload: Any):
self.job_id = job_id
self.payload = payload
self.state = JobState.READY
self.attempts = 0
self.current_worker: Optional[str] = None
self.lease_generation: int = 0
self.expires_at: float = 0.0
class ResilientWorkQueue:
def __init__(self, lease_duration: float, max_attempts: int, clock_fn=None):
self.lease_duration = lease_duration
self.max_attempts = max_attempts
self.get_time = clock_fn if clock_fn else (lambda: __import__('time').time())
self._lock = Lock()
self._jobs: Dict[str, JobRecord] = {}
self._ready_queue = deque()
self._lease_heap = []
self._dead_letter_ids = set()
def submit(self, job_id: str, payload: Any) -> bool:
with self._lock:
if job_id in self._jobs:
return False # Ignore duplicate submissions
job = JobRecord(job_id, payload)
self._jobs[job_id] = job
self._ready_queue.append(job_id)
return True
def claim_next(self, worker_id: str) -> Optional[Tuple[str, Any]]:
with self._lock:
self._sweep_expired_leases_locked()
while self._ready_queue:
job_id = self._ready_queue.popleft()
job = self._jobs.get(job_id)
if not job or job.state != JobState.READY:
continue
now = self.get_time()
job.attempts += 1
job.state = JobState.IN_FLIGHT
job.current_worker = worker_id
job.lease_generation += 1
job.expires_at = now + self.lease_duration
heapq.heappush(
self._lease_heap,
(job.expires_at, job.job_id, job.lease_generation)
)
return (job.job_id, job.payload)
return None
def complete(self, job_id: str, worker_id: str) -> bool:
with self._lock:
job = self._jobs.get(job_id)
if not job:
return False
# Reject late completions or completions from unassigned workers
if job.state != JobState.IN_FLIGHT or job.current_worker != worker_id:
return False
job.state = JobState.SUCCEEDED
job.current_worker = None
return True
def report_failure(self, job_id: str, worker_id: str) -> bool:
with self._lock:
job = self._jobs.get(job_id)
if not job:
return False
if job.state != JobState.IN_FLIGHT or job.current_worker != worker_id:
return False
self._reclaim_or_deadletter_locked(job)
return True
def sweep_expired_leases(self) -> int:
with self._lock:
return self._sweep_expired_leases_locked()
def _sweep_expired_leases_locked(self) -> int:
now = self.get_time()
reclaimed_count = 0
while self._lease_heap:
exp_time, job_id, generation = self._lease_heap[0]
if exp_time > now:
break
heapq.heappop(self._lease_heap)
job = self._jobs.get(job_id)
# Check if lease generation matches active record
if (
job
and job.state == JobState.IN_FLIGHT
and job.lease_generation == generation
):
self._reclaim_or_deadletter_locked(job)
reclaimed_count += 1
return reclaimed_count
def _reclaim_or_deadletter_locked(self, job: JobRecord):
job.current_worker = None
if job.attempts >= self.max_attempts:
job.state = JobState.DEAD_LETTER
self._dead_letter_ids.add(job.job_id)
else:
job.state = JobState.READY
self._ready_queue.append(job.job_id)
Complexity Analysis
submit: $O(1)$ time complexity for key insertion and deque append.claim_next: $O(\log K)$ time where $K$ is the number of active leases, driven by pushing to the min-heap.complete/report_failure: $O(1)$ key lookup and field update.sweep_expired_leases: $O(M \log K)$ where $M$ is the number of expired items popped from the min-heap.- Space Complexity: $O(N)$ memory, where $N$ is total active and historical jobs managed.
Key Considerations & Edge Cases
- At-Least-Once Processing Guarantees: A delayed worker might execute a task while another worker picks up the reclaimed task. Applications must ensure idempotency at the business execution level.
- Generational Lease Tokens: Tracking
lease_generationprevents stale heap items from falsely failing tasks that have been reclaimed, re-leased, and updated with newer expirations. - Lock Scope & Concurrency: Using a coarse lock ensures atomic state checks across ready queues, lookup tables, and min-heaps, eliminating race conditions across worker threads.