Thread-Safe Leased Payment Queue

Hard · Software Engineering Fundamentals · Software Engineer · Technical Screen

Problem Statement

Payment processing workers can stall on network calls or crash mid-flight, so an in-memory work queue cannot simply pop and forget jobs on delivery, nor can it allow duplicate submissions or late acknowledgments from timed-out workers to settle a charge twice.

Implement a thread-safe class ConcurrentPaymentQueue that coordinates payment dispatch using temporary visibility leases, per-lease receipt tokens, and permanent payment_id deduplication:

from typing import Callable, Optional, Tuple
import time


class ConcurrentPaymentQueue:
    def __init__(
        self,
        visibility_timeout: float,
        clock: Callable[[], float] = time.monotonic,
    ) -> None: ...

    def submit(self, payment_id: str, amount: float) -> bool: ...

    def receive(self) -> Optional[Tuple[str, float, str]]: ...

    def ack(self, payment_id: str, receipt_handle: str) -> bool: ...

Your implementation must enforce these exact rules:

  1. Initialization & validation: visibility_timeout specifies the lease duration in seconds (visibility_timeout <= 0 raises ValueError). clock is a zero-argument callable returning current monotonic seconds (defaulting to time.monotonic so tests can inject deterministic clocks). In submit, amount <= 0 raises ValueError without recording payment_id.
  2. Permanent idempotency (submit): If payment_id has never been accepted before, record it as immediately visible at clock() and return True. If payment_id was ever accepted earlier — whether currently waiting, actively leased, expired awaiting redelivery, or already completed — reject it and return False.
  3. Leased delivery & ordering (receive): Atomically claim the uncompleted payment with the earliest visibility timestamp (submit time if never leased, or its expired lease deadline if a prior lease timed out; ties broken by whichever schedule event occurred first). If no uncompleted payment has visible_at <= clock(), return None. Otherwise, issue a brand-new unique receipt_handle, hide the payment over the half-open window [now, now + visibility_timeout) so it becomes visible again at now + visibility_timeout, and return (payment_id, amount, receipt_handle).
  4. Fenced completion (ack): Permanently mark payment_id completed and return True if and only if payment_id exists, is not yet completed, matches the newest receipt_handle issued for payment_id, and clock() < lease_deadline. At clock() >= lease_deadline, the lease is expired and ack must return False even if no consumer has re-received the payment yet.
  5. Thread safety: Every method must execute safely across concurrent producer and consumer threads with no race conditions or deadlocks.

Examples

Example 1

Input:

q = ConcurrentPaymentQueue(visibility_timeout=3.0, clock=clock)  # clock starts at 0.0
r1 = q.submit("inv_42", 75.5)
r2 = q.submit("inv_42", 75.5)
lease_1 = q.receive()
empty_check = q.receive()
clock.advance(3.2)               # t = 3.2 (past the 3.0s lease deadline)
lease_2 = q.receive()
stale_ack = q.ack("inv_42", lease_1[2])
valid_ack = q.ack("inv_42", lease_2[2])
resubmit = q.submit("inv_42", 12.0)
double_ack = q.ack("inv_42", lease_2[2])

Output:

r1 = True, r2 = False
lease_1 = ("inv_42", 75.5, "<handle_1>"), empty_check = None
lease_2 = ("inv_42", 75.5, "<handle_2>")  (with <handle_2> != <handle_1>)
stale_ack = False, valid_ack = True, resubmit = False, double_ack = False

Walk-through: "inv_42" is accepted once at t = 0.0 and leased with <handle_1> until t = 3.0, so an immediate second receive() returns None. At t = 3.2 the first lease has expired, allowing Worker 2 to receive "inv_42" under a fresh token <handle_2>. Worker 1's late ack with <handle_1> is rejected, Worker 2's ack succeeds, and both re-submission and duplicate ack calls afterward return False.

Example 2

Input:

q = ConcurrentPaymentQueue(visibility_timeout=4.0, clock=clock)  # clock starts at 10.0
q.submit("tx_alpha", 25.0)
q.receive()                      # leases "tx_alpha" at t = 10.0 (deadline 14.0)
clock.advance(2.0)               # t = 12.0
q.submit("tx_beta", 40.0)        # visible from t = 12.0
clock.advance(3.0)               # t = 15.0
q.submit("tx_gamma", 15.0)       # visible from t = 15.0
order = [q.receive()[0], q.receive()[0], q.receive()[0]]

