Prioritized Job Queue with Retries
Role: Software Engineer
Category: Software Engineering Fundamentals
Difficulty: medium
Interview Round: Other
Design a background job processing system that supports priority levels, a maximum retry limit, exponential backoff on failures, and a dead letter queue for jobs that exhaust all retries.
Jobs are added with a name, a priority (lower number means higher priority), and a maximum retry count. When a job is processed, it either succeeds (and is removed) or fails. On failure, the job is re-enqueued with an exponential backoff delay of `2^retryCount` time units, where `retryCount` is the number of times the job has failed so far, including this failure. If a job has failed more times than its maximum retry limit, it is moved to the dead letter queue instead of being re-enqueued.
When selecting the next job to process, the system picks the highest-priority job whose backoff period has expired (`availableAt <= currentTime`). Ties in priority are broken by earliest available time, then by insertion order. A newly added job is available immediately, with an available time of 0, and a retried job keeps its original insertion order.
Implement a `JobQueue` class with the following methods:
- `addJob(name: str, priority: int, maxRetries: int)`: Add a job to the queue with the given name, priority (lower number = higher priority), and maximum number of retries allowed.
- `processNext(currentTime: int, success: bool) -> str`: Process the next available job at the given timestamp. If `success` is true, the job is completed and removed. If false, the job fails and is retried with exponential backoff, or moved to the dead letter queue if its retries are exhausted. Returns the job name, or an empty string if no job is available.
- `getDeadLetterQueue() -> List[str]`: Return the names of the jobs in the dead letter queue in the order they were added to it.
- `getQueueSize() -> int`: Return the number of jobs currently in the active queue, including jobs that are waiting out a backoff.
- `getDeadLetterQueueSize() -> int`: Return the number of jobs in the dead letter queue.
- `peekNext(currentTime: int) -> str`: Return the name of the job that would be processed at the given timestamp without processing it. Returns an empty string if no job is available.
Example 1: a single job that fails once and succeeds on its retry.
```text
Input:
["JobQueue", "processNext", "addJob", "peekNext", "processNext", "processNext", "getQueueSize"]
[[], [0, true], ["taskA", 5, 3], [0], [0, false], [5, true], []]
Output: [null, "", null, "taskA", "taskA", "taskA", 0]
Explanation:
jq = JobQueue() # empty job queue
jq.processNext(0, True) # -> "" (no jobs in the queue)
jq.addJob("taskA", 5, 3) # priority 5, at most 3 retries
jq.peekNext(0) # -> "taskA" (nothing is processed)
jq.processNext(0, False) # -> "taskA" (fails: retryCount = 1, availableAt = 0 + 2 = 2)
jq.processNext(5, True) # -> "taskA" (available since t = 2, succeeds and is removed)
jq.getQueueSize() # -> 0 (queue is empty)
```
Example 2: priorities, the available-time tie-break, and the dead letter queue.
```text
Input:
["JobQueue", "addJob", "addJob", "addJob", "processNext", "processNext", "processNext", "peekNext", "processNext", "processNext", "getQueueSize", "processNext", "processNext", "getDeadLetterQueue", "getDeadLetterQueueSize"]
[[], ["email", 2, 1], ["report", 1, 2], ["cleanup", 2, 1], [0, false], [1, false], [2, true], [3], [3, false], [3, false], [], [4, true], [5, false], [], []]
Output: [null, null, null, null, "report", "email", "report", "cleanup", "cleanup", "email", 1, "", "cleanup", ["email", "cleanup"], 2]
Explanation:
jq = JobQueue()
jq.addJob("email", 2, 1)
jq.addJob("report", 1, 2)
jq.addJob("cleanup", 2, 1)
jq.processNext(0, False) # -> "report" (priority 1 goes first; fails, retryCount = 1, availableAt = 0 + 2 = 2)
jq.processNext(1, False) # -> "email" (report waits until 2; email and cleanup tie on priority 2 and
# availableAt 0, email was added first; fails, availableAt = 1 + 2 = 3)
jq.processNext(2, True) # -> "report" (runnable again at 2; succeeds and is removed)
jq.peekNext(3) # -> "cleanup" (both priority 2; cleanup's availableAt 0 is earlier than email's 3)
jq.processNext(3, False) # -> "cleanup" (fails, retryCount = 1, availableAt = 3 + 2 = 5)
jq.processNext(3, False) # -> "email" (second failure: 2 > maxRetries 1, moved to the dead letter queue)
jq.getQueueSize() # -> 1 (cleanup, still waiting out its backoff)
jq.processNext(4, True) # -> "" (cleanup is not runnable until 5)
jq.processNext(5, False) # -> "cleanup" (second failure, moved to the dead letter queue)
jq.getDeadLetterQueue() # -> ["email", "cleanup"]
jq.getDeadLetterQueueSize() # -> 2
```
```hint Ordering the candidates
Write the selection rule as one comparison key built from the three tie-break fields, and use exactly the same rule in processNext and peekNext.
```
```hint The retry boundary
Trace a job with maxRetries = 1 by hand. How many times can it fail before it lands in the dead letter queue, and how long is each wait?
```
### Constraints & Assumptions
- `1 <= maxRetries <= 10`
- `0 <= priority <= 100`
- Job names are non-empty strings.
- `0 <= currentTime <= 10⁶`, and `currentTime` never decreases across successive calls.
- At most `10³` operations in total.
### Clarifying Questions to Ask
- Can two jobs share a name, and will a later operation (cancel, status lookup) need to find a job by name?
- Is the queue called from a single thread, or will several workers call `processNext` at the same time?
- How large can the active queue grow in production compared with the 1,000 operations here? That decides which data structure is worth the extra code.
### What a Strong Answer Covers
- The selection rule (priority, then available time, then insertion order) applied identically in `processNext` and `peekNext`, with `peekNext` leaving every job untouched.
- The failure path: when the retry count is incremented, the exact comparison that sends a job to the dead letter queue, and a backoff computed from the updated count.
- What `getQueueSize` counts and how the dead letter queue keeps its order.
- Time and space complexity of the chosen structure, and how it would change for a much larger queue.
- Edge cases such as an empty queue, every job still in backoff, and repeated job names.
### Follow-up Questions
- How would you make `processNext` and `peekNext` run in logarithmic time?
- Several workers on different machines pull from this queue. How do you stop two of them from running the same job, and what happens to a job whose worker crashes halfway through?
- Many jobs fail at the same moment because a downstream service is down. What goes wrong with plain exponential backoff, and how would you change it?
- What would you store in the dead letter queue so an operator can inspect and replay failed jobs?
Overview: Design an in-memory job queue that runs the highest-priority job whose backoff has expired, retries failed jobs with exponential backoff, and moves jobs past their retry limit to a dead letter queue. It tests state modeling, deterministic tie-breaking, retry-limit boundaries and how the design scales to a large queue.