KatInterview

Design a Resilient In-Memory Task Queue with Worker Failure Handling

Data Structure DesignModel answer
MediumModel answerData Structure Designdesign-dsstacks-queuesconcurrency

Last 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:

  1. Job Lifecycle Management: Producers can enqueue new work units, and worker threads can request available work.
  2. 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.
  3. 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.
  4. 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.
  5. 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 to worker_id and 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.