Output:

order = ["tx_beta", "tx_alpha", "tx_gamma"]

Walk-through: By t = 15.0, all three payments are visible: "tx_beta" has been waiting since 12.0, "tx_alpha" became visible again when its lease expired at 14.0, and "tx_gamma" arrived at 15.0. receive() dispatches them in ascending order of visibility timestamp.

Constraints

  • visibility_timeout > 0
  • amount > 0
  • 1 <= len(payment_id) <= 128
  • Up to 10^5 total submit, receive, and ack calls across concurrent worker threads.
  • Use only the Python standard library (e.g., heapq, threading, time).

Step-by-step walkthrough

  1. Understand the payment lifecycle and lease rules

    In a payment system, simply popping a message off a queue when a worker asks for work is dangerous: if that worker crashes mid-request, the payment vanishes forever. Instead, receive() grants a temporary lease for visibility_timeout seconds and hands the worker a unique receipt handle (a one-lease claim token).

    Each accepted payment_id moves through three states:

    submit()          receive() issues (handle, deadline)          ack() before deadline with latest handle
       |                              |                                              |
    PENDING  ------------------>  IN FLIGHT  ----------------------------------> COMPLETED
       ^                              |
       |                              +-- now >= deadline without ack:
       +--------------------------------- lease expires; message becomes visible again
    

    Before writing code, let's pin down the exact boundary rules so every edge case is crystal clear:

    • Complementary lease boundary ([t, t + timeout)): A receive() at time t keeps the message invisible while now < t + visibility_timeout. At the exact instant now == t + visibility_timeout, the lease is expired (ack returns False even if nobody else has called receive() yet) and the message is visible again to receive().
    • Visibility order: receive() always hands out whichever payment became visible earliest — its submit time if never received, or its expired lease_deadline if a worker timed out. Ties go to whichever event was scheduled first.
    • Permanent idempotency: Once a payment_id is accepted by submit(), any future submit() with that same payment_id must return False forever — whether the payment is pending, in flight, expired, or already completed — so a customer can never be charged twice.
    • Injectable monotonic clock: Defaulting clock to time.monotonic protects leases from wall-clock jumps (such as NTP time adjustments) and lets unit tests advance a fake clock instantly without time.sleep().
  2. Why a naive list scan becomes a bottleneck

    The simplest correct implementation stores a dictionary payment_id -> record and scans every stored payment inside receive() to find the earliest visible, non-completed entry.

    Why is that too slow here? With up to 100,000 operations, tens of thousands of completed or in-flight payments can sit in the dictionary at once. Scanning N records on every receive() takes O(N) time while holding the lock, stalling every other producer and consumer thread for up to billions of loop iterations total. Spawning a threading.Timer per message is worse: creating tens of thousands of OS threads wastes memory and introduces tricky race conditions between timer callbacks and ack().

  3. Key idea: unify new and in-flight payments in one min-heap

    Notice that every payment that is not yet completed has a single timestamp visible_at when a consumer is next allowed to receive it:

    • For a newly submitted payment, visible_at = submit_time (visible right now).
    • For an in-flight payment, visible_at = lease_deadline (invisible until its lease expires).

    If we store (visible_at, seq, payment_id) in a min-heap (heapq), the payment with the smallest visible_at always sits at self._heap[0] in O(1) time:

    self._heap[0] -> (visible_at, seq, payment_id)
                         |         |
                         |         +-- strictly increasing counter: breaks ties in FIFO order
                         |             and stops Python from ever comparing payment_id strings
                         +------------ earliest timestamp when this payment may be received
    

    How do we avoid O(N) heap removals when ack() finishes an in-flight payment? We use lazy deletion:

    • ack() only sets payment.completed = True on the dictionary record in O(1) time without touching the heap.
    • Later, whenever a completed payment's old (deadline, seq, payment_id) tuple bubbles up to self._heap[0] inside receive(), receive() pops and ignores it.
    • Because a payment is only pushed on submit() and re-pushed when popped in receive(), each payment_id has at most one tuple in the heap at any moment.
  4. Define per-payment state and idempotent `submit`

    Let's create a small _Payment helper class for each payment's state and write __init__, _schedule, and submit. Notice that we validate amount <= 0 before acquiring the lock or inserting into self._payments, so an invalid call never poisons a valid payment_id.

    from typing import Callable, Dict, List, Optional, Tuple
    import heapq
    import threading
    import time
    
    
    class _Payment:
        """Mutable lifecycle state for a single accepted payment_id."""
    
        def __init__(self, payment_id: str, amount: float) -> None:
            self.payment_id = payment_id
            self.amount = amount
            self.latest_handle: Optional[str] = None
            self.lease_deadline: float = 0.0
            self.completed: bool = False
    
    
    class ConcurrentPaymentQueue:
        def __init__(self, visibility_timeout: float, clock: Callable[[], float] = time.monotonic) -> None:
            if visibility_timeout <= 0:
                raise ValueError("visibility_timeout must be > 0")
            self._timeout = visibility_timeout
            self._clock = clock
            self._lock = threading.Lock()
            self._payments: Dict[str, _Payment] = {}
            self._heap: List[Tuple[float, int, str]] = []
            self._seq = 0
            self._lease_counter = 0
    
        def _schedule(self, visible_at: float, payment_id: str) -> None:
            """Push one visibility event onto the min-heap with a FIFO tie-breaker."""
            self._seq += 1
            heapq.heappush(self._heap, (visible_at, self._seq, payment_id))
    
        def submit(self, payment_id: str, amount: float) -> bool:
            if amount <= 0:
                raise ValueError("amount must be > 0")
    
            with self._lock:
                if payment_id in self._payments:
                    return False
                now = self._clock()
                self._payments[payment_id] = _Payment(payment_id, amount)
                self._schedule(now, payment_id)
                return True
    
  5. Lease the earliest visible payment in `receive`

    When a worker calls receive(), we inspect self._heap[0] in a while loop under self._lock:

    1. Completed entry (payment.completed is True): Pop the stale heap entry and continue to the next candidate.
    2. Still invisible (visible_at > now): Because a min-heap keeps the smallest visible_at at index 0, if the top entry is still in the future, every entry in the heap is still in the future. We can stop immediately and return None.
    3. Visible (visible_at <= now): Pop the entry, mint a brand-new handle "rh-<counter>", set lease_deadline = now + self._timeout, push (lease_deadline, seq, payment_id) back onto the heap for automatic timeout recovery, and return the lease tuple.

    Overwriting payment.latest_handle with the new handle is what automatically invalidates every older worker's receipt handle on re-delivery.

    def receive(self) -> Optional[Tuple[str, float, str]]:
        with self._lock:
            now = self._clock()
    
            while self._heap:
                visible_at, _, payment_id = self._heap[0]
                payment = self._payments[payment_id]
    
                # Phase 1 (Lazy deletion): Discard entries for payments acked while in flight.
                if payment.completed:
                    heapq.heappop(self._heap)
                    continue
    
                # Phase 2 (Visibility check): Earliest entry is still invisible, so all are.
                if visible_at > now:
                    return None
    
                # Phase 3 (Grant lease): Mint a fresh handle and reschedule at `now + timeout`.
                heapq.heappop(self._heap)
                self._lease_counter += 1
                new_handle = f"rh-{self._lease_counter}"
                new_deadline = now + self._timeout
    
                payment.latest_handle = new_handle
                payment.lease_deadline = new_deadline
                self._schedule(new_deadline, payment_id)
                return (payment_id, payment.amount, new_handle)
    
            return None
    
  6. Reject stale, expired, and duplicate receipts in `ack`

    For ack(payment_id, receipt_handle) to succeed, four things must all hold inside the same lock acquisition:

    1. payment_id was submitted (payment is not None).
    2. It has not already been completed (not payment.completed).
    3. It has been leased and receipt_handle matches payment.latest_handle (rejects forged handles and handles superseded by a newer receive()).
    4. Current time is strictly before the deadline (now < payment.lease_deadline). Using if now >= payment.lease_deadline: return False matches if visible_at > now: return None in receive(), so at now == lease_deadline the old lease is expired and a new lease can be granted without conflict.

    Why must all of submit, receive, and ack hold self._lock for their entire check-and-update? Even in CPython, the Global Interpreter Lock (GIL) can switch threads between any two bytecodes — for example, right after two threads both see payment.completed == False — allowing both threads to return True from ack without a mutex. Because there is only one non-reentrant lock, no public method calls another public method, and nothing sleeps inside the lock, deadlocks are impossible.

    def ack(self, payment_id: str, receipt_handle: str) -> bool:
        with self._lock:
            payment = self._payments.get(payment_id)
            if payment is None or payment.completed:
                return False
            if payment.latest_handle is None or payment.latest_handle != receipt_handle:
                return False
            now = self._clock()
            if now >= payment.lease_deadline:
                return False
    
            payment.completed = True
            return True
    
  7. Trace Example 1 step by step

    Let's trace Example 1 from statement.md with visibility_timeout = 3.0 starting at t = 0.0:

    Time  Call                       Return value               Record state                     Heap [(visible_at, seq, id)]
    ----  -------------------------  -------------------------  -------------------------------  ----------------------------
    0.0   submit("inv_42", 75.5)     True                       handle=None, done=False          [(0.0, 1, "inv_42")]
    0.0   submit("inv_42", 75.5)     False (already in dict)    handle=None, done=False          [(0.0, 1, "inv_42")]
    0.0   receive()                  ("inv_42", 75.5, "rh-1")   handle="rh-1", deadline=3.0      [(3.0, 2, "inv_42")]
    0.0   receive()                  None (top 3.0 > 0.0)       handle="rh-1", deadline=3.0      [(3.0, 2, "inv_42")]
    3.2   receive()                  ("inv_42", 75.5, "rh-2")   handle="rh-2", deadline=6.2      [(6.2, 3, "inv_42")]
    3.2   ack("inv_42", "rh-1")      False ("rh-1" != "rh-2")   handle="rh-2", deadline=6.2      [(6.2, 3, "inv_42")]
    3.2   ack("inv_42", "rh-2")      True (3.2 < 6.2)           handle="rh-2", done=True         [(6.2, 3, "inv_42")] (stale)
    3.2   submit("inv_42", 12.0)     False (kept in dict)       handle="rh-2", done=True         [(6.2, 3, "inv_42")] (stale)
    3.2   ack("inv_42", "rh-2")      False (already done)       handle="rh-2", done=True         [(6.2, 3, "inv_42")] (stale)
    

    Notice how Worker 1's late ack("inv_42", "rh-1") at t = 3.2 was safely rejected because Worker 2's receive() had already overwritten latest_handle with "rh-2", and how the stale (6.2, 3, "inv_42") heap tuple will be silently discarded the next time receive() inspects the top of the heap.

  8. Complete solution

    from typing import Callable, Dict, List, Optional, Tuple
    import heapq
    import threading
    import time
    
    
    class _Payment:
        """Mutable lifecycle state for a single accepted payment_id."""
    
        def __init__(self, payment_id: str, amount: float) -> None:
            self.payment_id = payment_id
            self.amount = amount
            # latest_handle: receipt handle of the newest lease, or None if never received yet.
            self.latest_handle: Optional[str] = None
            # lease_deadline: timestamp when the current lease expires; valid while now < lease_deadline.
            self.lease_deadline: float = 0.0
            # completed: True once a valid ack() permanently finishes this payment.
            self.completed: bool = False
    
    
    class ConcurrentPaymentQueue:
        def __init__(self, visibility_timeout: float, clock: Callable[[], float] = time.monotonic) -> None:
            if visibility_timeout <= 0:
                raise ValueError("visibility_timeout must be > 0")
            self._timeout = visibility_timeout
            # Monotonic clock avoids wall-clock jumps (e.g. NTP adjustments) and lets tests inject fake time.
            self._clock = clock
            # Single mutex serializing every check-and-update across submit, receive, and ack.
            self._lock = threading.Lock()
            # _payments: dict mapping payment_id -> _Payment, retained forever to enforce idempotency.
            self._payments: Dict[str, _Payment] = {}
            # _heap: min-heap of (visible_at, seq, payment_id) tuples ordered by earliest visibility time.
            # Holds at most one entry per payment (submit time when new, lease_deadline when in flight).
            self._heap: List[Tuple[float, int, str]] = []
            # _seq: strictly increasing tie-breaker so equal visible_at timestamps preserve FIFO order.
            self._seq = 0
            # _lease_counter: strictly increasing counter so every receive() issues a distinct handle.
            self._lease_counter = 0
    
        def _schedule(self, visible_at: float, payment_id: str) -> None:
            """Push one visibility event onto the min-heap with a FIFO tie-breaker."""
            self._seq += 1
            heapq.heappush(self._heap, (visible_at, self._seq, payment_id))
    
        def submit(self, payment_id: str, amount: float) -> bool:
            # Validate input before touching shared state so bad calls never reserve a payment_id.
            if amount <= 0:
                raise ValueError("amount must be > 0")
    
            with self._lock:
                # Phase 1: Reject duplicates across all states (pending, in-flight, expired, or completed).
                if payment_id in self._payments:
                    return False
    
                # Phase 2: Record the new payment and schedule it as immediately visible at `now`.
                now = self._clock()
                self._payments[payment_id] = _Payment(payment_id, amount)
                self._schedule(now, payment_id)
                return True
    
        def receive(self) -> Optional[Tuple[str, float, str]]:
            with self._lock:
                now = self._clock()
    
                while self._heap:
                    visible_at, _, payment_id = self._heap[0]
                    payment = self._payments[payment_id]
    
                    # Phase 1 (Lazy deletion): Discard entries for payments acked while in flight.
                    if payment.completed:
                        heapq.heappop(self._heap)
                        continue
    
                    # Phase 2 (Visibility check): Because the heap is ordered by `visible_at`,
                    # if the earliest entry has `visible_at > now`, every entry is still invisible.
                    if visible_at > now:
                        return None
    
                    # Phase 3 (Grant lease): Pop the visible payment, mint a fresh receipt handle,
                    # and reschedule it at `now + timeout` in case this consumer crashes or times out.
                    heapq.heappop(self._heap)
                    self._lease_counter += 1
                    new_handle = f"rh-{self._lease_counter}"
                    new_deadline = now + self._timeout
    
                    # Overwriting `latest_handle` immediately invalidates all older handles for this payment.
                    payment.latest_handle = new_handle
                    payment.lease_deadline = new_deadline
                    self._schedule(new_deadline, payment_id)
                    return (payment_id, payment.amount, new_handle)
    
                return None
    
        def ack(self, payment_id: str, receipt_handle: str) -> bool:
            with self._lock:
                payment = self._payments.get(payment_id)
    
                # Reject unknown payment_ids and payments that were already completed.
                if payment is None or payment.completed:
                    return False
    
                # Reject payments never received or handles superseded by a newer receive() lease.
                if payment.latest_handle is None or payment.latest_handle != receipt_handle:
                    return False
    
                # Use `>=` so the lease expires at the exact instant `receive()` considers it visible again
                # (`visible_at <= now`), leaving zero overlap or gap at `now == lease_deadline`.
                now = self._clock()
                if now >= payment.lease_deadline:
                    return False
    
                # Mark completed in O(1); its in-flight heap entry will be lazily popped by receive().
                payment.completed = True
                return True
    

    ✅ Submit now — all tests should pass.

