Design an AsyncTaskQueue with a concurrency limit and a priority-ordered pending queue
Company: Miro
Role: Software Engineer
Category: Software Engineering Fundamentals
Difficulty: medium
Interview Round: Other
Design an `AsyncTaskQueue` that schedules tasks under a bounded concurrency limit. The queue accepts task submissions with an integer `priority` and allows at most `maxConcurrent` tasks to be in the `RUNNING` state at any moment.
When a task is submitted and the running count is below the limit, it starts immediately and becomes `RUNNING`. Otherwise the task is placed in a pending queue ordered by higher priority first, then by earlier submission time as a tiebreaker. When a running task completes or is cancelled, the next eligible pending task is promoted to `RUNNING`.
Each task is in one of these states: `PENDING`, `RUNNING`, `COMPLETED` or `CANCELLED`. Cancelling a pending task removes it from the queue; cancelling a running task frees a concurrency slot.
Implement the following methods:
- `AsyncTaskQueue(maxConcurrent: int)`: create an empty queue with the given limit.
- `submit(taskId: int, priority: int) -> str`: submit a task. Returns `'RUNNING'` if it starts immediately, otherwise `'PENDING'`.
- `complete(taskId: int) -> bool`: mark a running task as `COMPLETED`, freeing a slot and promoting the next pending task. Returns `True` on success, `False` if the task is not currently running.
- `cancel(taskId: int) -> bool`: cancel a pending or running task. Returns `True` if it was cancelled, `False` if the task does not exist or has already finished.
- `getState(taskId: int) -> str`: return the current state of the task: `'PENDING'`, `'RUNNING'`, `'COMPLETED'`, `'CANCELLED'`, or `'UNKNOWN'` if no such task was ever submitted.
- `runningCount() -> int`: return the number of tasks currently in the `RUNNING` state.
- `pendingCount() -> int`: return the number of tasks currently in the `PENDING` state.
Example 1:
```text
Input:
["AsyncTaskQueue", "submit", "submit", "submit", "submit", "runningCount", "pendingCount", "complete", "getState", "getState"]
[[2], [1, 5], [2, 3], [3, 7], [4, 1], [], [], [1], [3], [4]]
Output: [null, "RUNNING", "RUNNING", "PENDING", "PENDING", 2, 2, true, "RUNNING", "PENDING"]
Explanation:
q = AsyncTaskQueue(2) # maxConcurrent = 2
q.submit(1, 5) # 'RUNNING' (slot free, task 1 starts)
q.submit(2, 3) # 'RUNNING' (slot free, task 2 starts)
q.submit(3, 7) # 'PENDING' (slots full, queued at priority 7)
q.submit(4, 1) # 'PENDING' (queued at priority 1)
q.runningCount() # 2
q.pendingCount() # 2
q.complete(1) # True (frees a slot, promotes task 3, the highest priority)
q.getState(3) # 'RUNNING'
q.getState(4) # 'PENDING'
```
Example 2:
```text
Input:
["AsyncTaskQueue", "submit", "submit", "submit", "cancel", "complete", "getState", "getState", "runningCount", "pendingCount"]
[[1], [10, 2], [20, 5], [30, 5], [20], [10], [10], [30], [], []]
Output: [null, "RUNNING", "PENDING", "PENDING", true, true, "COMPLETED", "RUNNING", 1, 0]
Explanation:
q = AsyncTaskQueue(1) # maxConcurrent = 1
q.submit(10, 2) # 'RUNNING' (task 10 starts)
q.submit(20, 5) # 'PENDING' (queued, priority 5)
q.submit(30, 5) # 'PENDING' (queued, priority 5 but submitted later)
q.cancel(20) # True (pending task 20 removed)
q.complete(10) # True (promotes task 30, since 20 was cancelled)
q.getState(10) # 'COMPLETED'
q.getState(30) # 'RUNNING'
q.runningCount() # 1
q.pendingCount() # 0
```
```hint Ordering the pending tasks
Pick a structure that hands you the highest-priority task quickly, and think about what to add to its key so that equal priorities come out in submission order.
```
```hint Cancelling from the middle
Removing an arbitrary task from a heap is awkward. Consider leaving its entry in place and deciding what to do with it when it reaches the top, and check what that does to your pending count.
```
### Constraints & Assumptions
- `1 <= maxConcurrent <= 100`
- `1 <= priority <= 10` (a higher value means higher priority)
- Task ids are unique positive integers.
- At most 10,000 operations in total across `submit`, `complete`, `cancel` and the queries.
### Clarifying Questions to Ask
- If `submit` is called with an id that is already pending or running, should it return the current state without queuing the task again?
- Can an id be submitted again after its task has completed or been cancelled?
- Does the queue execute the tasks itself, or does the caller report completion through `complete`?
- Are the methods called from a single thread, or does the queue have to be safe under concurrent calls?
### What a Strong Answer Covers
- A pending structure that returns the highest-priority, earliest-submitted task in logarithmic time, with a submission counter as the tiebreak.
- A way to cancel a pending task without scanning the queue, and correct handling of any stale entries that approach leaves behind.
- Promotion after both `complete` and `cancel` of a running task, and the reason a newly submitted task that finds a free slot never jumps ahead of a waiting one.
- Constant-time state lookups and counts, and the right return values for unknown, finished and repeated ids.
- The time and space cost of each operation.
### Follow-up Questions
- How would you make the queue safe when `submit`, `complete` and `cancel` arrive from many threads, or turn it into an asyncio scheduler that actually runs coroutines?
- With lazy deletion, cancelled entries can pile up in the heap. When does that become a problem, and how would you compact it?
- How would you keep low-priority tasks from starving under a steady stream of high-priority work?
- How would you support changing the priority of a task that is still pending?
Overview: Design a task queue that runs at most a fixed number of tasks at once and holds the rest in a pending queue ordered by priority, then submission time. It tests heap-based scheduling, cancellation with lazy deletion, and careful state tracking across submit, complete and cancel.