KatInterview

State-Driven Job Scheduler with DLQ and Dependencies

Data Structure DesignAuto-graded · 18 test cases
HardAuto-gradedData Structure Designdesign-dsheaps-sortingtrees-graphs

Last updated

Simulate an event-driven task queue handling execution states, lease timeouts, retry budgets, dependencies, and dead-letter cascading.

Build a stateful in-memory task queue system that processes tasks with time-based reservation leases, retry handling, failure dead-letter queues (DLQ), and prerequisite dependencies.

The queue maintains an internal continuous clock starting at 0.0. It receives a sequence of operations executed one after another. Before every single operation is processed, the system automatically checks for and processes all expired reservation timers up to the current simulated time.

Job States

Each enqueued job exists in exactly one of the following five states:

  • ready: Ready to be claimed by a worker via reserve.
  • blocked: Waiting on one or more unfinished dependency jobs to reach state passed.
  • reserved: Active lease held by a worker.
  • passed: Successfully completed.
  • dlq: Sent to the Dead-Letter Queue due to failure or a failed prerequisite.

Operations and Behavior

  1. enqueue: Arguments [job_id, timeout, max_retry] or [job_id, timeout, max_retry, depends_on]

    • job_id (str): Unique job identifier.
    • timeout (int or float): Duration (in seconds) of each reservation lease.
    • max_retry (int): Maximum number of retry attempts allowed after failures/timeouts.
    • depends_on (list[str], optional): List of prerequisite job IDs. Defaults to [] if omitted.
    • Validation: Fails (returns False) if job_id already exists, or if any dependency in depends_on has not been previously enqueued.
    • State assignment:
      • If any dependency in depends_on is currently in state dlq, the new job immediately transitions to dlq (and transitively dead-letters any waiting dependents).
      • Otherwise, if all dependencies in depends_on are currently in state passed (or depends_on is empty), the job starts in state ready.
      • Otherwise (some dependencies are not yet passed), the job starts in state blocked.
    • Returns True if successfully enqueued.
  2. reserve: Arguments [job_id]

    • Can only be claimed if job_id exists and its current state is ready.
    • Changes state to reserved, increments its reservation version counter, and schedules a lease expiration timer at current_time + timeout.
    • Returns True if reserved successfully, or False if the job does not exist or is not ready.
  3. pass (or ack): Arguments [job_id]

    • Can only be called on a job currently in state reserved.
    • Transitions job state to passed.
    • Decrements the remaining dependency count of any blocked child jobs that depend on job_id. Any dependent child whose remaining dependency count reaches 0 transitions to ready.
    • Returns True if successful, or False if the job does not exist or is not reserved.
  4. fail: Arguments [job_id]

    • Can only be called on a job currently in state reserved.
    • Increments the job's retries count by 1.
    • If retries > max_retry, the job transitions to state dlq and recursively forces all dependent downstream jobs (which depend directly or indirectly on job_id) to transition to dlq.
    • Otherwise (retries $\le$ max_retry), the job reverts to state ready.
    • Returns True if successful, or False if the job does not exist or is not reserved.
  5. advance: Arguments [delta_time]

    • Increases internal simulated time by delta_time (int or float).
    • Immediately checks for and processes all reservation expirations up to the updated time.
    • Returns None.
  6. get_dlq: Arguments []

    • Returns a list[str] containing the job_ids of all jobs currently in state dlq, in order of their initial enqueuing.

Timer Expiration Logic

  • At every step (including inside advance and right before evaluating any operation), any reservation timer with deadline <= current_time is evaluated:
    • If the timer corresponds to the job's current active reservation version (meaning it is still reserved), the job's retries count increments by 1.
    • If retries > max_retry, the job enters state dlq (cascading transitively to all dependent downstream jobs).
    • Otherwise, it reverts to state ready.
  • Outdated timer entries (from jobs that were explicitly passed, failed, or re-reserved before the timer fired) are ignored when popped.

Constraints

  • Operations are provided as operations: List[str] and matching arguments: List[List].
  • Output is a List of individual operation return values (True, False, None, or List[str]).
  • Job IDs are non-empty strings.
  • Time values and timeouts are non-negative real numbers.

Examples

Example 1

Input: process_queue(['enqueue', 'reserve', 'fail', 'reserve', 'pass', 'get_dlq'], [['a', 5, 1], ['a'], ['a'], ['a'], ['a'], []])

Output: [True, True, True, True, True, []]

Example 2

Input: process_queue(['enqueue', 'enqueue', 'reserve', 'pass', 'reserve', 'get_dlq'], [['parent', 10, 0], ['child', 10, 1, ['parent']], ['child'], ['parent'], ['child'], []])

Output: [True, True, False, False, False, []]

Example 3

Input: process_queue(['enqueue', 'reserve', 'advance', 'get_dlq'], [['job', 2, 0], ['job'], [2], []])

Output: [True, True, None, ['job']]

Hints

Hint 1

Store job metadata in a dictionary containing current state, retry count, max retries, lease duration, dependency counts, and an integer reservation version.

Hint 2

Use a min-heap for lease timeouts sorted by `deadline_time`. Store the reservation version in each heap element to perform lazy deletion of stale timers.

Hint 3

When a job transitions to `dlq`, perform a BFS or DFS traversal over the dependency graph to transitively transition all non-passed, non-dlq dependent jobs to `dlq` as well.

Hint 4

Remember to trigger the expiration handler both during `advance` calls and at the very beginning of processing every operation.