codejump
MediumPythonJavaScriptTypeScript

System Design — Delayed Job Queue

System DesignPriority QueueScheduling

Jobs that must run at or after a given time: retries with backoff, reminders, email
digests. A worker periodically asks "what is due?".

solve(args, ops) builds new DelayedQueue() and replays ops:

  • schedule(id, runAt) — add job id to run at runAt. If id is already pending, its

time is replaced and it counts as newly scheduled. Returns nothing.

  • cancel(id) — remove a pending job. Returns true if it was pending, else false.
  • poll(now) — remove and return the ids of every pending job with runAt <= now, ordered

by runAt ascending, then by scheduling order (earlier schedule call first).

A sorted array makes poll linear. The scalable structure is a **min-heap keyed by
(runAt, sequence)** with lazy deletion for cancel; any approach that gives the right
answers is accepted here.

Example

schedule("a",10) schedule("b",5) schedule("c",10)
poll(4) → []    poll(5) → ["b"]    poll(10) → ["a","c"]

Sample tests

Test #1Due jobs come out by time then scheduling order
Input: [[],[["schedule","a",10],["schedule","b",5],["schedule","c",10],["poll",4],["poll",5],["poll",10],["poll",100]]]
Output: [null,null,null,[],["b"],["a","c"],[]]
Test #2Cancelling
Input: [[],[["schedule","d",20],["cancel","d"],["cancel","d"],["poll",30]]]
Output: [null,true,false,[]]
Test #3Rescheduling replaces the time
Input: [[],[["schedule","e",50],["schedule","f",50],["schedule","e",40],["poll",45],["poll",50]]]
Output: [null,null,null,["e"],["f"]]