Skip to content
Forward Engineering
Go back

Payment deadlines that keep moving: why I kept the timers in a MySQL ledger

- views

Table of contents

Open Table of contents

0. What if the deadline moved but the old timer still fires?

Let’s follow one unpaid booking. The times are for illustration.

TimeWhat happens
10:00The customer books. The payment deadline is 15:00. A timer is set to fire at 15:00:01
12:00The deadline is extended to 16:00. The timer has to move to 16:00:01
15:00:01If 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

TermMeaning
Payment deadlineThe 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)
TimerOne scheduled task: “check this booking at this time”
LedgerA table that records timers, one row each. The source of truth for what runs when
WorkerA process that takes due timers and runs them. Workers run on several pods at once
LeaseThe period a worker holds a timer as “mine, running”. The worker extends it while running
FencingA 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-onceA delivery mode where a message arrives at least once, possibly more than once

1. Mission and constraints

There were four requirements.

  1. Timers must be changeable. The deadline changes several times after booking.
  2. The same booking must not be cancelled twice automatically. The cancellation on the airline side can’t be undone.
  3. Missing or duplicated notifications must not corrupt the timers. Change notifications come through Kafka, at least once.
  4. Second-level precision is enough. A few minutes late is fine; a few hours is not.

There were constraints too.

ConstraintEffect on the design
Only the backend service writes booking dataThe batch doesn’t change the database directly. It calls the backend’s shared booking-cancellation API
The external airline integration has a low call limitThroughput 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 placeDon’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

CandidateChanging a timerHow runs are recoveredOperational costVerdict
TemporalStrong (timer and signal APIs)Workflow history replayHigh (separate cluster)Rejected
db-schedulerPossible (row update)Heartbeats and recoveryLow (library)Library rejected, pattern adopted
Quartz clusterPossibleBuild it yourselfMediumRejected
ShedLock + @ScheduledNone (it’s a lock)NoneLowRejected
Kubernetes CronJobNone (periodic)NoneLowRejected
Kafka delay and retry topicsNot possibleBuild it on the consumer sideExisting infraUsed only as the notification channel
Redis sorted setEasy (ZREM)Build it yourselfMemory is the source of truthRejected
MySQL ledger + SKIP LOCKEDWrite a new rowLease and fencingExisting databaseChosen

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

CaseShapeSame as this postDifferent
Airbnb Dynein (2019)A DynamoDB schedule store and SQS delivery queues, supports cancelling a scheduled jobCancellation is a core requirement for delayed jobs. Conditional updates prevent duplicate dispatchStuck jobs are dispatched again
Dropbox ATF (2020)Task store, polling, queue, executors, heartbeat claimsLedger, polling, claimsFailures are retried. Cancelling a single task is not described
Slack job queue (2017)Kafka, relay, RedisA durable buffer between accepting and running jobsThe topic is backlog protection, not delayed jobs. Over 1.4 billion jobs on the busiest days
Meta FOQS (2021)Distributed priority queue on sharded MySQLOne MySQL row per item, leases and acksClose 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.

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.

  1. Rows locked by other workers are skipped, not waited on. So several pods take different rows at the same time.
  2. 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.
  3. The taken rows become “running”, get a lease, have their attempt number raised by one, and the transaction commits right away.
  4. 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.
  5. 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 designImplementationWhy it changed
When a lease expires, return the row to “waiting” so another worker retriesWhen a lease expires, close it as “failed” and don’t retryThe 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 decideClose as failed, a person checksThe 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 backendLedger fencing, the cancellation API’s state rejection, and a no-retry policyThe batch only calls the shared cancellation API, and I decided not to change that API’s contract
One timer on the order-level deadlineOne timer per booking, one second after its own deadlineThe 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 fixesNot yetLeft out of the first scope. Kept as a limitation in Section 7
A trial mode that records instead of cancellingReplaced by a per-organization on/off switchA separate trial job verifies the engine, and real cancellations only run for organizations with the switch on
A dedicated outbox table for deadline changesOne more event type in the existing outboxNo new table and no new relay to operate
Redis idempotency keys against duplicate runsRemovedThe 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.

ScenarioSituationResult
baseline (no timer)An unpaid booking past its deadlineNothing cleans it up
S1The first deadline change arrivesOne waiting timer
S2A newer deadline change arrivesThe old waiting row is closed, one new waiting row
S3An old change arrives lateIgnored. Only the newest deadline waits
S4The same change arrives twice (redelivery)Still one timer
S5An old change arrives late after the timer was closed by paymentThe timer does not come back
S6An old and a new change reach two pods at the same timeOne waiting timer, on the new deadline
S7A running timer whose lease has expiredNot run again, closed as failed
S8A worker that lost its claim writes its result lateZero rows. The ledger is unchanged, a warning is left
S9The cancellation went through but the response connection droppedNot sent again, stays failed. One cancellation
S9bThe cancellation went through but the pod waiting for the response died or frozeThe remaining pod closes it as failed on lease expiry. Not sent again, one cancellation
S10One change arrives in an environment with two containers runningExactly one cancellation

6. When to abandon this choice

6.1 Decision matrix

SituationRecommendation
Timers change often, and one database primary handles the throughputA MySQL or PostgreSQL ledger + SKIP LOCKED (this post)
Long, multi-step workflows across several teams, with people to run a clusterA durable execution engine such as Temporal
Timers rarely change and throughput is very highQueue-based delayed jobs (the Dynein approach)
Ledger writes saturate the primaryShard 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 requestsAutomatic retry after lease expiry is fine
The target can’t filter duplicates and the result is irreversibleDon’t retry; give people a path to check

6.2 Self-check

7. Limitations of this post

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

Open source

Design sources

External cases

In this series


Share this post on:

Previous Post
Same cancellation, different events: why I put event classification in one place with an outbox
Next Post
Why You Cannot Simply Add a Second Instance to an In-Memory Pool