Table of contents
Open Table of contents
- 0. What if the deadline moved but the old timer still fires?
- 1. Mission and constraints
- 2. Why a common tool wasn’t enough
- 3. The solution: keep timers as rows in a ledger
- 4. What changed from the design to the implementation
- 5. Verification scenarios
- 6. When to abandon this choice
- 7. Limitations of this post
- 8. FAQ
- 9. Closing
- References
0. What if the deadline moved but the old timer still fires?
Let’s follow one unpaid booking. The times are for illustration.
| Time | What happens |
|---|---|
| 10:00 | The customer books. The payment deadline is 15:00. A timer is set to fire at 15:00:01 |
| 12:00 | The deadline is extended to 16:00. The timer has to move to 16:00:01 |
| 15:00:01 | If the old timer is still there, it fires and cancels the booking, even though the customer could still pay |
That is the problem this post solves. There is a timer whose firing time keeps changing, and when it fires, something irreversible happens. Meanwhile, the notifications saying “the deadline changed” arrive duplicated or out of order.
Without something that cleans up bookings past their deadline, an expiry only shows up when the customer tries to pay. My first thought was “just schedule a job at the deadline.”
0.1 Terms used in this post
| Term | Meaning |
|---|---|
| Payment deadline | The time by which the booking must be paid, or it is not kept. Each booking has its own. Airlines call it the TL (time limit) |
| Timer | One scheduled task: “check this booking at this time” |
| Ledger | A table that records timers, one row each. The source of truth for what runs when |
| Worker | A process that takes due timers and runs them. Workers run on several pods at once |
| Lease | The period a worker holds a timer as “mine, running”. The worker extends it while running |
| Fencing | A way for the storage to reject a late write from an old worker that lost its claim. Here it compares the attempt number (attempt) |
| At-least-once | A delivery mode where a message arrives at least once, possibly more than once |
1. Mission and constraints
There were four requirements.
- Timers must be changeable. The deadline changes several times after booking.
- The same booking must not be cancelled twice automatically. The cancellation on the airline side can’t be undone.
- Missing or duplicated notifications must not corrupt the timers. Change notifications come through Kafka, at least once.
- Second-level precision is enough. A few minutes late is fine; a few hours is not.
There were constraints too.
| Constraint | Effect on the design |
|---|---|
| Only the backend service writes booking data | The batch doesn’t change the database directly. It calls the backend’s shared booking-cancellation API |
| The external airline integration has a low call limit | Throughput targets follow the external limit, not the database |
| There are many customer organizations (workspaces) | Each can be switched on and off, and one busy organization must not hold back the others |
| MySQL, Kafka and an outbox were already in place | Don’t add new parts to operate |
A rough estimate of the average load showed that timer writes were not a reason to rule out the database. I expected the bottleneck to be the external call limit, not the database. I did not measure it (Section 7).
1.1 Three threats to correctness
graph LR
A["[WARN] Change notifications<br/>arrive duplicated or reordered"] --> T["Timer"]
B["[WARN] The deadline changes<br/>again while running"] --> T
T --> C["[WARN] The result is an<br/>irreversible external cancellation"]
These three set most of the decisions in this post.
2. Why a common tool wasn’t enough
2.1 Seven candidates
| Candidate | Changing a timer | How runs are recovered | Operational cost | Verdict |
|---|---|---|---|---|
| Temporal | Strong (timer and signal APIs) | Workflow history replay | High (separate cluster) | Rejected |
| db-scheduler | Possible (row update) | Heartbeats and recovery | Low (library) | Library rejected, pattern adopted |
| Quartz cluster | Possible | Build it yourself | Medium | Rejected |
ShedLock + @Scheduled | None (it’s a lock) | None | Low | Rejected |
| Kubernetes CronJob | None (periodic) | None | Low | Rejected |
| Kafka delay and retry topics | Not possible | Build it on the consumer side | Existing infra | Used only as the notification channel |
| Redis sorted set | Easy (ZREM) | Build it yourself | Memory is the source of truth | Rejected |
MySQL ledger + SKIP LOCKED | Write a new row | Lease and fencing | Existing database | Chosen |
Whatever tool you pick, the responsibility for not cancelling twice stays with you. A tool only solves “how do we bring a dead run back”. Whether an external call can be sent again depends on the contract of the thing you call. So there is no column for it here; Section 3.4 covers it.
2.2 Why each candidate was dropped
Temporal fit this problem best. Durable timers, cancellation and signals, and an execution history UI are all there. I dropped it for operational cost, not features. Temporal is a separate cluster of Frontend, History and Matching services plus storage, and some settings, such as the number of history shards, are hard to change once chosen. At our scale and with our people, running that cluster would cost more than the problem itself.
db-scheduler is the candidate I borrowed from most. It keeps jobs in one table, picks them up by polling, signals liveness with heartbeats, and recovers dead runs. On MySQL 8 it claims jobs with SKIP LOCKED. I didn’t use the library itself because its table schema is fixed. Adding customer organizations, timer versions and state history would have meant changing it. So I took the pattern instead of the library.
Why Quartz, ShedLock, CronJob, Kafka and Redis were dropped (expand)
In cluster mode, Quartz serializes the step where nodes acquire triggers through a row lock in the QRTZ_LOCKS table. That is fine for a few dozen periodic jobs. But with one timer per booking, the count grows a lot, and I judged that this single row lock could become the bottleneck.
ShedLock’s README says it plainly: it is not a distributed scheduler, “it’s just a lock”, and if you need a distributed scheduler you should use another project such as db-scheduler. Its behavior section explains that while one node holds the lock, the same task on other nodes is skipped, not blocked. If the JVM crashes mid-run, the lock is simply released after lockAtMostFor. That is as far as the recovery the README describes goes; nothing runs that execution again or keeps a history of it.
Kubernetes CronJob is for periodic work. The default concurrencyPolicy is Allow, so a new run can overlap one that hasn’t finished, and it can’t express a different firing time for every booking.
Kafka delay topics took the longest to rule out, because Kafka was already there. But there is no per-message delay, and above all a published message can’t be cancelled. Every deadline change would need an “ignore the previous message” marker stored somewhere, and that place ends up being the database. So I made the database the source of truth from the start and used Kafka only as the channel that carries “the deadline changed”.
A Redis sorted set makes popping and cancelling easy if the firing time is the score. But then an in-memory store becomes the source of truth for timers, and atomic pops and recovery after a worker dies mid-pop are yours to build.
2.3 Cases that solved the same kind of problem at larger scale
| Case | Shape | Same as this post | Different |
|---|---|---|---|
| Airbnb Dynein (2019) | A DynamoDB schedule store and SQS delivery queues, supports cancelling a scheduled job | Cancellation is a core requirement for delayed jobs. Conditional updates prevent duplicate dispatch | Stuck jobs are dispatched again |
| Dropbox ATF (2020) | Task store, polling, queue, executors, heartbeat claims | Ledger, polling, claims | Failures are retried. Cancelling a single task is not described |
| Slack job queue (2017) | Kafka, relay, Redis | A durable buffer between accepting and running jobs | The topic is backlog protection, not delayed jobs. Over 1.4 billion jobs on the busiest days |
| Meta FOQS (2021) | Distributed priority queue on sharded MySQL | One MySQL row per item, leases and acks | Close to one trillion items a day, a choice of at-least-once or at-most-once |
None of the four public write-ups promises “exactly once”. Dynein and ATF choose at-least-once and require the executing side to be idempotent. FOQS lets you choose between at-least-once and at-most-once, and Slack states that there is a window where an accepted job can be lost. That observation set the direction: don’t try to get “exactly once” from the scheduler; handle duplicates in the ledger and in the execution policy.
3. The solution: keep timers as rows in a ledger
Here is the whole flow.
graph LR
BE["Backend<br/>(booking data)"] -->|"record the deadline change"| OB[("outbox")]
OB -->|"the deadline changed"| K["Kafka"]
K --> W1["Batch: register timers"]
W1 -->|"write a new row, close the old waiting row"| L[("Timer ledger")]
L -->|"take rows whose time has come"| W2["Batch: worker"]
W2 -->|"shared booking-cancellation API"| BE
W2 -->|"record the result"| L
3.1 When the deadline changes, write a new row
Just updating the firing time of the existing row looks simple. But if a worker is running that row at that moment, the change and the run overwrite each other. So a change is written as a new row.
timer(booking=B1, version=101, fire_at=15:00:01, status=closed(superseded))
timer(booking=B1, version=205, fire_at=16:00:01, status=waiting)
There are five rules.
- There is one timer per booking. It fires one second after that booking’s own payment deadline, because payment is still allowed during the deadline’s second.
- A row’s version is the outbox row number of the change notification. Newer changes have larger numbers.
- When a new version with a different deadline arrives, the booking’s waiting row is closed and a new row is written. A row that is already running is left alone.
- A new version with the same deadline does not create a new row. Otherwise the same booking would get the cancellation call once more.
- An old version that arrives late is ignored. When a booking is paid and no longer needs a timer, the row is not deleted; a “no timer needed” record is left instead. That way an even older notification arriving late can’t bring the timer back.
So that two registrations for the same booking can’t both leave a waiting row, registration locks that booking’s range of rows while it writes.
stateDiagram-v2
[*] --> Waiting: registered from a deadline change
Waiting --> Closed: a new version with a different deadline<br/>or paid, no timer needed
Waiting --> Running: due, taken by a worker
Running --> Succeeded: cancelled, nothing to do,<br/>or staff check needed
Running --> Failed: error, unknown result, lease expired
Failed --> [*]: (operating procedure) a person checks
Succeeded --> [*]
Closed --> [*]
3.2 Workers split rows with SKIP LOCKED
SELECT id, attempt FROM timer
WHERE status = 'READY' AND fire_at <= UNIX_TIMESTAMP()
ORDER BY fire_at
LIMIT :free_slots
FOR UPDATE SKIP LOCKED;
This query is shortened for explanation. Here is what happens behind that one line, in order.
- Rows locked by other workers are skipped, not waited on. So several pods take different rows at the same time.
- A worker takes only as many rows as it has free execution slots. If it took more, their leases would run out while they waited.
- The taken rows become “running”, get a lease, have their attempt number raised by one, and the transaction commits right away.
- The actual cancellation call happens outside the transaction. Holding database locks and connections through an external call would stall the database whenever the external side slows down.
- While running, the worker extends the lease periodically, before it runs out. With the default settings, that is every third of the lease.
Time comparisons such as “is this due?” and “has the lease expired?” all use the database’s UNIX_TIMESTAMP(). If each pod used its own slightly different clock, those decisions could disagree. The firing time itself comes from the payment deadline carried in the notification.
3.3 Leases and fencing stop the late worker
If a worker fails to extend its lease because of a long GC pause or a network delay, other pods consider the claim over. But that worker may actually be alive and try to write its result later.
Writing a run’s result and extending a lease both carry the condition WHERE id = ? AND attempt = ? AND status = RUNNING. The attempt number held by a worker that lost its claim is stale, or the row’s state has changed, so the late write changes zero rows. The idea comes from Martin Kleppmann’s post on distributed locking: a lock with an expiry can be lost without the holder knowing, so the storage has to reject late writes with a monotonically increasing number.
This fencing only protects writes to the ledger. If the old worker had already called the cancellation API before losing its claim, that cancellation has already happened outside the ledger. So when a late write changes zero rows, the result is dropped and a warning is left for a person to check.
3.4 A cancellation with an unknown result is not sent again
When a cancellation call times out, you don’t know whether it went through. Sending it again puts a second request on a booking that may already be cancelled. That would be fine for work that only changes a booking’s state, but the cancellation on the airline side can’t be undone.
So a timer makes one attempt. An error, a timeout and an expired lease all close it as “failed”, and it is not run again automatically. A person checks the real booking state and cleans up.
sequenceDiagram
participant W as Worker
participant API as Shared cancellation API
participant L as Timer ledger
W->>API: cancel the booking
API-->>API: cancellation done
API--xW: [Problem] response lost (connection drop, timeout)
W->>L: record as failed (result unknown)
Note over W,L: not sent again automatically
Note over L: ledger says "failed", the booking is "cancelled"<br/>a person checks and cleans up
There is one more guard against duplicates. The shared cancellation API rejects requests for bookings that are already cancelled or can’t be cancelled. Depending on the reason, the worker records the rejection as “nothing to do” or “staff check needed”. Both are finished runs, not failures.
4. What changed from the design to the implementation
The first version of this post was a design record written before the implementation. Here is what changed while building it.
| First design | Implementation | Why it changed |
|---|---|---|
| When a lease expires, return the row to “waiting” so another worker retries | When a lease expires, close it as “failed” and don’t retry | The worker that lost its claim may already have sent the cancellation. A retry would be a second cancellation |
| After a timeout, query the real state and then decide | Close as failed, a person checks | The query is another external call with its own cost and time, and reading its result also needed judgment |
| Put the last line of defence in a conditional update in the backend | Ledger fencing, the cancellation API’s state rejection, and a no-retry policy | The batch only calls the shared cancellation API, and I decided not to change that API’s contract |
| One timer on the order-level deadline | One timer per booking, one second after its own deadline | The order’s deadline can be the earliest of several bookings’ deadlines, or one that has already passed |
| A reconciliation job that catches missed notifications, plus a metric for its fixes | Not yet | Left out of the first scope. Kept as a limitation in Section 7 |
| A trial mode that records instead of cancelling | Replaced by a per-organization on/off switch | A separate trial job verifies the engine, and real cancellations only run for organizations with the switch on |
| A dedicated outbox table for deadline changes | One more event type in the existing outbox | No new table and no new relay to operate |
| Redis idempotency keys against duplicate runs | Removed | The ledger’s row-range lock and fencing already keep a target from having two waiting rows |
The biggest change is the first row. At first I copied db-scheduler’s approach as is: “recover dead runs and run them again.” But the result of this job is an external cancellation that can’t be undone. A retry is only safe if the target filters duplicate requests, and that contract was not changed this time. So I chose a person’s check over automatic retries. Failures may pile up, but a failed timer never sends the cancellation again by itself.
5. Verification scenarios
These tests start MySQL and Kafka containers and replace the backend with a fake server. S9b and S10 run on two containers started from the batch image, so the processes and the network are real. All scenarios from S1 to S10 passed.
| Scenario | Situation | Result |
|---|---|---|
| baseline (no timer) | An unpaid booking past its deadline | Nothing cleans it up |
| S1 | The first deadline change arrives | One waiting timer |
| S2 | A newer deadline change arrives | The old waiting row is closed, one new waiting row |
| S3 | An old change arrives late | Ignored. Only the newest deadline waits |
| S4 | The same change arrives twice (redelivery) | Still one timer |
| S5 | An old change arrives late after the timer was closed by payment | The timer does not come back |
| S6 | An old and a new change reach two pods at the same time | One waiting timer, on the new deadline |
| S7 | A running timer whose lease has expired | Not run again, closed as failed |
| S8 | A worker that lost its claim writes its result late | Zero rows. The ledger is unchanged, a warning is left |
| S9 | The cancellation went through but the response connection dropped | Not sent again, stays failed. One cancellation |
| S9b | The cancellation went through but the pod waiting for the response died or froze | The remaining pod closes it as failed on lease expiry. Not sent again, one cancellation |
| S10 | One change arrives in an environment with two containers running | Exactly one cancellation |
6. When to abandon this choice
6.1 Decision matrix
| Situation | Recommendation |
|---|---|
| Timers change often, and one database primary handles the throughput | A MySQL or PostgreSQL ledger + SKIP LOCKED (this post) |
| Long, multi-step workflows across several teams, with people to run a cluster | A durable execution engine such as Temporal |
| Timers rarely change and throughput is very high | Queue-based delayed jobs (the Dynein approach) |
| Ledger writes saturate the primary | Shard the ledger (the FOQS approach) or buffer in front with a queue |
| A handful of periodic jobs | @Scheduled + ShedLock, or a CronJob |
| The target filters duplicate requests | Automatic retry after lease expiry is fine |
| The target can’t filter duplicates and the result is irreversible | Don’t retry; give people a path to check |
6.2 Self-check
- I counted changes and cancellations per timer registration. The more changes, the more a ledger beats a queue
- I estimated writes per second from timers per day and writes per timer, and compared it with the primary’s headroom
- I checked whether the bottleneck is the database or the external call limit
- I checked whether the result can be undone, and whether the target filters duplicate requests
- There is a record that stops a late old change from bringing a timer back
- I checked whether anyone will operate a new cluster
7. Limitations of this post
- There are no production numbers. Throughput, the execution delay distribution and the point where lock waits start to bend were not measured.
- There is no reconciliation job yet to catch missed notifications. If a notification itself is lost, a timer can stay at the old time.
- A timer that is already running when the deadline changes runs to the end. If the new timer then runs, a second cancellation request can reach the same booking, and the cancellation API’s state rejection is what stops it.
- The ledger keeps the waiting timer on the newest deadline it has received, but if a change notification is late, the ledger itself believes the old deadline is the latest. To cover that case too, the target would have to check the deadline again at run time.
- Runs closed as failed need a person to check them. More failures mean more work for people.
- The scenarios in Section 5 test specific cases. They don’t prove every combination of faults.
8. FAQ
Q. Couldn’t you choose Temporal for the same problem?
You could. The reasons are sound: delayed queue messages are hard to cancel, and building it on polling means writing retries and locking yourself. I solved the first by writing new ledger rows and the second with the patterns proven in db-scheduler. With a different scale and more people to run infrastructure, I might reach the same conclusion.
Q. Isn’t polling a burden on the database?
With an index on state, organization and firing time, and taking only as many rows as there are free slots, I judged the load to be small. Finished rows do grow the index, so a retention period and a cleanup policy are needed. That is something to check together with throughput measurements.
Q. You already run Kafka. Why not use it for the timers?
Because a published message can’t be cancelled, and in a problem where the deadline moves, changes are common. Kafka carries “it changed”; the ledger owns “when to run”.
Q. Without retries, won’t failures pile up?
They can. That is the intended cost. Resending a cancellation with an unknown result would reduce failures, but a second cancellation could reach the same booking. For irreversible work, I judged one failure that a person looks at to be better than a wrong second cancellation.
9. Closing
The first question was “can’t we just schedule one job at the deadline?” The single observation that the timer moves removed half of the candidates. Most of the remaining decisions were about where to stop duplicates. In the ledger, new-row writes and fencing stop them; in execution, the policy of not resending does.
The next post picks up after this batch cancels a booking. It covers the problem of telling the receiving side “expired” for what is, in the data, the same “cancelled”.
References
Official documentation
- MySQL 8.0 Reference Manual: Locking Reads (NOWAIT, SKIP LOCKED)
- Kubernetes CronJob: concurrencyPolicy
- Temporal Documentation
- Quartz Scheduler Documentation
Open source
- db-scheduler: persistent cluster-friendly scheduler for Java
- ShedLock: “ShedLock is not a distributed scheduler”
Design sources
External cases
- Airbnb: Dynein, Building a Distributed Delayed Job Queueing System
- Dropbox: Asynchronous Task Scheduling at Dropbox
- Slack: Scaling Slack’s Job Queue
- Meta: FOQS, Scaling a distributed priority queue