State-Driven Job Scheduler with DLQ and Dependencies
Data Structure DesignAuto-graded · 18 test casesLast 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 viareserve.blocked: Waiting on one or more unfinished dependency jobs to reach statepassed.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
-
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) ifjob_idalready exists, or if any dependency independs_onhas not been previously enqueued. - State assignment:
- If any dependency in
depends_onis currently in statedlq, the new job immediately transitions todlq(and transitively dead-letters any waiting dependents). - Otherwise, if all dependencies in
depends_onare currently in statepassed(ordepends_onis empty), the job starts in stateready. - Otherwise (some dependencies are not yet
passed), the job starts in stateblocked.
- If any dependency in
- Returns
Trueif successfully enqueued.
-
reserve: Arguments[job_id]- Can only be claimed if
job_idexists and its current state isready. - Changes state to
reserved, increments its reservation version counter, and schedules a lease expiration timer atcurrent_time + timeout. - Returns
Trueif reserved successfully, orFalseif the job does not exist or is notready.
- Can only be claimed if
-
pass(orack): 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
blockedchild jobs that depend onjob_id. Any dependent child whose remaining dependency count reaches0transitions toready. - Returns
Trueif successful, orFalseif the job does not exist or is notreserved.
- Can only be called on a job currently in state
-
fail: Arguments[job_id]- Can only be called on a job currently in state
reserved. - Increments the job's
retriescount by1. - If
retries > max_retry, the job transitions to statedlqand recursively forces all dependent downstream jobs (which depend directly or indirectly onjob_id) to transition todlq. - Otherwise (retries $\le$
max_retry), the job reverts to stateready. - Returns
Trueif successful, orFalseif the job does not exist or is notreserved.
- Can only be called on a job currently in state
-
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.
- Increases internal simulated time by
-
get_dlq: Arguments[]- Returns a
list[str]containing thejob_ids of all jobs currently in statedlq, in order of their initial enqueuing.
- Returns a
Timer Expiration Logic
- At every step (including inside
advanceand right before evaluating any operation), any reservation timer withdeadline <= current_timeis evaluated:- If the timer corresponds to the job's current active reservation version (meaning it is still
reserved), the job'sretriescount increments by1. - If
retries > max_retry, the job enters statedlq(cascading transitively to all dependent downstream jobs). - Otherwise, it reverts to state
ready.
- If the timer corresponds to the job's current active reservation version (meaning it is still
- 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 matchingarguments: List[List]. - Output is a
Listof individual operation return values (True,False,None, orList[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.
Worked solution
Hard Try it yourself first — then compare your approach, complexity and edge cases.
Approach
This problem requires simulating an event-driven task scheduler with states (ready, blocked, reserved, passed, dlq), prerequisite dependencies, lease timeouts, and dead-letter cascading.
-
Job Tracking & Data Structures:
- We store job state and metadata in a dict
jobs[job_id], containingstate,timeout,max_retry,retries,version(reservation generation counter), andremaining(count of uncompleted dependencies). - An adjacency dictionary
waiting[parent_id]tracks downstream child job IDs waiting on each parent job. - A min-heap
timersstores tuple entries(deadline_time, sequence, job_id, reservation_version)for active reservation timeouts.
- We store job state and metadata in a dict
-
Timer Processing & Expiration:
- Expiration checks run before every operation processing step and during
advance. - When a timer entry pops from
timerswithdeadline <= current_time:- If the job is still
reservedand its current reservationversionmatches the popped tuple's version, the lease has timed out. retriesis incremented. Ifretries > max_retry, the job transitions todlqand triggers a cascading dead-letter traversal. Otherwise, it returns toready.- Stale timers (where job was already completed or failed early) are discarded seamlessly.
- If the job is still
- Expiration checks run before every operation processing step and during
-
Dependency and DLQ Cascading:
- When
pass/acksucceeds, we notify all downstream child jobs waiting inwaiting[job_id], decrementing theirremaininguncompleted dependency counts. Whenremainingreaches 0, the child enters stateready. - When a job enters
dlq(either via explicit failure beyondmax_retry, lease expiration, or enqueueing with adlqdependency), a BFS queue traverses all dependent children in the graph, transitioning them todlq.
- When
Complexity Analysis
enqueue: $O(D)$ time where $D$ is the number of dependencies to record edges and evaluate initial state.reserve: $O(\log N)$ time to push a deadline entry onto the min-heap, where $N$ is the number of pending timers.pass/fail: $O(C)$ time where $C$ is the number of dependent child jobs (plus $O(V + E)$ cascade cost if dead-lettering occurs).advance: $O(K \log N)$ where $K$ is the number of expiring lease timers.get_dlq: $O(J)$ time to iterate through enqueued jobs in insertion order, where $J$ is the total count of jobs.- Space Complexity: $O(J + E + N)$ total auxiliary space for job records, graph edges, and heap timers.
import heapq
from collections import deque
from typing import List
def process_queue(operations: List[str], arguments: List[List]) -> List:
jobs = {}
waiting = {}
timers = []
results = []
now = 0.0
sequence = 0
def dead_letter(root):
queue = deque([root])
while queue:
job_id = queue.popleft()
job = jobs[job_id]
if job['state'] in ('passed', 'dlq'):
continue
job['state'] = 'dlq'
for child in waiting[job_id]:
queue.append(child)
waiting[job_id].clear()
def expire():
while timers and timers[0][0] <= now:
deadline, _, job_id, version = heapq.heappop(timers)
job = jobs[job_id]
if job['state'] != 'reserved' or job['version'] != version:
continue
job['retries'] += 1
job['state'] = 'ready'
if job['retries'] > job['max_retry']:
dead_letter(job_id)
for operation, args in zip(operations, arguments):
expire()
if operation == 'enqueue':
job_id, timeout, max_retry, *dependency_arg = args
dependencies = dependency_arg[0] if dependency_arg else []
if job_id in jobs or any(dep not in jobs for dep in dependencies):
results.append(False)
continue
blocked = [dep for dep in dependencies if jobs[dep]['state'] != 'passed']
job = {'state': 'blocked' if blocked else 'ready', 'timeout': timeout,
'max_retry': max_retry, 'retries': 0, 'version': 0,
'remaining': len(blocked)}
jobs[job_id] = job
waiting[job_id] = []
for dep in blocked:
if jobs[dep]['state'] == 'dlq':
job['state'] = 'dlq'
break
waiting[dep].append(job_id)
if job['state'] == 'dlq':
dead_letter(job_id)
results.append(True)
elif operation == 'reserve':
job_id, = args
job = jobs.get(job_id)
if job is None or job['state'] != 'ready':
results.append(False)
continue
job['state'] = 'reserved'
job['version'] += 1
sequence += 1
heapq.heappush(timers, (now + job['timeout'], sequence, job_id, job['version']))
results.append(True)
elif operation in ('pass', 'ack'):
job_id, = args
job = jobs.get(job_id)
if job is None or job['state'] != 'reserved':
results.append(False)
continue
job['state'] = 'passed'
for child in waiting[job_id]:
dependent = jobs[child]
if dependent['state'] == 'blocked':
dependent['remaining'] -= 1
if dependent['remaining'] == 0:
dependent['state'] = 'ready'
waiting[job_id].clear()
results.append(True)
elif operation == 'fail':
job_id, = args
job = jobs.get(job_id)
if job is None or job['state'] != 'reserved':
results.append(False)
continue
job['retries'] += 1
if job['retries'] > job['max_retry']:
dead_letter(job_id)
else:
job['state'] = 'ready'
results.append(True)
elif operation == 'advance':
now += args[0]
expire()
results.append(None)
elif operation == 'get_dlq':
results.append([j_id for j_id, job in jobs.items() if job['state'] == 'dlq'])
else:
results.append(None)
return results