KatInterview

Thread-Safe Queue with Lease-Based Message Visibility

Data Structure DesignModel answer
HardModel answerData Structure Designconcurrencyqueuestate-machine

Last updated

Design an in-memory queue that delivers messages with time-limited leases, validates acknowledgments against current lease tokens, and rejects duplicate entries.

Problem

Build an in-memory queue for financial transactions that prevents duplicate processing, supports automatic retry on worker failure, and gracefully handles stale acknowledgments from slow or crashed workers.

Your PaymentQueue class must support three operations:

class PaymentQueue:
    def __init__(self, visibility_timeout: float):
        """
        Initialize the queue with a visibility window (in seconds) during which
        a delivered message cannot be re-delivered to other workers.
        """
        pass

    def submit(self, payment_id: str, amount: float) -> bool:
        """
        Add a new payment to the queue.
        Return True if accepted.
        Return False if a payment with this ID already exists in any state
        (waiting, being processed, or finished).
        """
        pass

    def receive(self) -> tuple[str, float, str] | None:
        """
        Retrieve the next available payment.
        Return (payment_id, amount, receipt_handle) if one is ready,
        or None if the queue is empty or all messages are currently leased.
        
        The returned message is hidden from other workers for visibility_timeout seconds.
        Each call generates a fresh receipt_handle (lease token).
        """
        pass

    def ack(self, payment_id: str, receipt_handle: str) -> bool:
        """
        Mark a payment as successfully processed.
        Return True if the acknowledgment is valid and the message is removed.
        Return False if the receipt_handle is stale, expired, or incorrect.
        """
        pass

Behavior

  1. Lease expiration: After receive() returns a message, that message remains hidden for visibility_timeout seconds. If no valid ack() arrives before the timeout, the message becomes available again for receive().

  2. Lease token validation: Each receive() call issues a unique receipt_handle. If the lease expires and another worker calls receive(), a new handle is generated. Any ack() using the old handle must fail.

  3. Deduplication: A payment_id can only be submitted once. Further attempts with the same ID fail, even after the message is acknowledged.

  4. Concurrency: All methods must be safe for simultaneous calls from multiple threads.

Constraints

  • visibility_timeout > 0
  • amount > 0
  • Up to 100,000 operations across concurrent threads
  • Use Python standard library threading primitives

Example

q = PaymentQueue(visibility_timeout=1.5)

q.submit("txn_42", 250.0)      # → True
q.submit("txn_42", 300.0)      # → False (duplicate ID)

pid, amt, handle1 = q.receive()  # → ("txn_42", 250.0, "abc123...")
q.receive()                      # → None (message is leased)

time.sleep(1.6)  # lease expires

pid, amt, handle2 = q.receive()  # → ("txn_42", 250.0, "def456...")

q.ack("txn_42", handle1)         # → False (stale handle)
q.ack("txn_42", handle2)         # → True

q.submit("txn_42", 100.0)        # → False (already completed)

Hints

Hint 1

Model each payment as a state machine: waiting → leased → completed. Track which state each ID is in.

Hint 2

Use a generation counter or timestamp per message so you can tell whether a receipt handle corresponds to the current lease or an expired one.

Hint 3

Reclaim expired leases lazily when receive() is called, rather than running a background timer thread.