Intuition & how it works

Think of this queue like a pharmacy pick-up counter that hands each worker a numbered claim ticket with an expiration timer. When a worker calls receive(), the queue does not delete the payment; instead, it hides the payment behind a visibility timeout (a time window during which no other worker can see or claim the message) and issues a fresh receipt handle (a unique one-lease token proving which checkout attempt is finishing the job). We combine two structures under one mutex (threading.Lock, a lock ensuring only one thread reads or modifies the queue at a time): a permanent dictionary self._payments enforcing idempotency (accepting each payment_id at most once across the entire lifetime of the queue) and a min-heap (a binary tree array whose index 0 always holds the smallest timestamp) keyed by visible_at — the exact instant each payment may next be received. When a worker calls ack(), we use lazy deletion (marking the dictionary record completed = True in O(1) time and letting receive() discard the leftover heap entry later when it reaches the top).

Why do simpler designs fail? Popping and deleting on receive() loses payments permanently whenever a worker crashes before finishing. Keeping all payments in a plain list or dictionary and scanning for an available one takes O(N) time per receive() while holding the lock, stalling every worker thread at 100,000 operations, whereas spawning a background threading.Timer per in-flight payment creates thousands of threads and race conditions between timer expiry and ack(). Finally, reusing the payment_id itself as the receipt handle fails when Worker A stalls past its timeout, Worker B picks up the payment, and Worker A wakes up and accidentally acks Worker B's active lease.

