codejump
MediumPythonJavaScriptTypeScript

System Design — Queue With Visibility Timeout

System DesignQueueDistributed Systems

How SQS-style queues survive crashing workers. A consumer that receives a message does not
remove it: the message is only hidden for a while. If the consumer deletes it in time the
work is done; if it crashes, the message reappears and another worker gets it.
That is *at-least-once* delivery.

solve(args, ops) builds new VisibilityQueue(timeout) — args = [timeout] — and replays
ops:

  • send(body, now) — enqueue a message and return its id (1, 2, 3, … in send order).
  • receive(now) — return [id, body] of the visible message with the smallest id, and

hide it until now + timeout; return null if no message is visible.

  • delete(id) — remove the message permanently (even while hidden). Returns true if it

existed, else false.

A message is visible when now >= hiddenUntil (new messages are visible at once). A
redelivered message keeps its id, so it is served before newer messages.

Example (timeout = 10)

send("a",0) → 1   send("b",1) → 2   receive(2) → [1,"a"]   receive(4) → [2,"b"]   receive(5) → null
receive(12) → [1,"a"]      // the first lease expired

Sample tests

Test #1Lease expiry and deletion
Input: [[10],[["send","a",0],["send","b",1],["receive",2],["receive",3],["receive",4],["receive",12],["delete",1],["receive",13],["delete",1],["receive",14]]]
Output: [1,2,[1,"a"],[2,"b"],null,[1,"a"],true,[2,"b"],false,null]
Test #2Empty queue
Input: [[5],[["receive",0]]]
Output: [null]
Test #3Visible again exactly at now + timeout
Input: [[5],[["send","x",0],["receive",0],["receive",4],["receive",5]]]
Output: [1,[1,"x"],null,[1,"x"]]