KatInterview

Build a Multi-Key Task Queue with Ordering and Concurrency Control

Data Structure DesignModel answer
MediumModel answerData Structure Designconcurrencythreadingqueue

Last updated

Create a thread-safe task scheduler that runs tasks sequentially per key while respecting a global worker limit and capacity bound.

Problem

Build a thread-safe task scheduler called OrderedKeyExecutor that manages asynchronous task execution with the following requirements:

  1. Sequential per-key execution: Tasks submitted with the same key must run one at a time, in submission order. No two tasks for the same key can execute simultaneously.

  2. Limited parallel execution: The scheduler can run at most max_workers tasks concurrently across all keys combined.

  3. Capacity enforcement: The total number of waiting tasks (not yet started) cannot exceed max_capacity. New submissions beyond this limit must fail immediately.

  4. Cancellation support: Tasks that haven't started yet can be cancelled through their handle.

  5. Clean shutdown: The scheduler must support a shutdown(wait=True, timeout=None) operation that stops accepting new work and optionally waits for running tasks to finish.

API

from typing import Callable, Any, Optional

class TaskRejectedException(Exception):
    """Raised when a task cannot be accepted."""
    pass

class TaskHandle:
    def result(self, timeout: Optional[float] = None) -> Any:
        """Block until task completes and return its result or raise its exception."""
        pass

    def cancel(self) -> bool:
        """Try to cancel the task. Returns True only if cancelled before execution."""
        pass

class OrderedKeyExecutor:
    def __init__(self, max_workers: int = 4, max_capacity: int = 100):
        """Create a scheduler with the given worker and capacity limits."""
        pass

    def submit(self, key: str, fn: Callable[[], Any]) -> TaskHandle:
        """
        Submit a task for the given key.
        Raises TaskRejectedException if at capacity or shut down.
        """
        pass

    def shutdown(self, wait: bool = True, timeout: Optional[float] = None) -> bool:
        """
        Stop accepting tasks. If wait=True, block until all work completes or timeout expires.
        Returns True if all tasks finished.
        """
        pass

Example Usage

scheduler = OrderedKeyExecutor(max_workers=2, max_capacity=10)

# Submit tasks
h1 = scheduler.submit("alice", job_a)  # Starts immediately (worker 1)
h2 = scheduler.submit("bob", job_b)    # Starts immediately (worker 2)
h3 = scheduler.submit("alice", job_c)  # Queued: alice is busy
h4 = scheduler.submit("carol", job_d)  # Queued: both workers occupied

# When job_a finishes, job_c runs next (maintaining alice's task order)

Requirements & Edge Cases

  • Worker and capacity parameters: 1 <= max_workers <= 64, 1 <= max_capacity <= 100,000
  • Tasks may throw exceptions; one task's failure must not block others for that key or crash worker threads
  • Keys with no pending work should release their internal resources to avoid memory leaks
  • All operations must be thread-safe (concurrent submissions, cancellations, result queries)
  • Attempting to cancel an already-running or completed task returns False

Hints

Hint 1

Maintain separate structures for queued work per key, keys currently executing, and keys ready to run

Hint 2

Use a single lock to coordinate state changes and worker threads

Hint 3

When a task finishes, check if that key has more work before releasing it