Thread-Safe Queue with Lease-Based Message Visibility
Data Structure DesignModel answerLast 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
-
Lease expiration: After
receive()returns a message, that message remains hidden forvisibility_timeoutseconds. If no validack()arrives before the timeout, the message becomes available again forreceive(). -
Lease token validation: Each
receive()call issues a uniquereceipt_handle. If the lease expires and another worker callsreceive(), a new handle is generated. Anyack()using the old handle must fail. -
Deduplication: A
payment_idcan only be submitted once. Further attempts with the same ID fail, even after the message is acknowledged. -
Concurrency: All methods must be safe for simultaneous calls from multiple threads.
Constraints
visibility_timeout > 0amount > 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.
Model answer
Hard Try it yourself first — then compare your approach, complexity and edge cases.
Approach
We model each payment as a small state machine with three states:
WAITING → LEASED → DONE
↑ ↓
└─timeout─┘
The core idea is to maintain:
- A record per payment ID storing amount, current state, active lease token, lease expiration time, and a generation counter.
- A ready queue holding IDs of messages in the WAITING state, preserving FIFO order.
- A min-heap of lease expirations so we can efficiently find and reclaim timed-out leases.
All shared state is protected by a single lock. Operations are short and non-blocking, so contention remains low even under concurrent load.
Data Structures
@dataclass
class _PaymentRecord:
amount: float
state: str = "WAITING" # "WAITING" | "LEASED" | "DONE"
lease_token: str | None = None
expires_at: float = 0.0
generation: int = 0 # incremented on each receive
_records: dict[str, _PaymentRecord]— source of truth; never deleted, enabling deduplication forever._ready_queue: deque[str]— FIFO queue of payment IDs ready for delivery._lease_heap: list[tuple[float, int, str]]— min-heap of(expires_at, generation, payment_id).
We never update or delete heap entries in place. Instead, when a message is acknowledged or re-leased, the old heap entry becomes stale. We detect staleness by comparing the entry's generation against the record's current generation. This avoids the cost of finding and removing arbitrary heap elements.
Operations
submit(payment_id, amount)
- Check if
payment_idexists in_records. If yes, returnFalse. - Create a new record in state WAITING.
- Append
payment_idto_ready_queue. - Return
True.
Complexity: O(1)
receive()
- Call
_reclaim_expired()to move any timed-out leases back to WAITING and push them onto_ready_queue. - If
_ready_queueis empty, returnNone. - Pop the front payment ID, retrieve its record.
- Transition state to LEASED, increment generation, generate a fresh UUID as
lease_token, computeexpires_at = now + visibility_timeout. - Push
(expires_at, generation, payment_id)onto_lease_heap. - Return
(payment_id, amount, lease_token).
Complexity: O(log n) amortized. Each message is pushed to the heap once per receive and popped once when it expires or becomes stale.
ack(payment_id, receipt_handle)
- Look up the record. If it doesn't exist or is not in LEASED state, return
False. - Check that
record.lease_token == receipt_handleandnow < record.expires_at. If either fails, returnFalse. - Transition state to DONE, clear
lease_token. - Return
True.
The old heap entry remains but is now stale; it will be ignored when popped.
Complexity: O(1)
_reclaim_expired()
Pop entries from _lease_heap while the top entry's expiration is <= now:
- Retrieve the record for the payment ID.
- If the record is not LEASED or its generation doesn't match the heap entry's generation, the entry is stale—discard it.
- Otherwise, the lease truly expired: transition back to WAITING and append to
_ready_queue.
Complexity: O(k log n), where k is the number of expired/stale entries processed.
Correctness
- No double delivery within a lease: A message moves from WAITING to LEASED atomically under the lock. Two concurrent
receive()calls cannot both retrieve the same message in the same lease period. - Stale acknowledgment rejection: Each
receive()increments the generation and issues a new token. An old token from a previous lease will not match the currentlease_tokenin the record. - Expiration safety: Even if an ack arrives after the deadline but before reclamation, the time check in
ack()will reject it. The message will then be reclaimed and redelivered. - Deduplication: Records are never deleted, so once a payment ID is submitted (in any state), further submissions fail.
- Thread safety: All operations acquire a single
threading.Lockand perform only fast, non-blocking work.time.monotonic()is used for all deadlines, avoiding issues with system clock adjustments.
Complexity Summary
| Operation | Time | Space |
|---|---|---|
submit | O(1) | O(1) per ID |
receive | O(log n) amortized | O(R) heap entries |
ack | O(1) | — |
Where n is the number of payments and R is the number of outstanding leases. With 100k operations, space usage remains well within practical limits.
Common Mistakes
- Using wall-clock time (
time.time()): System clock can jump backward due to NTP; always usetime.monotonic(). - Updating heap entries in place: Standard heaps don't support efficient decrease-key. Use lazy deletion with generation counters instead.
- Forgetting to check expiration in ack(): Even if a handle matches, the lease may have expired before the ack arrives.
- Background timer threads: Adds complexity (shutdown, races) with no benefit. Lazy reclamation during
receive()is simpler and sufficient. - Fine-grained locking: With short critical sections and Python's GIL, a single lock is faster and safer than multiple locks or lock-free structures.
Implementation
import heapq
import threading
import time
import uuid
from collections import deque
from dataclasses import dataclass
from typing import Optional
WAITING, LEASED, DONE = "WAITING", "LEASED", "DONE"
@dataclass
class _PaymentRecord:
amount: float
state: str = WAITING
lease_token: Optional[str] = None
expires_at: float = 0.0
generation: int = 0
class PaymentQueue:
def __init__(self, visibility_timeout: float):
if visibility_timeout <= 0:
raise ValueError("visibility_timeout must be positive")
self._visibility_timeout = visibility_timeout
self._lock = threading.Lock()
self._records: dict[str, _PaymentRecord] = {}
self._ready_queue: deque[str] = deque()
self._lease_heap: list[tuple[float, int, str]] = []
def submit(self, payment_id: str, amount: float) -> bool:
if amount <= 0:
raise ValueError("amount must be positive")
with self._lock:
if payment_id in self._records:
return False
self._records[payment_id] = _PaymentRecord(amount=amount)
self._ready_queue.append(payment_id)
return True
def receive(self) -> tuple[str, float, str] | None:
with self._lock:
now = time.monotonic()
self._reclaim_expired(now)
if not self._ready_queue:
return None
payment_id = self._ready_queue.popleft()
rec = self._records[payment_id]
rec.state = LEASED
rec.generation += 1
rec.lease_token = uuid.uuid4().hex
rec.expires_at = now + self._visibility_timeout
heapq.heappush(
self._lease_heap,
(rec.expires_at, rec.generation, payment_id)
)
return payment_id, rec.amount, rec.lease_token
def ack(self, payment_id: str, receipt_handle: str) -> bool:
with self._lock:
rec = self._records.get(payment_id)
if rec is None or rec.state != LEASED:
return False
if rec.lease_token != receipt_handle:
return False
if time.monotonic() >= rec.expires_at:
return False
rec.state = DONE
rec.lease_token = None
return True
def _reclaim_expired(self, now: float) -> None:
"""Move expired leases back to ready queue. Caller holds lock."""
while self._lease_heap and self._lease_heap[0][0] <= now:
expires_at, gen, payment_id = heapq.heappop(self._lease_heap)
rec = self._records[payment_id]
# Ignore stale heap entries
if rec.state != LEASED or rec.generation != gen:
continue
# Lease truly expired; make available again
rec.state = WAITING
rec.lease_token = None
self._ready_queue.append(payment_id)
This solution efficiently handles high-concurrency workloads, gracefully recovers from worker failures via automatic retry, and prevents all forms of duplicate processing through strict lease validation and永久 deduplication.