Let's trace Example 2 ("tx_alpha" and "tx_beta") with visibility_timeout = 4.0 starting at t = 10.0:

t = 10.0: submit("tx_alpha", 25.0) -> _payments["tx_alpha"] created; heap = [(10.0, 1, "tx_alpha")]
t = 10.0: receive()                -> pops "tx_alpha", issues "rh-1" (deadline 14.0), reschedules at 14.0
                                      heap = [(14.0, 2, "tx_alpha")]
t = 12.0: submit("tx_beta", 40.0)  -> _payments["tx_beta"] created; heap = [(12.0, 3, "tx_beta"), (14.0, 2, "tx_alpha")]
t = 15.0: receive()                -> top is "tx_beta" (12.0 <= 15.0); issues "rh-2" (deadline 19.0)
t = 15.0: receive()                -> "tx_alpha" expired at 14.0 <= 15.0! Issues "rh-3" (deadline 19.0); "rh-1" is now stale
t = 15.0: ack("tx_alpha", "rh-3")  -> marks _payments["tx_alpha"].completed = True; heap entry popped lazily later

Complexity

Let P be the total number of distinct accepted payment_ids and N (N <= P) be the number of entries currently in self._heap. Because a payment is pushed once on submit() and re-pushed only right after being popped in receive(), each payment has at most one entry in self._heap, so N <= P always holds.

  • submit: O(log N) time. Checking payment_id in self._payments and inserting the _Payment record into the hash map take O(1) average time, and pushing (now, seq, payment_id) onto the binary min-heap of size N takes O(log N) time.
  • receive: O(log N) amortized time (amortized means averaged per operation over any sequence of calls, even if one individual call cleans up several stale items). A single receive() call pops at most one live visible entry and pushes one rescheduled deadline entry (O(log N)). It may also pop completed stale entries from the top, but every heap entry is pushed once and popped at most once across the entire run, so M total operations perform at most M pops (O(M log N) total heap work).
  • ack: O(1) average time. It performs one dictionary lookup and four scalar comparisons (None, completed, latest_handle, lease_deadline), flipping payment.completed = True without touching the heap.
  • Space: O(P). self._payments retains one _Payment object per accepted payment_id forever to reject future duplicate submissions, and self._heap holds at most one 3-tuple per payment.

