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:
- Initialization & validation:
visibility_timeoutspecifies the lease duration in seconds (visibility_timeout <= 0raisesValueError).clockis a zero-argument callable returning current monotonic seconds (defaulting totime.monotonicso tests can inject deterministic clocks). Insubmit,amount <= 0raisesValueErrorwithout recordingpayment_id. - Permanent idempotency (
submit): Ifpayment_idhas never been accepted before, record it as immediately visible atclock()and returnTrue. Ifpayment_idwas ever accepted earlier — whether currently waiting, actively leased, expired awaiting redelivery, or already completed — reject it and returnFalse. - Leased delivery & ordering (
receive): Atomically claim the uncompleted payment with the earliest visibility timestamp (submittime 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 hasvisible_at <= clock(), returnNone. Otherwise, issue a brand-new uniquereceipt_handle, hide the payment over the half-open window[now, now + visibility_timeout)so it becomes visible again atnow + visibility_timeout, and return(payment_id, amount, receipt_handle). - Fenced completion (
ack): Permanently markpayment_idcompleted and returnTrueif and only ifpayment_idexists, is not yet completed, matches the newestreceipt_handleissued forpayment_id, andclock() < lease_deadline. Atclock() >= lease_deadline, the lease is expired andackmust returnFalseeven if no consumer has re-received the payment yet. - 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 > 0amount > 01 <= len(payment_id) <= 128- Up to
10^5totalsubmit,receive, andackcalls across concurrent worker threads. - Use only the Python standard library (e.g.,
heapq,threading,time).
Step-by-step walkthrough
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 forvisibility_timeoutseconds and hands the worker a unique receipt handle (a one-lease claim token).Each accepted
payment_idmoves 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 againBefore writing code, let's pin down the exact boundary rules so every edge case is crystal clear:
- Complementary lease boundary (
[t, t + timeout)): Areceive()at timetkeeps the message invisible whilenow < t + visibility_timeout. At the exact instantnow == t + visibility_timeout, the lease is expired (ackreturnsFalseeven if nobody else has calledreceive()yet) and the message is visible again toreceive(). - Visibility order:
receive()always hands out whichever payment became visible earliest — itssubmittime if never received, or its expiredlease_deadlineif a worker timed out. Ties go to whichever event was scheduled first. - Permanent idempotency: Once a
payment_idis accepted bysubmit(), any futuresubmit()with that samepayment_idmust returnFalseforever — whether the payment is pending, in flight, expired, or already completed — so a customer can never be charged twice. - Injectable monotonic clock: Defaulting
clocktotime.monotonicprotects leases from wall-clock jumps (such as NTP time adjustments) and lets unit tests advance a fake clock instantly withouttime.sleep().
- Complementary lease boundary (
Why a naive list scan becomes a bottleneck
The simplest correct implementation stores a dictionary
payment_id -> recordand scans every stored payment insidereceive()to find the earliest visible, non-completed entry.Why is that too slow here? With up to
100,000operations, tens of thousands of completed or in-flight payments can sit in the dictionary at once. ScanningNrecords on everyreceive()takesO(N)time while holding the lock, stalling every other producer and consumer thread for up to billions of loop iterations total. Spawning athreading.Timerper message is worse: creating tens of thousands of OS threads wastes memory and introduces tricky race conditions between timer callbacks andack().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_atwhen 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 smallestvisible_atalways sits atself._heap[0]inO(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 receivedHow do we avoid
O(N)heap removals whenack()finishes an in-flight payment? We use lazy deletion:ack()only setspayment.completed = Trueon the dictionary record inO(1)time without touching the heap.- Later, whenever a completed payment's old
(deadline, seq, payment_id)tuple bubbles up toself._heap[0]insidereceive(),receive()pops and ignores it. - Because a payment is only pushed on
submit()and re-pushed when popped inreceive(), eachpayment_idhas at most one tuple in the heap at any moment.
- For a newly submitted payment,
Define per-payment state and idempotent `submit`
Let's create a small
_Paymenthelper class for each payment's state and write__init__,_schedule, andsubmit. Notice that we validateamount <= 0before acquiring the lock or inserting intoself._payments, so an invalid call never poisons a validpayment_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 TrueLease the earliest visible payment in `receive`
When a worker calls
receive(), we inspectself._heap[0]in awhileloop underself._lock:- Completed entry (
payment.completedisTrue): Pop the stale heap entry andcontinueto the next candidate. - Still invisible (
visible_at > now): Because a min-heap keeps the smallestvisible_atat index0, if the top entry is still in the future, every entry in the heap is still in the future. We can stop immediately and returnNone. - Visible (
visible_at <= now): Pop the entry, mint a brand-new handle"rh-<counter>", setlease_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_handlewith 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- Completed entry (
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:payment_idwas submitted (payment is not None).- It has not already been completed (
not payment.completed). - It has been leased and
receipt_handlematchespayment.latest_handle(rejects forged handles and handles superseded by a newerreceive()). - Current time is strictly before the deadline (
now < payment.lease_deadline). Usingif now >= payment.lease_deadline: return Falsematchesif visible_at > now: return Noneinreceive(), so atnow == lease_deadlinethe old lease is expired and a new lease can be granted without conflict.
Why must all of
submit,receive, andackholdself._lockfor 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 seepayment.completed == False— allowing both threads to returnTruefromackwithout 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 TrueTrace Example 1 step by step
Let's trace Example 1 from
statement.mdwithvisibility_timeout = 3.0starting att = 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")att = 3.2was safely rejected because Worker 2'sreceive()had already overwrittenlatest_handlewith"rh-2", and how the stale(6.2, 3, "inv_42")heap tuple will be silently discarded the next timereceive()inspects the top of the heap.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. Checkingpayment_id in self._paymentsand inserting the_Paymentrecord into the hash map takeO(1)average time, and pushing(now, seq, payment_id)onto the binary min-heap of sizeNtakesO(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 singlereceive()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, soMtotal operations perform at mostMpops (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), flippingpayment.completed = Truewithout touching the heap.- Space:
O(P).self._paymentsretains one_Paymentobject per acceptedpayment_idforever to reject future duplicate submissions, andself._heapholds at most one 3-tuple per payment.
Edge cases
ackcalled at the exact deadline (now == lease_deadline): ReturnsFalse. The lease covers the half-open interval[receive_time, lease_deadline), matchingreceive()which treatsvisible_at <= nowas visible again, so there is zero instant where both an oldackand a newreceivecan succeed.- Lease expired, but nobody called
receive()again yet:payment.latest_handlestill equals the old worker's handle, so handle comparison alone would pass — checkingnow >= payment.lease_deadlineinsideack()is essential to reject the expired lease. ackfor an unknown ID, a never-received ID, or using another payment's handle: All returnFalsebecauseself._payments.get(payment_id)looks up that specific payment'slatest_handle.- Duplicate
submitafterackcompletes: ReturnsFalsebecauseack()markscompleted = Truerather than deleting the key fromself._payments. - Double
ackwith the winning handle: The first call setscompleted = Trueand returnsTrue; the second seespayment.completedand returnsFalse. - Invalid
visibility_timeout <= 0oramount <= 0: RaisesValueErrorbefore mutatingself._payments, so a bad call never permanently reserves apayment_id.
Common mistakes
- Splitting check and update across lock acquisitions: Peeking at
self._heap[0]under a lock and popping or updatinglatest_handleafter releasing it lets two threads lease orackthe 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_deadlineinack(): 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(...)insideack(): Removing an element from the middle of a Pythonheapqlist takesO(N)linear scan time and breaks the heap tree invariant unless followed by anO(N)heapq.heapify(). - Omitting the
seqtie-breaker in heap tuples: Withoutseqin(visible_at, seq, payment_id), equal timestamps fall back to comparingpayment_idstrings alphabetically instead of preserving first-scheduled FIFO order.
Alternative approaches
- FIFO
collections.deque+ separate in-flight min-heap: Put newly submitted payments into adeque, put in-flight leases into a min-heap keyed bydeadline, and at the start ofreceive()move all expired leases (deadline <= now) into thedequebefore popping. This achieves the sameO(log N)complexity, though an expired message's position relative to newly submitted messages depends on whenreceive()happens to run and sweep the heap, whereas a singlevisible_atheap orders them deterministically by exact visibility timestamp. - Blocking
receive(wait_timeout)withthreading.Condition: Wrappingself._lockin athreading.Conditionallows idle workers to sleep until eithersubmit()callsnotify()orself._heap[0]'svisible_atarrives, 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 underself._lockwith the exact same guards asack()(known payment, notcompleted,latest_handle == receipt_handle, andnow < lease_deadline, plusextra_seconds > 0), then setpayment.lease_deadline = now + extra_secondswhile keepinglatest_handleunchanged so the worker's eventualack()still succeeds. Because the earlier(old_deadline, old_seq, payment_id)tuple remains insideself._heap, storepayment.active_seq = self._seqwhenever_schedulepushes the latest deadline, and havereceive()lazily pop and skip any heap tuple whoseseq != payment.active_seqalongsidepayment.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 = 0to_Paymentand increment it each timereceive()grants a lease; whenreceive()pops a visible item whosedelivery_count == max_receives, itsmax_receives-th lease has just expired without anack, so markpayment.dead_lettered = True(rejected byackjust likecompleted), append(payment_id, payment.amount)toself._dlq, andcontinuescanning the heap while retainingpayment_idinsideself._paymentsso 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_idordering and preventing double charges? Partition requests across broker shards byhash(payment_id) % num_partitionsso every lifecycle step for a givenpayment_id(such asauthorize,capture,refund) routes to one shard leader that enforces local deduplication and holds stepk + 1until stepkcompletes 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
- How would you add an `extend_lease(payment_id, receipt_handle, extra_seconds)` heartbeat API so slow workers can push back their expiration deadline?
- What changes are needed to quarantine poison payments into a dead-letter queue once they exceed a maximum delivery-attempt count?
- If traffic outgrows a single process, how would you partition the queue across machines while preserving per-`payment_id` ordering and preventing double charges?
Similar questions
- Dynamic Dynasty Succession Without an Initial Monarch
- DOM Button Click Listener and Event Target
- Catalog Search, Filtering, and Pagination
- Case-Insensitive Ticket Queue Filtering and UI State Debugging
- Library Hold-Queue and Loan Reminder Notification Manager
- Transactional Shopping Cart with Nested Scopes