Design Problem: A Distributed Scheduler, Where a Million Delayed Tasks Must Each Run Only Once, at the Right Time
System Design series · Part 9 Design problems (7 of 7)
- Design Problem: A URL Shortener, from Estimates and Code Generation to Phishing Abuse
- Design Problem: A News Feed, Push vs Pull, and the Celebrity Problem
- Design Problem: A Chat System, Where Direct Messages and a 50,000-Person Live Chat Room Are Two Different Problems
- Design Problem: Flash Sale Ticketing, and How Much Each Layer Must Turn Away When 500,000 People Chase 10,000 Seats
- Design Problem: A Notification System Where Verification Codes Cannot Wait Behind 10 Million Newsletters
- Design Problem: A Leaderboard, with Ranks for Ten Million Members, Who Comes First in a Tie, and Time Decay for Trending Talks
- Design Problem: A Distributed Scheduler, Where a Million Delayed Tasks Must Each Run Only Once, at the Right Time
System Design series Part 9-7 | Previous: Leaderboard | Next: Testing at Scale | Series map
Read first: Part 4-7 Distributed Locks and Fencing Tokens.
Scenario and problem
The earlier problems left behind a list of “do it later” work:
| Task | Volume | Timing requirement |
|---|---|---|
| Payment deadline: cancel the order and release its seats if it is not paid within 10 minutes (Flash Sale Ticketing) | 50,000 a day normally; during a flash sale, 10,000 come due in the same minute | A few seconds late is fine; it must not be skipped, and must not run twice |
| Reminder 15 minutes before a talk starts (Notification System) | One per talk, about 2,000 a day | Within 1 minute either way |
| Marketing push notifications sent only after quiet hours end | Up to 1 million a day, all originally due at 08:00 | Any time between 08:00 and 08:30 |
| Recurring jobs: daily settlement, merging the trending leaderboard every minute (Leaderboard) | A few dozen | Depends on the job |
The Distributed Locks and Fencing Tokens post used ShedLock to solve “only one machine runs a given cron job”. This problem is a different one: hundreds of thousands to over a million tasks, each with its own due time, have to be spread across several machines, picked up by another machine when one crashes, and each task’s effect must happen only once.
Scale estimate
| Item | Estimate |
|---|---|
| Tasks waiting at the same time | About 1 million rows |
| Normal rate of tasks coming due | Dozens a second |
| Peak | The 1 million push notifications at 08:00; spread over 30 minutes with jitter → about 560 a second |
| Run time of a single task | 10 to 50 milliseconds (one or two database writes, or sending one message) |
- Work for laterPayment deadlines, reminders before a talk starts, push notifications after quiet hours end, daily settlement. About 1 million task rows are waiting at the same time, each with its own due time.
- Spread across machinesTasks that come due have to be spread across several machines, normally dozens a second.
- A machine crashesA machine crashes halfway through. The tasks it was holding have to be taken over by another machine; they cannot be skipped.
- The effect happens only onceAn order not paid within 10 minutes has to be canceled and its seats released. A few seconds late is fine, but it must not happen twice. If both the machine that took over and the machine that woke up cancel it, the seats are released twice.
- 1 million pushes at 08:00Marketing push notifications sent after quiet hours end were all originally due at 08:00; even spread over 30 minutes with jitter, that is still about 560 a second.
The simplest approach and its limits
@Scheduled on one machine, scanning for due tasks once a minute and running them one by one:
- Single point of failure: when this machine crashes or is being deployed, every task stops; adding ShedLock lets several machines take turns, but still only one of them is working at any moment
- Throughput: one machine running tasks in sequence at 20 milliseconds each does 50 a second. The 1 million at 08:00 take 5.5 hours to finish
- Precision: scanning once a minute, a task can be up to 1 minute late
- Long tasks block: one stuck task makes every task after it wait
Core mechanism
Tasks live in the database, in the same transaction as the business data
When you create an order, write a “check payment in 10 minutes” task row in the same transaction. If the order is created, the task is guaranteed to exist; if the order rolls back, the task does not exist either. This is the same idea as the outbox in the Sagas and the Outbox Pattern post: a local transaction keeps “the business state” and “what to do later” consistent.
A task row holds only a reference (the order ID), not the data itself. Read the latest state when the task runs, because anything can change in 10 minutes.
Several machines claim batches: FOR UPDATE SKIP LOCKED
Every scheduler machine runs this once a second:
SELECT id, task_type, payload, attempts FROM scheduled_task
WHERE status = 'PENDING' AND run_at <= NOW(3)
ORDER BY run_at
LIMIT 200
FOR UPDATE SKIP LOCKED;SKIP LOCKED (MySQL 8.0 and later) makes the query skip rows that other transactions have already locked instead of waiting for them. Three machines running it at the same time each get 200 tasks that do not overlap, and they do not block each other. After claiming the tasks, in the same transaction, set their status to RUNNING, write the lease deadline, commit, and then run the tasks outside the transaction.
This makes the scheduler machines stateless: for more throughput, add a few more; any one of them crashing does not affect the others (Vertical Scaling, Horizontal Scaling, and Stateless Services).
Leases and claim IDs
A machine can crash while running a task, and the task would then stay in RUNNING forever. So when claiming, also write:
- Lease deadline (
lease_until): for example 5 minutes. A cleanup job sets tasks that are stillRUNNINGafter the deadline back toPENDING, so another machine can claim them again - Claim ID (
claim_id): every claim generates a new random value. The completion update includesclaim_idin its condition. If this task’s lease has expired and another machine has claimed it again, the original machine’s completion update affects 0 rows and does not overwrite the other machine’s state
A claim ID does the same job as the fencing token in the Distributed Locks and Fencing Tokens post: the party that “thinks it still holds the task, but has actually expired” cannot change the state. But it protects only the task row itself; the task’s effect (canceling an order, sending a notification) can still happen twice, so handlers must be idempotent.
The handler checks the state again itself
When the payment deadline arrives, the handler does not cancel the order outright. Instead it runs:
UPDATE ticket_order SET status = 'EXPIRED'
WHERE id = :orderId AND status = 'PENDING_PAYMENT';- The member pays successfully at 9 minutes 59 seconds: the order is already
PAID, the update affects 0 rows, and nothing happens - The same task runs twice: the second time, the order is already
EXPIRED, and the update affects 0 rows - Seats are released only when the update affected 1 row
The scheduler is responsible only for “reminding the handler to check at this point in time”; correctness comes from the handler’s conditional update. When a payment succeeds, you can also mark the task as CANCELLED along the way, but that only saves one useless run; correctness does not depend on it.
One task, or ten thousand
There are two ways to set up talk reminders:
- One task per registrant: a talk with 10,000 people means 10,000 tasks, all due in the same second
- One task per talk: when it comes due, the handler sends “this talk’s registrants” to the notification system in batches
The second way has several orders of magnitude fewer tasks, and the peak of tasks coming due disappears too. The fan-out is handed to a downstream queue, which controls the pace. The unit of scheduling should be the business event, not the recipient.
Tasks due all at once: add jitter
Quiet hours end at 08:00, so the run_at of all 1 million push notifications is 08:00:00. At that moment the database has to return a huge number of due rows, and the downstream push provider takes a sudden spike too.
Add random jitter to run_at when you create the task: 08:00 plus a random value between 0 and 30 minutes. This is the same principle as the retry jitter in the Timeouts, Retries, Backoff, and Jitter post: spread out things that would otherwise happen at the same moment. Add jitter only to tasks that are allowed to run late, not to payment deadlines.
Precision and the polling interval
Polling once a second, a task usually runs within 1 to 2 seconds of coming due. That is enough for every task above.
When you need millisecond precision (for example a countdown in a game, or the end time of a live auction), querying the database once a second is not enough. The common approach has two layers: the database stores long-term tasks, and tasks close to their due time are loaded into an in-memory timing wheel (hashed timing wheel). A timing wheel is a circular array in which each slot stands for one unit of time; inserting and firing are both O(1). Kafka uses one to manage large numbers of request timeouts, and Netty’s HashedWheelTimer has the same structure. The in-memory part is lost when the machine restarts, so the database remains the source of truth.
Recurring jobs and missed runs
Take the daily settlement at 03:00: if the scheduler service is down from 02:00 to 05:00, what should happen when it comes back? You have to decide this in advance, job by job:
| Policy for missed runs | Suited to |
|---|---|
| Catch up once | Daily settlement: a missed settlement must run, but only once |
| Catch up every missed run | An hourly report, where each report covers a different time range |
| Skip | Merging the trending leaderboard every minute: it runs again the next minute |
In practice, each time a recurring job finishes, it computes the next run time and writes a new task row. The missed-run policy is simply the rule for “computing the next time”. Give cron expressions an explicit time zone; in time zones with daylight saving time, times between 02:00 and 03:00 may not exist or may occur twice, so keep important jobs out of that window.
Observability
- Lag: how long ago the oldest task that is due but still
PENDINGcame due. This is the most direct indicator of whether the scheduler is healthy - Stuck tasks: the number of tasks still
RUNNINGpast their lease - Failures: the number of tasks that went to
DEAD, with separate alerts per task type
Comparing options
| Option | Pros | Cost | Suited to |
|---|---|---|---|
Database task table + SKIP LOCKED |
Same transaction as the business data; no new component | Polling load; precision of about 1 second | Hundreds to thousands of tasks a second |
| Redis sorted set (the score is the due time) | High precision, fast | Weak durability; cannot be kept consistent with database transactions | Short-lived tasks that can be rebuilt |
| Delayed delivery in a message queue | No polling | The maximum delay and support for canceling depend on the product | Fixed, short delays |
| Quartz in cluster mode | Mature, supports recurring jobs | Coordinates through database row locks, so lock contention becomes noticeable at high task volume; requires the nodes’ clocks to be in sync | Mostly recurring jobs, and not many of them |
| A cloud scheduling service | Nothing to operate | Cost and vendor lock-in; cannot be kept consistent with database transactions | You are already on that cloud platform |
The talk platform picks the database task table: the task volume is in the range of hundreds a second, and the most important task, the payment deadline, must be created in the same transaction as the order. The Java ecosystem also has libraries that take the same approach (db-scheduler, for example), so you do not have to write it yourself; it is written out here to show what each column does.
In Java
1. The task table
CREATE TABLE scheduled_task (
id BIGINT PRIMARY KEY,
task_type VARCHAR(64) NOT NULL, -- PAYMENT_DEADLINE, LECTURE_REMINDER, NOTIFICATION_RELEASE
dedup_key VARCHAR(200) NOT NULL, -- e.g. PAYMENT_DEADLINE:order:98765
payload JSON NOT NULL, -- IDs only, no personal data
run_at TIMESTAMP(3) NOT NULL,
status VARCHAR(16) NOT NULL, -- PENDING, RUNNING, DONE, CANCELLED, DEAD
attempts INT NOT NULL DEFAULT 0,
claim_id BINARY(16) NULL,
lease_until TIMESTAMP(3) NULL,
created_by VARCHAR(64) NOT NULL, -- the service or member that created the task, for auditing and the authorization check at run time
UNIQUE KEY uk_dedup (dedup_key),
KEY idx_due (status, run_at),
KEY idx_lease (status, lease_until)
);idx_due makes the claim query scan only the due PENDING rows; SKIP LOCKED on a query without a suitable index locks and skips a large number of unrelated rows.
2. Scheduling and canceling
@Service
public class DelayedTasks {
private final JdbcClient jdbc;
private final IdGenerator ids;
public DelayedTasks(JdbcClient jdbc, IdGenerator ids) {
this.jdbc = jdbc;
this.ids = ids;
}
/** Must be called inside the business transaction: the task commits or rolls back together with the business data. */
@Transactional(propagation = Propagation.MANDATORY)
public void schedule(String type, String dedupKey, String payloadJson, Instant runAt, String createdBy) {
try {
jdbc.sql("""
INSERT INTO scheduled_task (id, task_type, dedup_key, payload, run_at, status, created_by)
VALUES (:id, :type, :dedup, :payload, :runAt, 'PENDING', :createdBy)
""")
.param("id", ids.next()).param("type", type).param("dedup", dedupKey)
.param("payload", payloadJson).param("runAt", Timestamp.from(runAt))
.param("createdBy", createdBy)
.update();
} catch (DuplicateKeyException e) {
// this business event is already scheduled; skip it
}
}
/** Only saves one useless run; even if the cancel misses, the handler checks the state again. */
public void cancel(String dedupKey) {
jdbc.sql("UPDATE scheduled_task SET status = 'CANCELLED' WHERE dedup_key = :k AND status = 'PENDING'")
.param("k", dedupKey).update();
}
/** For tasks that may run late: add a random delay between 0 and maxJitter. */
public static Instant withJitter(Instant runAt, Duration maxJitter) {
return runAt.plusMillis(ThreadLocalRandom.current().nextLong(maxJitter.toMillis() + 1));
}
}When a flash sale order is created (OrderCreator in Flash Sale Ticketing), call schedule("PAYMENT_DEADLINE", "PAYMENT_DEADLINE:order:" + orderId, ..., now + 10 minutes, "ticketing-service") in the same transaction.
3. Claiming and running
@Component
public class TaskPoller {
private static final int BATCH = 200;
private static final int MAX_ATTEMPTS = 8;
private final JdbcClient jdbc;
private final TransactionTemplate tx;
private final Map<String, TaskHandler> handlers;
private final ExecutorService workers = Executors.newFixedThreadPool(32);
public TaskPoller(JdbcClient jdbc, TransactionTemplate tx, List<TaskHandler> handlers) {
this.jdbc = jdbc;
this.tx = tx;
this.handlers = handlers.stream().collect(Collectors.toUnmodifiableMap(TaskHandler::type, h -> h));
}
@Scheduled(fixedDelay = 1000)
public void poll() throws InterruptedException {
List<Task> claimed;
do {
byte[] claimId = UuidBytes.random();
claimed = claim(claimId);
List<Callable<Void>> jobs = new ArrayList<>();
for (Task t : claimed) {
jobs.add(() -> {
run(t, claimId);
return null;
});
}
workers.invokeAll(jobs); // finish this batch before claiming the next, so concurrency is capped
} while (claimed.size() == BATCH); // keep going while there is a backlog; do not wait for the next second
}
private List<Task> claim(byte[] claimId) {
return tx.execute(status -> {
List<Task> due = jdbc.sql("""
SELECT id, task_type, payload, attempts FROM scheduled_task
WHERE status = 'PENDING' AND run_at <= NOW(3)
ORDER BY run_at
LIMIT :batch
FOR UPDATE SKIP LOCKED
""")
.param("batch", BATCH)
.query(Task.class)
.list();
if (!due.isEmpty()) {
jdbc.sql("""
UPDATE scheduled_task
SET status = 'RUNNING', claim_id = :claim, lease_until = NOW(3) + INTERVAL 5 MINUTE
WHERE id IN (:ids)
""")
.param("claim", claimId)
.param("ids", due.stream().map(Task::id).toList())
.update();
}
return due;
});
}
private void run(Task t, byte[] claimId) {
TaskHandler handler = handlers.get(t.taskType());
if (handler == null || t.attempts() >= MAX_ATTEMPTS) {
finish(t.id(), claimId, "DEAD"); // unknown types are not run; tasks out of retries go to a human
return;
}
try {
handler.handle(t);
finish(t.id(), claimId, "DONE");
} catch (RuntimeException e) {
long delaySeconds = Math.min(3600, 1L << (t.attempts() + 2)); // 4, 8, 16... seconds, capped at 1 hour
jdbc.sql("""
UPDATE scheduled_task
SET status = 'PENDING', attempts = attempts + 1, run_at = NOW(3) + INTERVAL :delay SECOND
WHERE id = :id AND claim_id = :claim AND status = 'RUNNING'
""")
.param("delay", delaySeconds).param("id", t.id()).param("claim", claimId)
.update();
}
}
private void finish(long id, byte[] claimId, String status) {
// A claim_id mismatch means the lease expired and another machine claimed the task again: 0 rows affected, the other machine's state is not overwritten
jdbc.sql("UPDATE scheduled_task SET status = :s WHERE id = :id AND claim_id = :claim AND status = 'RUNNING'")
.param("s", status).param("id", id).param("claim", claimId)
.update();
}
@Scheduled(fixedDelay = 60_000)
public void reclaimExpiredLeases() {
jdbc.sql("""
UPDATE scheduled_task SET status = 'PENDING', attempts = attempts + 1, claim_id = NULL
WHERE status = 'RUNNING' AND lease_until < NOW(3)
""").update();
}
}- Every machine runs
poll()and relies onSKIP LOCKEDto divide the tasks, so no leader election is needed - Spring Boot’s scheduler has only one thread when virtual threads are not enabled.
poll()keeps looping while there is a backlog, so the other@Scheduledmethods in the same application (includingreclaimExpiredLeasesbelow) never get a turn. Setspring.task.scheduling.pool.size, or enablespring.threads.virtual.enabled - Always compare times with the database’s
NOW(3), never with each machine’s own clock - The claim transaction contains only the
SELECTand theUPDATE, and commits before the tasks run, so the locks are held for only a few milliseconds - When a handler throws an exception, the task is retried with exponential backoff; reclaims after an expired lease also count toward
attempts, so a task that crashes the machine every time eventually ends up inDEADinstead of looping forever reclaimExpiredLeasesruns on every machine; running it more than once gives the same result
4. Handlers
public interface TaskHandler {
String type();
void handle(Task task);
}
@Component
public class PaymentDeadlineHandler implements TaskHandler {
private final JdbcClient jdbc;
private final SeatRelease seatRelease;
public PaymentDeadlineHandler(JdbcClient jdbc, SeatRelease seatRelease) {
this.jdbc = jdbc;
this.seatRelease = seatRelease;
}
@Override
public String type() {
return "PAYMENT_DEADLINE";
}
@Override
@Transactional
public void handle(Task task) {
long orderId = task.longParam("orderId");
int expired = jdbc.sql("UPDATE ticket_order SET status = 'EXPIRED' WHERE id = :id AND status = 'PENDING_PAYMENT'")
.param("id", orderId).update();
if (expired == 1) {
seatRelease.release(orderId); // add the seats back in the database, and tell Redis through the outbox to add the stock back
}
}
}The code above is written from the official documentation for Spring Boot 4.1, Spring Framework 7 (
JdbcClient,TransactionTemplate,@Scheduled), MySQL 8.4 (SKIP LOCKED), and Java 21, and has not been compiled or run.IdGenerator,UuidBytes,Task, andSeatReleaseare illustrative components.
Pitfalls and gotchas
- The task and the business data are not in the same transaction: the order is created, but the payment deadline task was never written, so the seats are never released
- The handler trusts the task: it cancels the order outright without checking whether the member has already paid
- Not checking the claim ID on completion: after the lease expires, the original machine marks a task that another machine is processing as done
- Using the application server’s clock to decide what is due: clock skew between machines makes tasks run early or late
- One task per recipient: one talk creates ten thousand tasks that come due at the same moment
- No jitter on tasks that are allowed to run late: the spike at exactly 08:00 overwhelms downstream services
- No missed-run policy decided: after the scheduler recovers, the daily settlement runs three times, or not at all
- Running tasks inside the claim transaction: the row locks and the database connection are held until the whole batch is done; if one task fails, the whole batch’s state rolls back with it
- No
DEADstatus: a task that always fails is retried every few seconds, forever
Threat model
| STRIDE | Threat | On the talk platform | Defense |
|---|---|---|---|
| Spoofing | Identity at delayed run time | A member schedules “publish this post at 9 tomorrow”, but tonight the account is suspended, or the post is changed to someone else’s talk page; when the task comes due, it runs with system privileges | The task records its creator (created_by), and at run time it checks permissions again as the creator instead of running directly with system privileges (8-3) |
| Tampering | Modifying task rows; insecure deserialization | Someone who can write to the database changes the payload to a different order; task content is stored with Java serialization, and once tampered with, deserializing it runs arbitrary code |
Handlers check the business state again; payloads use only JSON with a fixed set of fields, never Java serialization, and the payload never decides which class to create; task types map to handlers through an allowlist |
| Repudiation | Who scheduled, or who canceled, this task | A payment deadline task is canceled, the order never expires, and the seats stay held for a long time | created_by and a record of cancellations; cancel operations are written to the audit log |
| Information disclosure | The task table becomes a copy of personal data | The payload holds the member’s name, phone number, and notification content, and is kept longer than the original data | Payloads hold only IDs; finished tasks are purged regularly |
| Denial of service | Creating tasks in bulk; poison tasks | Members can create “remind me” tasks, and a script creates millions of them; one task crashes the handler every time | A cap on tasks per member; a retry limit and the DEAD status |
| Elevation of privilege | Handlers running member-supplied content with system privileges | The payload of a task a member scheduled names an internal URL to call or an action to perform | Members can create only fixed task types, and the payload holds only parameters; handlers never run arbitrary commands or URLs from the payload |
When to use it, and when not to
- ShedLock plus
@Scheduled: there are only a few recurring jobs, and all you need is “never run two copies at once” (Distributed Locks and Fencing Tokens post) - A database task table: large numbers of delayed tasks that have to be created in the same transaction as the business data
- An off-the-shelf library or cloud service: when your needs fit their model, use one first instead of maintaining your own
- A timing wheel or Redis: you need sub-second precision, and you can accept reloading from the database on restart
- When to re-evaluate: when the claim query becomes the main load on the database, or the task volume goes beyond thousands a second, consider splitting the task table by due time or by type
References
- MySQL 8.4 Reference Manual — Locking Read Concurrency with NOWAIT and SKIP LOCKED: https://dev.mysql.com/doc/refman/8.4/en/innodb-locking-reads.html
- George Varghese, Anthony Lauck, “Hashed and Hierarchical Timing Wheels: Data Structures for the Efficient Implementation of a Timer Facility”, SOSP 1987
- Apache Kafka Blog — “Apache Kafka, Purgatory, and Hierarchical Timing Wheels”, 2015
- Spring Framework Reference — Task Execution and Scheduling: https://docs.spring.io/spring-framework/reference/integration/scheduling.html
- Quartz Scheduler Documentation — Configure Clustering with JDBC-JobStore
- Interactive diagrams: Dilum Sanjaya, System Design — an interactive course: https://designed-to-scale.vercel.app/
Comments