Edge cases

  • ack called at the exact deadline (now == lease_deadline): Returns False. The lease covers the half-open interval [receive_time, lease_deadline), matching receive() which treats visible_at <= now as visible again, so there is zero instant where both an old ack and a new receive can succeed.
  • Lease expired, but nobody called receive() again yet: payment.latest_handle still equals the old worker's handle, so handle comparison alone would pass — checking now >= payment.lease_deadline inside ack() is essential to reject the expired lease.
  • ack for an unknown ID, a never-received ID, or using another payment's handle: All return False because self._payments.get(payment_id) looks up that specific payment's latest_handle.
  • Duplicate submit after ack completes: Returns False because ack() marks completed = True rather than deleting the key from self._payments.
  • Double ack with the winning handle: The first call sets completed = True and returns True; the second sees payment.completed and returns False.
  • Invalid visibility_timeout <= 0 or amount <= 0: Raises ValueError before mutating self._payments, so a bad call never permanently reserves a payment_id.

Common mistakes

  • Splitting check and update across lock acquisitions: Peeking at self._heap[0] under a lock and popping or updating latest_handle after releasing it lets two threads lease or ack the exact same payment, causing a double charge.
  • Using time.time() instead of a monotonic clock (time.monotonic): System wall clocks can jump backward or forward during NTP syncs or daylight-saving misconfigurations, prematurely expiring active leases or freezing invisible messages.
  • Comparing handles without checking lease_deadline in ack(): Allows a worker that took 10 minutes on a 2-second lease to succeed if the queue happened to be idle during those 10 minutes.
  • Calling self._heap.remove(...) inside ack(): Removing an element from the middle of a Python heapq list takes O(N) linear scan time and breaks the heap tree invariant unless followed by an O(N) heapq.heapify().
  • Omitting the seq tie-breaker in heap tuples: Without seq in (visible_at, seq, payment_id), equal timestamps fall back to comparing payment_id strings alphabetically instead of preserving first-scheduled FIFO order.

Alternative approaches

  • FIFO collections.deque + separate in-flight min-heap: Put newly submitted payments into a deque, put in-flight leases into a min-heap keyed by deadline, and at the start of receive() move all expired leases (deadline <= now) into the deque before popping. This achieves the same O(log N) complexity, though an expired message's position relative to newly submitted messages depends on when receive() happens to run and sweep the heap, whereas a single visible_at heap orders them deterministically by exact visibility timestamp.
  • Blocking receive(wait_timeout) with threading.Condition: Wrapping self._lock in a threading.Condition allows idle workers to sleep until either submit() calls notify() or self._heap[0]'s visible_at arrives, avoiding busy-polling loops in worker threads.

Follow-up questions

  • How would you add an extend_lease(payment_id, receipt_handle, extra_seconds) heartbeat API so slow workers can push back their expiration deadline? Validate the call under self._lock with the exact same guards as ack() (known payment, not completed, latest_handle == receipt_handle, and now < lease_deadline, plus extra_seconds > 0), then set payment.lease_deadline = now + extra_seconds while keeping latest_handle unchanged so the worker's eventual ack() still succeeds. Because the earlier (old_deadline, old_seq, payment_id) tuple remains inside self._heap, store payment.active_seq = self._seq whenever _schedule pushes the latest deadline, and have receive() lazily pop and skip any heap tuple whose seq != payment.active_seq alongside payment.completed.

```python def _schedule(self, visible_at: float, payment_id: str) -> None: self._seq += 1 self._payments[payment_id].active_seq = self._seq heapq.heappush(self._heap, (visible_at, self._seq, payment_id))

def extend_lease(self, payment_id: str, receipt_handle: str, extra_seconds: float) -> bool: if extra_seconds <= 0: raise ValueError("extra_seconds must be > 0") with self._lock: payment = self._payments.get(payment_id) now = self._clock() if (payment is None or payment.completed or payment.latest_handle != receipt_handle or now >= payment.lease_deadline): return False payment.lease_deadline = now + extra_seconds self._schedule(payment.lease_deadline, payment_id) return True ```

  • What changes are needed to quarantine poison payments into a dead-letter queue once they exceed a maximum delivery-attempt count? A dead-letter queue (DLQ) is a side queue where "poison" messages that repeatedly crash or time out workers are isolated for inspection rather than cycling forever. Add delivery_count: int = 0 to _Payment and increment it each time receive() grants a lease; when receive() pops a visible item whose delivery_count == max_receives, its max_receives-th lease has just expired without an ack, so mark payment.dead_lettered = True (rejected by ack just like completed), append (payment_id, payment.amount) to self._dlq, and continue scanning the heap while retaining payment_id inside self._payments so producer retries still cannot re-submit it.
  • If traffic outgrows a single process, how would you partition the queue across machines while preserving per-payment_id ordering and preventing double charges? Partition requests across broker shards by hash(payment_id) % num_partitions so every lifecycle step for a given payment_id (such as authorize, capture, refund) routes to one shard leader that enforces local deduplication and holds step k + 1 until step k completes or enters the DLQ, replicating state transitions via a consensus log like Raft so failovers preserve active leases and idempotency history. Attach a monotonically increasing lease sequence number (a fencing token, meaning an ever-increasing generation number verified by downstream storage) to every worker lease so that if a stalled worker wakes up after its visibility timeout expired, the downstream payment ledger rejects its older fencing token and blocks a duplicate charge.

Follow-up questions

Similar questions

More Socure interview questions

All 1 Socure questions →