We are going to design a system that replaces cron with the following features:
Deduplication: Avoid running the same job multiple times if it's already scheduled or running.
Jitter: Add randomness to the start time to avoid thundering herd.
Concurrency caps: Limit the number of concurrent instances of a job.
Failure escalation: Retry with backoff and eventually escalate (e.g., alert) after repeated failures.
Visibility: Provide logs and metrics for monitoring.
We assume we are building this in a distributed environment (multiple workers).
Steps:
Job Storage: We need a persistent storage to keep track of:
Scheduled jobs (with their schedule, next run time, etc.)
Currently running jobs (to enforce concurrency caps and deduplication)
Job history (for visibility and failure escalation)
Scheduler: A component that decides when to run which job. It should:
Be able to jitter the scheduled time (within a small window) to avoid simultaneous starts.
When a job's scheduled time (with jitter) arrives, it tries to acquire a lock (for deduplication and concurrency) and then dispatches the job.
Worker: Executes the job. It should:
Report back to the storage about the job status (success, failure).
Release the lock when done.
Concurrency Control:
We can use a semaphore or a counter in the storage to limit concurrent runs of the same job.
Alternatively, when scheduling, we check the current running count and only schedule if below the cap.
Failure Escalation:
Track the number of consecutive failures for a job.
After a threshold, mark the job as failed and/or send an alert.
Visibility:
Store logs for each job run.
Provide metrics (e.g., number of runs, successes, failures, concurrency, etc.)
Implementation Outline:
We'll use a database (e.g., PostgreSQL) for storage, and a set of workers and a scheduler.
Tables:
jobs:
id (primary key)
name (unique)
command (or reference to a task)
schedule (cron expression or interval)
jitter_seconds (optional, default 0)
max_concurrent (default 1)
failure_threshold (number of consecutive failures before escalation, default 3)
job_runs:
id (primary key)
job_id (foreign key to jobs)
scheduled_time (when it was scheduled to run, with jitter applied)
start_time (when the worker actually started)
end_time (when the worker finished)
status (enum: scheduled, running, success, failure, escalated)
worker_id (which worker ran it)
log (text or reference to log storage)
job_locks:
This table can be used for locking a job during execution to prevent concurrent runs beyond the limit.
Alternatively, we can use a counter in the job_runs table (with a running status) and use transactions to check and update.
However, for simplicity and to avoid race conditions, we can use advisory locks in PostgreSQL for each job.
Alternatively, we can have:
job_concurrency:
job_id
running_count
(and use UPDATE ... WHERE running_count < max_concurrent to try to increment)
But note: we must also handle the case when a job fails and we decrement.
Instead, let's use a lock table and advisory locks per job, but then we cannot have more than one run at a time if we use a single lock.
For max_concurrent > 1, we need a counting semaphore. We can implement:
BEGIN;
SELECT current_count FROM job_semaphores WHERE job_id = ? FOR UPDATE;
IF current_count < max_concurrent THEN
UPDATE job_semaphores SET current_count = current_count + 1 WHERE job_id = ?;
INSERT INTO job_runs ... (status='running')
COMMIT;
ELSE
ROLLBACK; and skip this run.
END;
But note: we must also decrement when the job finishes (success or failure). And we must handle crashes (heartbeat or timeout).
Instead, we can use a combination:
The job_runs table has a status. We consider a run as "running" if it's in the running state and started within a reasonable time (to handle crashes).
Then we count the number of running runs for a job and compare with max_concurrent.
However, counting in a transaction might be heavy and we have to lock the job_runs rows? Not necessarily if we use a separate counter.
Let's stick with the job_semaphores table and update it when we start and finish a job.
Steps for scheduling:
Scheduler picks jobs that are due (scheduled_time <= now and status is not running for that run?).
For each job, try to acquire a semaphore slot (by incrementing the count in job_semaphores) in a transaction.
If successful, create a job_run with status 'running' and record the start_time and worker_id.
If not, skip this run (and maybe reschedule? or just wait for next schedule?).
But note: if a job fails, we decrement the semaphore and then we can run another instance.
However, if a job crashes, we need a way to decrement the semaphore. We can have a background process that checks for runs that have been running for too long and marks them as failed and decrements the semaphore.
Alternatively, we can have a heartbeat mechanism where the worker updates the job_run periodically. Then we consider a run as alive only if it has a recent heartbeat.
Given complexity, let's assume we don't have long-running jobs that might crash without finishing. But in reality, we must handle this.
We can have:
job_runs:
...
last_heartbeat (timestamp, updated by worker periodically)
Then a monitor process (or the scheduler) can check for runs that have not had a heartbeat for, say, 5 minutes and mark them as failed and decrement the semaphore.
Alternatively, we can set a timeout on the job_run and if it exceeds the expected duration, we consider it failed.
But without heartbeat, we cannot know if the worker is still alive.
Let's design for:
Each job_run has a status and a last_heartbeat.
The worker updates the heartbeat every, say, 30 seconds.
The scheduler (or a separate monitor) checks for runs that have not had a heartbeat for > 2*heartbeat_interval and marks them as failed.
Then we decrement the semaphore when we mark as failed.
Steps:
Scheduling:
For each job that is due (scheduled_time <= now and not already running for this scheduled time? Actually, we schedule by time, so we might have multiple runs scheduled at the same time? No, because we are using a cron-like schedule, we schedule the next run after the current one finishes? Not exactly.
We have a fixed schedule (cron expression). So we want to run at every scheduled time, but if the previous run is still running (and we have max_concurrent=1) then we skip.
How do we know which scheduled time we are running? We have a scheduled_time in job_runs. We schedule a new run for the next scheduled time (according to cron) when the current run finishes? Not necessarily.
Actually, we want to run at fixed intervals, regardless of previous run duration, but with concurrency cap.
So:
The scheduler looks at the job's schedule and calculates the next scheduled time (with jitter) that is in the past and not yet run (or we create a new scheduled run every time the scheduler runs?).
We can have:
Table: job_schedules
job_id
scheduled_time (the exact time we want to run, with jitter)
But then we have to create a new schedule for each occurrence? That might be too many.
Alternatively, we can calculate the next scheduled time on the fly and then when we schedule, we mark that time as taken for that job? But if we skip due to concurrency, then we might miss that run.
Let's think:
We have a cron expression: "*/5 * * * *" meaning every 5 minutes.
We want to run at 00:00, 00:05, 00:10, etc.
But if a run takes 6 minutes, then at 00:05 we might still be running, so we skip the 00:05 run? Yes, if max_concurrent=1.
So we need to know: for a given scheduled time (the nominal time from cron) we want to run at that time + jitter, but only if we have capacity.
How about:
We have a table: job_scheduled_runs
job_id
scheduled_time (the nominal time from cron, without jitter)
jittered_time (scheduled_time + random(0, jitter))
status (scheduled, running, completed, failed, etc.)
But then we have to create a new row for each scheduled time. And we have to calculate the next scheduled time.
Alternatively, we can have:
In the jobs table, we store the last scheduled time (the last time we tried to run). Then the scheduler, for each job, computes the next scheduled time (according to cron) and if that time is in the past and we haven't scheduled it yet (or we have, but it was skipped and we want to retry?) then we try to schedule.
But note: if we skip because of concurrency, we might want to try again at the same scheduled time? No, because the scheduled time has passed. We might want to run as soon as possible? That's a design decision.
Typically, cron runs at fixed times and if it misses because the previous run is still ongoing, it skips. So we don't backlog.
So:
We store for each job:
next_scheduled_time (the next nominal time from cron, without jitter)
Then the scheduler:
For each job, if now >= next_scheduled_time (with jitter? no, jitter is applied to the start time, so we schedule the run at next_scheduled_time + jitter).
But then we might schedule multiple runs if the scheduler runs multiple times in the same minute? We need to avoid that.
We can have a table of scheduled runs that are pending (scheduled_time <= now and status = 'pending') and then try to run them.
But then we have to create a new pending run for each scheduled occurrence.
Let's do:
Table: scheduled_job_runs
id
job_id
nominal_time (the time from cron, without jitter, e.g., 2024-01-01 12:00:00)
jittered_time (nominal_time + random(0, jitter))
created_at (when we created this scheduled run)
status (pending, running, completed, failed, etc.)
The scheduler:
For each job, compute the next nominal_time that is >= last_nominal_time and <= now? Actually, we want to create a scheduled run for every nominal_time that is in the past and we haven't created a scheduled run for.
So we need to store the last nominal_time we scheduled for that job? Or we can generate a series of nominal times from the last scheduled one until now and create scheduled runs for each.
We can have in the jobs table:
code
last_scheduled_nominal_time (the last nominal time we created a scheduled run for)
Then the scheduler:
For each job:
Let last = last_scheduled_nominal_time (or the job's start date if none)
Let now = current time
Generate nominal times from last + interval (according to cron) until now.
code
For each nominal_time in that range (that we haven't scheduled yet) we create a scheduled_job_run with:
nominal_time = nominal_time
jittered_time = nominal_time + random(0, job.jitter_seconds)
status = 'pending'
Then we update last_scheduled_nominal_time to the last nominal_time we generated.
Then we try to run the pending scheduled_job_runs that have jittered_time <= now.
But note: if the jitter is large, we might have jittered_time in the future, so we don't run until then.
Then, for each pending scheduled_job_run with jittered_time <= now, we try to acquire a semaphore slot (for the job) and then start the run.
We then update the scheduled_job_run to status='running' and create a job_run record that points to the scheduled_job_run? Or we can merge.
Alternatively, we can skip the scheduled_job_runs table and just have:
job_runs:
id
job_id
nominal_time (the scheduled time without jitter)
jittered_time (nominal_time + jitter)
start_time
... etc.
And then the scheduler:
For each job, compute the next nominal_time (starting from the job's last_scheduled_nominal_time) until now, and for each nominal_time that we haven't created a job_run for, we create a job_run with status='pending' and jittered_time.
Then we try to run the pending job_runs with jittered_time <= now.
We need an index on job_runs (job_id, nominal_time) to avoid creating duplicate runs for the same nominal_time.
Scheduler steps:
For each job, generate nominal times from last_scheduled_nominal_time (or job's start date) until now, and for each nominal_time that does not exist in job_runs for that job, create a job_run with:
nominal_time = nominal_time
jittered_time = nominal_time + random(0, jitter_seconds)
status = 'pending'
(start_time, end_time, etc. are null)
Update last_scheduled_nominal_time to the last nominal_time we generated.
Then, for each job, select the pending job_runs where jittered_time <= now and try to run them (with concurrency check).
Concurrency check:
We have a table job_semaphores:
job_id (unique)
current_count
We try to start a job_run by:
BEGIN;
SELECT current_count FROM job_semaphores WHERE job_id = ? FOR UPDATE;
IF current_count < job.max_concurrent THEN
UPDATE job_semaphores SET current_count = current_count + 1 WHERE job_id = ?;
UPDATE job_runs SET status='running', start_time=now(), worker_id=? WHERE id=?;
COMMIT;
Then dispatch to worker.
ELSE
ROLLBACK; and leave the job_run as pending (for next scheduler run?).
END;
But note: if we leave it pending, then the next scheduler run (in a few seconds) will try again. That's acceptable because we want to run as soon as there's capacity.
However, if the jittered_time is in the past, we are trying to run it as soon as possible. But if we have max_concurrent=1 and the job runs for 10 minutes, then we will try every scheduler interval (say every minute) to run the pending job_run that is 10 minutes old? That might be acceptable.
Alternatively, we can mark the pending job_run as 'skipped' if we try for too long? But then we might lose runs.
We can also have a maximum age for pending job_runs? Or we can just keep trying until the job finishes and then we can run the next pending one.
But note: we have multiple pending job_runs for the same job? Yes, if the job is scheduled every minute and it runs for 10 minutes, then we will have 10 pending job_runs.
And when the current run finishes, we decrement the semaphore and then the next pending job_run (the oldest) will be picked up.
This is acceptable.
Worker:
The worker executes the command and then:
On success:
UPDATE job_runs SET status='success', end_time=now() WHERE id=?;
UPDATE job_semaphores SET current_count = current_count - 1 WHERE job_id=?;
On failure:
UPDATE job_runs SET status='failure', end_time=now(), error_message=? WHERE id=?;
UPDATE job_semaphores SET current_count = current_count - 1 WHERE job_id=?;
Then check the consecutive failures for this job (for recent runs). We can do:
SELECT COUNT(*) FROM job_runs
WHERE job_id=? AND status='failure' AND end_time > now() - interval '1 day'
ORDER BY end_time DESC LIMIT job.failure_threshold?
Actually, we want consecutive failures. So we look at the last job.failure_threshold runs and if they are all failures, then we escalate.
But note: we might have a success in between. So we want the last N runs (by end_time) and if they are all failures, then escalate.
We can do:
WITH last_n_runs AS (
SELECT status FROM job_runs
WHERE job_id=?
ORDER BY end_time DESC
LIMIT ?
)
SELECT COUNT(*) = ? AND bool_and(status='failure')
FROM last_n_runs;
If true, then we mark the job as escalated? Or we send an alert.
We can have a table job_alerts:
job_id, alerted_at, message
And we insert a row when we escalate.
But note: we don't want to alert on every failure, only after the threshold of consecutive failures.
Heartbeat:
The worker should update the job_run's last_heartbeat periodically (every 30 seconds). Then a monitor process (or the scheduler) can check for runs that have not had a heartbeat for, say, 2 minutes and mark them as failed and decrement the semaphore.
We can have a background job that runs every minute:
UPDATE job_runs
SET status='failure', error_message='heartbeat timeout'
WHERE status='running' AND last_heartbeat < now() - interval '2 minutes';
Then we also need to decrement the semaphore for these runs.
But note: we are updating the job_runs table and then we need to update the semaphore. We can do:
For each job_id that has runs marked as failed due to timeout, we decrement the semaphore by the number of such runs.
Alternatively, we can have the monitor process:
BEGIN;
SELECT job_id, COUNT(*) FROM job_runs
WHERE status='running' AND last_heartbeat < now() - interval '2 minutes'
GROUP BY job_id;
Then for each job_id, we update the job_semaphores:
UPDATE job_semaphores
SET current_count = current_count - :count
WHERE job_id = :job_id AND current_count >= :count;
But note: we must also update the job_runs to set status='failure' and error_message.
We can do:
WITH timedout_runs AS (
SELECT id, job_id FROM job_runs
WHERE status='running' AND last_heartbeat < now() - interval '2 minutes'
)
UPDATE job_runs
SET status='failure', error_message='heartbeat timeout'
FROM timedout_runs
WHERE job_runs.id = timedout_runs.id;
Then update the semaphores.
But we must be careful: if the semaphore count becomes negative? We use a condition that current_count >= count.
Alternatively, we can use a trigger on job_runs to decrement the semaphore when status changes from running to non-running? But then we have to handle the timeout update.
Let's do:
We have a function that decrements the semaphore for a job_run when it finishes (success or failure) and also for timeouts.
But we are updating job_runs in two places: the worker and the timeout monitor.
We can have a trigger on job_runs after update of status from 'running' to something else, but then we have to know the old status.
Alternatively, we can handle the decrement in the application code (worker and timeout monitor) and not use a trigger.
Steps for worker:
When the job finishes (success or failure):
BEGIN;
UPDATE job_runs SET status=?, end_time=now(), last_heartbeat=null WHERE id=?;
UPDATE job_semaphores SET current_count = current_count - 1 WHERE job_id = (SELECT job_id FROM job_runs WHERE id = ?);
COMMIT;
For timeout monitor:
BEGIN;
-- Select the timedout runs and update them
WITH timedout AS (
SELECT id, job_id FROM job_runs
WHERE status='running' AND last_heartbeat < now() - interval '2 minutes'
)
UPDATE job_runs
SET status='failure', error_message='heartbeat timeout', last_heartbeat=null
FROM timedout
WHERE job_runs.id = timedout.id;
-- Then decrement the semaphore for each job_id that had timedout runs.
-- We can do it by grouping by job_id and then updating.
-- But we have to be cautious because we might have multiple runs for the same job.
We can do:
WITH job_counts AS (
SELECT job_id, COUNT(*) as count
FROM job_runs
WHERE status='failure' AND error_message='heartbeat timeout'
AND last_heartbeat IS NULL -- to avoid double counting?
AND end_time = now()? -- we just set end_time to now()? Actually, we set end_time in the update above? We didn't set end_time in the timeout update.
Wait, in the timeout update we set status and error_message but not end_time? We should set end_time to now().
Let's adjust the timeout update:
UPDATE job_runs
SET status='failure', error_message='heartbeat timeout', end_time=now(), last_heartbeat=null
FROM timedout
WHERE job_runs.id = timedout.id;
Then:
WITH job_counts AS (
SELECT job_id, COUNT(*) as count
FROM job_runs
WHERE status='failure' AND error_message='heartbeat timeout'
AND end_time = now() -- but now() is the time of the update? We can use the same time for all? Actually, we set end_time=now() in the update, so they are all the same as the update time.
code
But note: we might have multiple timeout runs for the same job, and we want to decrement the semaphore by the count.
However, we are updating the job_runs and then we want to update the semaphore. We can do:
WITH updated_runs AS (
UPDATE job_runs
SET status='failure', error_message='heartbeat timeout', end_time=now(), last_heartbeat=null
WHERE id IN (SELECT id FROM timedout)
RETURNING job_id
)
UPDATE job_semaphores
SET current_count = current_count - sub.count
FROM (
SELECT job_id, COUNT(*) as count
FROM updated_runs
GROUP BY job_id
) as sub
WHERE job_semaphores.job_id = sub.job_id;
But note: we are updating the same job_semaphores row multiple times? No, because we group by job_id.
However, we must ensure that the semaphore count doesn't go negative. We can add a condition:
AND current_count >= sub.count
But if it does, then we have a problem because we already marked the runs as failed but didn't decrement? Actually, we are decrementing and if the condition fails, then the update doesn't happen. Then we have a mismatch.
So we must ensure that the semaphore count is accurate. We can use a trigger to maintain the semaphore count? Or we can recalculate the semaphore count from the job_runs table? But that would be expensive.
Alternatively, we can avoid the semaphore table and compute the current_count by counting the job_runs with status='running' (and recent heartbeat) for each job. But that would be a heavy query every time we want to schedule.
Given the complexity, let's stick with the semaphore table and try to keep it consistent.
We can have a trigger on job_runs that updates the semaphore when a run becomes running (increment) and when it becomes non-running (decrement). But then we have to handle the timeout update which also changes the status from running to failure.
So:
Trigger on job_runs after update of status:
IF OLD.status = 'running' and NEW.status != 'running' THEN
UPDATE job_semaphores SET current_count = current_count - 1 WHERE job_id = NEW.job_id;
END IF;
And when we insert a job_run with status='running', we increment the semaphore.
Then the worker and the timeout monitor just update the job_run status and the trigger will handle the semaphore.
But note: when we update the job_run from pending to running, we also increment the semaphore. And when we update from running to success/failure, we decrement.
So the trigger:
CREATE OR REPLACE FUNCTION update_semaphore_on_job_run_status_change() RETURNS trigger AS $$
BEGIN
IF TG_OP = 'UPDATE' THEN
IF OLD.status = 'pending' AND NEW.status = 'running' THEN
UPDATE job_semaphores SET current_count = current_count + 1 WHERE job_id = NEW.job_id;
ELSIF OLD.status = 'running' AND NEW.status != 'running' THEN
UPDATE job_semaphores SET current_count = current_count - 1 WHERE job_id = NEW.job_id;
END IF;
END IF;
RETURN NEW;
END;
But then we have to handle the case when we insert a job_run with status='running'? We don't insert with status='running' directly? We insert as pending and then update to running.
Actually, we do:
We insert the job_run as pending, then we update it to running (in the same transaction when we acquire the semaphore). So the trigger will fire for the update from pending to running and increment the semaphore.
And then when the worker updates to success/failure, it decrements.
And the timeout monitor updates from running to failure, and the trigger decrements.
But what about the initial insert? We don't want to increment the semaphore on insert because we insert as pending.
So the trigger only on update.
Also, we must handle the case when we update the job_run from running to running? (heartbeat update). We update last_heartbeat but not status, so trigger doesn't fire.
Now, we must ensure that the semaphore table exists and has a row for each job. We can have a job that inserts a row into job_semaphores when a new job is created.
Alternatively, we can use a foreign key and have the semaphore row created automatically? We can have a trigger on jobs to insert into job_semaphores.
But note: we are updating the semaphore in the trigger on job_runs, so we must have a row in job_semaphores for the job. We can ensure that by:
- When creating a job, also create a job_semaphore row with current_count=0.
Now, the concurrency check:
We try to update the job_run from pending to running, and the trigger will increment the semaphore. But we must check that the current_count does not exceed max_concurrent.
How?
We can do:
BEGIN;
-- Lock the job_semaphores row for the job.
SELECT current_count FROM job_semaphores WHERE job_id = ? FOR UPDATE;
IF current_count < job.max_concurrent THEN
UPDATE job_runs SET status='running', start_time=now(), worker_id=? WHERE id=?;
-- The trigger will increment the semaphore.
COMMIT;
ELSE
ROLLBACK;
END;
But note: the trigger will increment the semaphore after the update. So we are checking the current_count before the increment.
This works.
However, we have a race condition: two schedulers might both read the current_count and both see it's below the limit and both update. But because we lock the row in the SELECT ... FOR UPDATE, they will be serialized.
So it's safe.
Now, the heartbeat:
The worker should update the job_run's last_heartbeat periodically (without changing status). We can do:
UPDATE job_runs SET last_heartbeat=now() WHERE id=? and status='running';
And the timeout monitor will look for runs where last_heartbeat is too old.
Failure escalation:
We can have a separate process that checks for jobs that have consecutive failures and then alerts.
Steps for failure escalation:
For each job, get the last N runs (where N = failure_threshold) that are completed (success or failure) and check if they are all failures.
We can do this in the worker when it fails? But then we might have multiple workers and we don't want to escalate multiple times.
Alternatively, we can have a background job that runs every few minutes and checks for jobs that have had failure_threshold consecutive failures and haven't been alerted yet.
We can have a table job_escalations:
job_id, escalated_at, resolved_at
Then the background job:
For each job:
SELECT COUNT(*) as failure_count
FROM (
SELECT status FROM job_runs
WHERE job_id = job.id
ORDER BY end_time DESC
LIMIT job.failure_threshold
) as last_runs
WHERE status='failure';
If failure_count = job.failure_threshold and there is no recent escalation (or the last escalation was more than, say, 1 hour ago) then insert a new escalation record and send an alert.
Visibility:
We can expose the job_runs table and job_semaphores table via an API.
Also, we can have metrics:
- Number of pending, running, success, failure job_runs per job.
- Current concurrency (current_count in job_semaphores) per job.
- Failure rate.
We can compute these from the database.
Implementation:
We'll need:
- A scheduler that runs every, say, 30 seconds and:
a. For each job, generate the missing scheduled job_runs (nominal times) and update last_scheduled_nominal_time.
b. Then for each pending job_run with jittered_time <= now, try to start it (with concurrency check).
- Workers that pick up running job_runs (we can have a queue of running job_runs? or the scheduler dispatches to a worker?).
We can have the scheduler, when it updates a job_run to running, push the job_run id to a message queue (e.g., RabbitMQ, Redis) and workers consume from that queue.
Or we can have a pool of workers that poll the database for job_runs with status='running' and worker_id is null? But then we have to assign a worker_id.
Alternatively, the scheduler can assign a worker_id (from a pool of workers) and then the worker picks up by worker_id? That's more complex.
Let's do:
The scheduler, when it decides to run a job_run, it updates the job_run to running and sets a worker_id (which is the id of the worker that will run it). Then the worker, on start, looks for job_runs with worker_id = its own id and status='running'? But then we have to assign the worker_id at scheduling time.
Alternatively, we can have a queue:
Scheduler updates the job_run to running and then pushes the job_run id to a queue. Then workers consume from the queue and process the job_run.
Then the worker_id in job_runs is the id of the worker that processed it. We can set the worker_id when the worker starts processing.
Steps:
1. Scheduler updates job_run to running (without worker_id) and then pushes the job_run id to a queue.
2. Worker pops a job_run id from the queue, then updates the job_run to set worker_id and starts processing.
3. Worker updates last_heartbeat periodically.
But note: the scheduler might update the job_run to running and then push to queue, but if the worker crashes before updating the worker_id, then we have a running job_run without a worker? That's okay because we have the heartbeat.
We can also set the worker_id when the scheduler updates to running? But then we have to know which worker will run it.
Alternatively, we can have a pool of workers that poll for job_runs with status='running' and worker_id is null, and then try to claim it (update worker_id) if they are free? That's more like a work queue.
Given the complexity, let's assume we have a message queue and the scheduler pushes the job_run id to the queue. Then the worker, when it gets the job_run id, updates the job_run to set worker_id and then processes.
But then we have to update the job_run twice: once by scheduler (status to running) and once by worker (set worker_id). We can combine:
Scheduler: update job_run to running and set worker_id to a placeholder? Or we can have the worker set the worker_id when it starts.
Actually, we can have:
Scheduler:
UPDATE job_runs
SET status='running', start_time=now()
WHERE id=? and status='pending'
RETURNING id;
Then push the id to the queue.
Worker:
When it gets an id, it updates the job_run to set worker_id and then starts processing.
But then the job_run is already running (status='running') but without worker_id. That's acceptable.
Alternatively, we can set the worker_id in the scheduler and then the worker just processes. But then we have to assign a worker at scheduling time, which might not be available.
So let's do:
Scheduler:
BEGIN;
-- try to acquire semaphore and update job_run to running (without worker_id)
... (as above)
COMMIT;
Then push the job_run id to the queue.
Worker:
When it gets a job_run id, it:
UPDATE job_runs
SET worker_id = ?
WHERE id = ? and status='running' and worker_id is null;
Then it processes the job.
This way, if multiple workers get the same job_run id (shouldn't happen because queue is single consumer? but we might have multiple queues or multiple consumers) then only one will succeed in setting worker_id.
But note: the job_run is already running, so we don't want multiple workers to process the same job_run.
So the worker must claim the job_run by setting worker_id. If it fails (because another worker already set it), then it skips.
We can do:
worker_id = the worker's own id (unique).
UPDATE job_runs
SET worker_id = :worker_id
WHERE id = :job_run_id
AND status='running'
AND worker_id IS NULL;
Then check the number of rows updated. If 1, then proceed. If 0, then someone else claimed it, so skip.
Then the worker processes the job and updates the job_run on completion.
Heartbeat:
The worker, while processing, updates the last_heartbeat of the job_run it claimed.
Periodic heartbeat:
UPDATE job_runs
SET last_heartbeat=now()
WHERE id = :job_run_id
AND status='running'
AND worker_id = :worker_id;
Then the timeout monitor will look for job_runs with status='running' and last_heartbeat < now() - interval '2 minutes'.
This design should work.
Let's summarize the steps:
Scheduler (runs every 30 seconds):
1. For each job, generate the missing nominal times (from last_scheduled_nominal_time until now) and insert job_runs with status='pending', nominal_time, jittered_time = nominal_time + random(0, jitter_seconds).
2. Update last_scheduled_nominal_time to the last nominal_time generated.
3. For each job, select the pending job_runs with jittered_time <= now() and try to start them:
For each such job_run:
BEGIN;
SELECT current_count FROM job_semaphores WHERE job_id = job_run.job_id FOR UPDATE;
IF current_count < job.max_concurrent THEN
UPDATE job_runs
SET status='running', start_time=now()
WHERE id = job_run.id and status='pending';
-- The trigger will increment the semaphore.
COMMIT;
Push job_run.id to the work queue.
ELSE
ROLLBACK;
-- leave it pending for next time.
END IF;
Worker:
- Pop a job_run id from the queue.
- Try to claim it:
UPDATE job_runs
SET worker_id = :worker_id
WHERE id = :job_run_id
AND status='running'
AND worker_id IS NULL;
If rows updated = 1, then proceed. Else, skip (and maybe push back? or just drop).
- While processing, every 30 seconds, update the job_run's last_heartbeat:
UPDATE job_runs
SET last_heartbeat=now()
WHERE id = :job_run_id
AND status='running'
AND worker_id = :worker_id;
- When done (success or failure):
UPDATE job_runs
SET status=:new_status, end_time=now(), error_message=:error_message, last_heartbeat=null
WHERE id = :job_run_id
AND status='running'
AND worker_id = :worker_id;
The trigger will decrement the semaphore.
Timeout Monitor (runs every minute):
WITH timedout AS (
SELECT id, job_id FROM job_runs
WHERE status='running'
AND last_heartbeat < now() - interval '2 minutes'
)
UPDATE job_runs
SET status='failure', error_message='heartbeat timeout', end_time=now(), last_heartbeat=null
FROM timedout
WHERE job_runs.id = timedout.id;
-- The trigger will decrement the semaphore for each updated row.
Failure Escalation Monitor (runs every 5 minutes):
For each job:
Let n = job.failure_threshold
SELECT COUNT(*) = n AND bool_and(status='failure')
FROM (
SELECT status FROM job_runs
WHERE job_id = job.id
ORDER BY end_time DESC
LIMIT n
) as last_n;
If true and there is no recent escalation (e.g., in the last hour) for this job, then insert into job_escalations (job_id, escalated_at) and send an alert.
This design should meet the requirements.
Note: We are using PostgreSQL and assume we can use advisory locks or row-level locking for the semaphore.
Let's write the SQL for the trigger and the tables.
Tables:
CREATE TABLE jobs (
id BIGSERIAL PRIMARY KEY,
name TEXT NOT NULL UNIQUE,
command TEXT NOT NULL,
schedule TEXT NOT NULL, -- cron expression
jitter_seconds INT DEFAULT 0,
max_concurrent INT DEFAULT 1,
failure_threshold INT DEFAULT 3,
last_scheduled_nominal_time TIMESTAMPTZ
);
CREATE TABLE job_semaphores (
job_id BIGINT PRIMARY KEY REFERENCES jobs(id) ON DELETE CASCADE,
current_count INT DEFAULT 0
);
CREATE TABLE job_runs (
id BIGSERIAL PRIMARY KEY,
job_id BIGINT NOT NULL REFERENCES jobs(id),
nominal_time TIMESTAMPTZ NOT NULL,
jittered_time TIMESTAMPTZ NOT NULL,
status TEXT NOT NULL CHECK (status IN ('pending', 'running', 'success', 'failure', 'escalated')),
start_time TIMESTAMPTZ,
end_time TIMESTAMPTZ,
worker_id TEXT, -- or BIGINT if workers are stored in a table
last_heartbeat TIMESTAMPTZ,
error_message TEXT,
UNIQUE (job_id, nominal_time) -- to avoid duplicate scheduled runs for the same nominal time.
);
CREATE INDEX idx_job_runs_job_id ON job_runs(job_id);
CREATE INDEX idx_job_runs_status ON job_runs(status);
CREATE INDEX idx_job_runs_jittered_time ON job_runs(jittered_time) WHERE status='pending';
Trigger function:
CREATE OR REPLACE FUNCTION update_semaphore_on_job_run_status_change() RETURNS trigger AS $$
BEGIN
IF TG_OP = 'UPDATE' THEN
IF OLD.status = 'pending' AND NEW.status = 'running' THEN
UPDATE job_semaphores SET current_count = current_count + 1 WHERE job_id = NEW.job_id;
ELSIF OLD.status = 'running' AND NEW.status != 'running' THEN
UPDATE job_semaphores SET current_count = current_count - 1 WHERE job_id = NEW.job_id;
END IF;
END IF;
RETURN NEW;
END;
$$ LANGUAGE plpgsql;
CREATE TRIGGER trg_job_run_status_change
AFTER UPDATE ON job_runs
FOR EACH ROW
EXECUTE FUNCTION update_semaphore_on_job_run_status_change();
Note: We must ensure that the job_semaphores table has a row for each job. We can have a trigger on jobs to insert into job_semaphores when a new job is created.
Alternatively, we can use a foreign key with ON DELETE CASCADE and then when we delete a job, the semaphore row is deleted.
But we must insert the semaphore row when creating a job. We can do:
INSERT INTO jobs (...) VALUES (...);
INSERT INTO job_semaphores (job_id) VALUES (lastval());
Or we can have a trigger:
CREATE OR REPLACE FUNCTION create_job_semaphore() RETURNS trigger AS $$
BEGIN
INSERT INTO job_semaphores (job_id) VALUES (NEW.id);
RETURN NEW;
END;
$$ LANGUAGE plpgsql;
CREATE TRIGGER trg_create_job_semaphore
AFTER INSERT ON jobs
FOR EACH ROW
EXECUTE FUNCTION create_job_semaphore();
Now, the scheduler and workers are separate processes.
We also need to handle the case when the scheduler crashes in the middle of updating the job_run and pushing to the queue. We are using transactions, so if the scheduler crashes after updating the job_run but before pushing, then the job_run is stuck in 'running' state without a worker? We can have a timeout for running job_runs without worker_id? But then the timeout monitor would mark it as failure.
Alternatively, we can push to the queue and then update the job_run? But then if the push fails, we have a job_run in pending? We are doing:
BEGIN;
update job_run to running;
COMMIT;
then push.
If the push fails, the job_run is running but not in the queue. Then we need a way to recover: we can have a process that looks for running job_runs without worker_id and that were started more than, say, 1 minute ago and re-queue them? But then we might run the same job twice? Because the worker might have claimed it but crashed before updating worker_id? Actually, we set worker_id only when the worker claims it.
So if the scheduler updates the job_run to running and then crashes before pushing, then the job_run is running but not in the queue. Then we need a way to re-queue it.
We can have a process that looks for job_runs with status='running' and worker_id is null and start_time < now() - interval '1 minute' and then push them again? But then we might have duplicates if the original push succeeded but the worker didn't claim it? Actually, the worker claims by setting worker_id. So if the worker got the job_run id from the queue and then crashed before setting worker_id, then the job_run is still without worker_id and we re-queue it. Then another worker might claim it and run, which is acceptable because the first worker crashed.
So we can have a "re-queue" monitor that runs every minute and:
SELECT id FROM job_runs
WHERE status='running'
AND worker_id IS NULL
AND start_time < now() - interval '1 minute';
Then push these ids to the queue again.
But note: we might have a job_run that was just started (within 1 minute) and the worker is slow to claim? We set a 1 minute grace period.
Alternatively, we can set worker_id in the scheduler when we update to running? Then we don't have the problem. But then we have to assign a worker at scheduling time.
We can have a pool of workers and the scheduler picks one? But then if that worker is down, the job won't run.
So let's stick with the current design and have the re-queue monitor.
Alternatively, we can change the scheduler to:
BEGIN;
update job_run to running and set worker_id to a specific worker (by having the scheduler know about the workers). Then push to that worker's personal queue? That's more complex.
Given the complexity, I think the re-queue monitor is acceptable.
Let's adjust:
Scheduler:
When it updates the job_run to running, it does not set worker_id.
Re-queue monitor (runs every minute):
SELECT id FROM job_runs
WHERE status='running'
AND worker_id IS NULL
AND start_time < now() - interval '1 minute';
For each such job_run, push it to the queue again.
But note: the same job_run might be pushed multiple times? We can mark that we have re-queued it? Or we can update a field? Or we can just push and rely on the worker to claim it (and only one will succeed because of the worker_id update).
However, if the job_run is already being processed by a worker that hasn't set worker_id yet (because it's slow) then we might re-queue it and then two workers might try to claim it. But the first one to update worker_id will win, and the second will fail (because worker_id is already set). So it's safe.
But we might have duplicate pushes. We can avoid by having a "re-queued" flag? Or we can update the job_run to set a re-queued_at timestamp and only re-queue if re-queued_at is null or old? But then if the worker crashes after setting worker_id? We don't care because it's claimed.
Actually, we only re-queue if worker_id is null. So if a worker claims it (sets worker_id) then we don't re-queue.
So the re-queue monitor is safe.
Now, the worker:
When it gets a job_run id, it tries to set worker_id. If it succeeds, it processes.
If it fails (because another worker set worker_id), then it discards.
This design should be robust.
Let's write the steps for the scheduler and monitors.
Scheduler (pseudocode):
for each job in jobs:
generate nominal times from last_scheduled_nominal_time (or job's start_date) until now.
for each nominal_time that doesn't exist in job_runs for this job:
jittered_time = nominal_time + random(0, job.jitter_seconds)
insert into job_runs (job_id, nominal_time, jittered_time, status) values (job.id, nominal_time, jittered_time, 'pending')
update job.last_scheduled_nominal_time to the last nominal_time generated.
Then:
for each job:
for each pending job_run with jittered_time <= now() and not yet tried in this scheduler run? (we can just try all pending that are due)
try to start:
BEGIN;
SELECT current_count FROM job_semaphores WHERE job_id = job.id FOR UPDATE;
IF current_count < job.max_concurrent THEN
UPDATE job_runs SET status='running', start_time=now() WHERE id = job_run.id and status='pending';
COMMIT;
push job_run.id to work queue.
ELSE
ROLLBACK;
END IF;
Note: we must lock the job_semaphores row for the job to avoid two schedulers starting more than max_concurrent.
Re-queue monitor:
SELECT id FROM job_runs
WHERE status='running'
AND worker_id IS NULL
AND start_time < now() - interval '1 minute';
For each id, push to work queue.
Heartbeat:
Workers update last_heartbeat every 30 seconds for their job_run.
Timeout monitor:
UPDATE job_runs
SET status='failure', error_message='heartbeat timeout', end_time=now(), last_heartbeat=null
WHERE status='running'
AND last_heartbeat < now() - interval '2 minutes';
Failure escalation monitor:
For each job:
Let n = job.failure_threshold
SELECT COUNT(*) = n AND bool_and(status='failure')
FROM (
SELECT status FROM job_runs
WHERE job_id = job.id
ORDER BY end_time DESC
LIMIT n
) as last_n;
If true and there is no escalation in the last hour (or we can have a cooldown), then insert into job_escalations and alert.
This is a comprehensive design.
However, note that generating the nominal times for each job every scheduler run might be expensive if we have many jobs and long history.
We can cache the last_scheduled_nominal_time and only generate up to now.
Also, we must generate the nominal times according to the cron expression. We can use a cron parser library.
We assume we have a function that, given a cron expression and a start time, returns the next occurrence until an end time.
We can do:
last_scheduled = job.last_scheduled_nominal_time or job.start_date (the date from which we start scheduling)
now = current time
next_nominal = cron_next(job.schedule, last_scheduled)
while next_nominal <= now:
if not exists (select 1 from job_runs where job_id=job.id and nominal_time=next_nominal):
insert job_run with nominal_time=next_nominal, jittered_time=next_nominal + random(0, job.jitter_seconds)
last_scheduled = next_nominal
next_nominal = cron_next(job.schedule, next_nominal)
Then update job.last_scheduled_nominal_time = last_scheduled.
But note: we might have multiple scheduler instances. We must avoid two schedulers generating the same nominal_time.
We can use a advisory lock on the job when generating the schedule? Or we can have a table that locks the job during scheduling.
Alternatively, we can have a distributed lock (e.g., using a lock table with job_id and use SELECT FOR UPDATE).
We can do:
BEGIN;
SELECT * FROM jobs WHERE id = job.id FOR UPDATE;
Then generate and update last_scheduled_nominal_time.
COMMIT;
This will serialize the scheduling for the same job.
But if we have many jobs, we can lock each job one by one.
Alternatively, we can have a separate table for scheduling locks.
Given the complexity, we can assume we have a single scheduler instance? But we want high availability.
We can use advisory locks for each job:
SELECT pg_advisory_lock(job.id);
Then generate and update, then unlock.
But note: advisory locks are session-level. We must hold the lock until we commit.
We can do:
BEGIN;
SELECT pg_advisory_lock(job.id);
... generate and update ...
COMMIT; -- which releases the lock.
This way, only one scheduler can schedule for a given job at a time.
Now, the design is complete.
Let's note the potential issues:
- Clock skew: We assume all servers have synchronized clocks.
- Database load: The scheduler and monitors hit the database frequently. We need to index properly.
- Long running jobs: We have a heartbeat and timeout, but if a job runs for weeks, we might have many heartbeat updates. We can update the heartbeat less frequently for long jobs? But we have to update at least every 2 minutes to avoid timeout.
- Jitter: We add jitter at scheduling time (when we create the job_run). But note: if we reschedule (due to concurrency) we don't change the jittered_time? We use the same jittered_time that was set when we created the job_run. That's acceptable because the jitter is only to spread the start times, and if we skip the nominal time and run later, we are already jittered? Actually, we want to jitter the start time relative to the nominal time. If we run at a much later time (because of concurrency) then the jitter is irrelevant.
So it's okay.
This design should work.
However, note that the scheduler might create many pending job_runs for a job that is continuously busy (with max_concurrent=1 and long runs). We will have a backlog of pending job_runs. That's acceptable because we will run them in order (oldest first) when the job finishes.
But if the job is scheduled every minute and runs for 10 minutes, then we will have 10 pending job_runs. When the current run finishes, we will start the next pending one (which is the oldest) and then the next, etc. This is acceptable.
We must ensure that we don't create duplicate pending job_runs for the same nominal_time. We have a unique constraint on (job_id, nominal_time).
Now, we have to implement this in code. But the question was to design the system, so we have provided the design.
Let's write the SQL for the tables and trigger.
We also need to handle the creation of the job_semaphores row for existing jobs? We can write a script to backfill.
Alternatively, we can change the trigger to insert only if not exists? But we want one row per job.
We can do:
CREATE OR REPLACE FUNCTION create_job_semaphore() RETURNS trigger AS $$
BEGIN
INSERT INTO job_semaphores (job_id) VALUES (NEW.id)
ON CONFLICT (job_id) DO NOTHING;
RETURN NEW;
END;
$$ LANGUAGE plpgsql;
But the primary key is job_id, so conflict on job_id. But we are inserting after the job is created, so there should be no conflict. But if we run the trigger multiple times? It's an AFTER INSERT trigger, so it runs once per insert.
So we don't need ON CONFLICT.
But if we have existing jobs, we need to insert into job_semaphores for them.
We can do:
INSERT INTO job_semaphores (job_id)
SELECT id FROM jobs
WHERE id NOT IN (SELECT job_id FROM job_semaphores);
Now, the design is complete.
However, note that the job_runs table can grow very large. We might want to archive or delete old job_runs. We can have a retention policy.
But that's beyond the scope.
This is a solid design for replacing cron with the required features.</think>
To replace cron with a robust, production-ready system that addresses deduplication, jitter, concurrency caps, failure escalation, and visibility, here's a comprehensive design pattern:
## Core Architecture Components
### 1. **Job Scheduler + Queue System**
```
[API/CLI] → [Scheduler DB] → [Job Queue] → [Workers]
↑ ↑ ↑
[Control Plane] [Metadata] [Dispatch Logic]
```
### 2. **Database Schema (PostgreSQL example)**
```sql
-- Job definitions
CREATE TABLE jobs (
id UUID PRIMARY KEY,
name TEXT UNIQUE NOT NULL,
command JSONB NOT NULL, -- {type: "docker", "http", "shell", ...}
schedule_cron TEXT NOT NULL,
jitter_seconds INT DEFAULT 30,
max_concurrent INT DEFAULT 1,
timeout_seconds INT DEFAULT 3600,
failure_threshold INT DEFAULT 3,
escalation_webhook TEXT,
created_at TIMESTAMPTZ DEFAULT NOW()
);
-- Job runs with deduplication key
CREATE TABLE job_runs (
id UUID PRIMARY KEY,
job_id UUID REFERENCES jobs(id),
dedup_key TEXT GENERATED ALWAYS AS (
job_id || '_' ||
DATE_TRUNC('minute', scheduled_start_at AT TIME ZONE 'UTC')
) STORED UNIQUE, -- Dedup by job+minute bucket
scheduled_start_at TIMESTAMPTZ NOT NULL,
actual_start_at TIMESTAMPTZ,
completed_at TIMESTAMPTZ,
status TEXT CHECK (status IN ('pending','running','success','failed','escalated')),
worker_id TEXT,
attempt INT DEFAULT 1,
error_message TEXT,
metadata JSONB DEFAULT '{}'
);
-- Concurrency tracking (atomic counters)
CREATE TABLE job_concurrency (
job_id UUID PRIMARY KEY REFERENCES jobs(id),
active_count INT DEFAULT 0 CHECK (active_count >= 0),
last_updated TIMESTAMPTZ DEFAULT NOW()
);
-- Failure tracking for escalation
CREATE TABLE job_failures (
job_id UUID REFERENCES jobs(id),
run_id UUID REFERENCES job_runs(id),
failed_at TIMESTAMPTZ DEFAULT NOW(),
error_code TEXT,
consecutive_failures INT
);
```
### 3. **Scheduler Logic**
```python
class SmartScheduler:
def schedule_next_run(self, job):
# 1. Calculate next cron time
next_time = croniter(job.schedule_cron, datetime.utcnow()).get_next(datetime)
# 2. Apply jitter (±job.jitter_seconds)
jitter = random.uniform(-job.jitter_seconds, job.jitter_seconds)
jittered_time = next_time + timedelta(seconds=jitter)
# 3. Deduplication check
dedup_key = f"{job.id}_{jittered_time.strftime('%Y%m%d%H%M')}"
if self.is_duplicate(dedup_key):
return None # Skip this run
# 4. Create run record
run = JobRun.create(
job_id=job.id,
scheduled_start_at=jittered_time,
dedup_key=dedup_key
)
# 5. Check concurrency before enqueueing
if self.concurrency_semaphore.acquire(job.id, job.max_concurrent):
self.enqueue_for_execution(run)
```
### 4. **Concurrency Control (Redis-based semaphore)**
```python
class ConcurrencyLimiter:
def acquire(self, job_id: str, max_concurrent: int) -> bool:
key = f"concurrency:{job_id}"
current = redis.incr(key)
if current > max_concurrent:
redis.decr(key)
return False
# Set TTL for crash recovery (2x expected max job time)
redis.expire(key, 7200)
return True
def release(self, job_id: str):
redis.decr(f"concurrency:{job_id}")
```
### 5. **Worker with Circuit Breaker Pattern**
```python
class ResilientWorker:
def execute_job(self, run: JobRun):
try:
with self.circuit_breaker(run.job_id):
result = self.run_command(run.command)
run.complete('success', result)
except TransientError as e:
run.record_failure(e)
if run.attempt < MAX_RETRIES:
self.reschedule_with_backoff(run) # Exponential backoff
else:
self.escalate_failure(run)
except PermanentError as e:
run.complete('failed', str(e))
self.escalate_failure(run)
```
### 6. **Failure Escalation System**
```python
class EscalationManager:
def check_and_escalate(self, job_id: str):
# Get consecutive failure count from last N runs
failures = self.get_recent_failures(job_id, window_hours=24)
if failures >= job.failure_threshold:
# Mark job as escalated (prevents further runs)
self.mark_job_escalated(job_id)
# Send alerts
self.send_alert(
job_id=job_id,
failure_count=failures,
recent_errors=self.get_recent_errors(job_id)
)
```
### 7. **Visibility & Monitoring**
#### **Metrics (Prometheus format)**
```
# Job metrics
cron_replace_job_runs_total{job="name",status="success"} 1234
cron_replace_job_concurrent{job="name"} 2
cron_replace_job_latency_seconds{job="name",quantile="0.99"} 1.2
cron_replace_job_failures_total{job="name",type="timeout"} 5
# System metrics
cron_replace_scheduler_skipped_due_to_concurrent 10
cron_replace_scheduler_deduplicated_runs 25
```
#### **Dashboard Schema (Grafana-ready)**
```sql
-- Recent runs with details
SELECT
j.name,
r.scheduled_start_at,
r.actual_start_at,
r.completed_at,
EXTRACT(EPOCH FROM (r.completed_at - r.actual_start_at)) as duration,
r.status,
r.error_message
FROM job_runs r
JOIN jobs j ON r.job_id = j.id
WHERE r.scheduled_start_at > NOW() - INTERVAL '24 hours'
ORDER BY r.scheduled_start_at DESC;
-- Current concurrency overview
SELECT
j.name,
j.max_concurrent,
COALESCE(c.active_count, 0) as current_active,
j.max_concurrent - COALESCE(c.active_count, 0) as available_slots
FROM jobs j
LEFT JOIN job_concurrency c ON j.id = c.job_id;
```
### 8. **Implementation Options**
#### **Option A: Custom Service (Most Control)**
```yaml
# docker-compose.yml
services:
scheduler:
image: your-scheduler:latest
depends_on: [postgres, redis]
environment:
- DB_URL=postgresql://...
- REDIS_URL=redis://...
- QUEUE_URL=redis://redis:6379/0
worker:
image: your-worker:latest
deploy:
replicas: 5 # Auto-scale based on queue depth
environment:
- QUEUE_URL=redis://redis:6379/0
exporter:
image: your-exporter:latest
ports: ["9090:9090"] # Prometheus metrics
```
#### **Option B: Managed Services**
```
AWS: EventBridge (scheduler) → SQS (queue) → ECS/Fargate (workers)
with DynamoDB (metadata) + CloudWatch (metrics)
GCP: Cloud Scheduler → Pub/Sub → Cloud Run
with Firestore (metadata) + Cloud Monitoring
Azure: Logic Apps → Service Bus → Container Instances
with Cosmos DB (metadata) + Application Insights
```
### 9. **Safety Mechanisms**
```python
class SafeScheduler:
def __init__(self):
self.heartbeat = HealthCheck()
def run_cycle(self):
if not self.heartbeat.is_healthy():
logger.critical("Scheduler heartbeat failed! Pausing...")
return
try:
with db.transaction():
jobs = self.get_due_jobs()
for job in jobs:
self.schedule_job_safely(job)
except Exception as e:
logger.exception("Scheduler cycle failed")
self.alert_on_failure(e)
```
### 10. **Deployment Best Practices**
1. **Idempotency**: All jobs must be idempotent (safety net)
2. **Timeouts**: Enforce hard timeouts at worker level
3. **Backfill Protection**: Prevent accidental historical runs
4. **Dry Runs**: `--dry-run` flag to preview schedule
5. **Graceful Degradation**:
- If DB fails → jobs run but no dedup/concurrency control
- If queue fails → fallback to direct execution
6. **Canary Deployments**:
- Route 1% of jobs to new scheduler version
- Compare metrics before full rollout
### 11. **Critical Missing from Cron**
- **No overlapping runs** (enforced by concurrency caps)
- **No missed runs** (scheduler tracks actual vs scheduled)
- **No silent failures** (all failures tracked with context)
- **No thundering herd** (jitter + queue)
- **No blind execution** (full audit trail)
### 12. **Migration Strategy**
```bash
# 1. Parallel run (both cron and new system)
cron "*/5 * * * *" && new-scheduler --shadow-mode
# 2. Validate shadow mode outputs match
diff <(cron-logs) <(new-scheduler-logs --dry-run)
# 3. Gradually shift traffic
kubectl patch job/scheduler -p '{"spec":{"template":{"spec":{"containers":[{"name":"scheduler","env":[{"name":"MODE","value":"hybrid"}]}]}}}}'
# 4. Full cutover after validation
kubectl set env deployment/scheduler MODE=active
```
## Key Advantages Over Cron
| Feature | Cron | This System |
|---------|------|-------------|
| Deduplication | ❌ | ✅ (time-window based) |
| Jitter | ❌ | ✅ (±configurable seconds) |
| Concurrency Caps | ❌ | ✅ (per-job limits) |
| Failure Escalation | ❌ | ✅ (threshold-based alerts) |
| Visibility | ❌ (syslog) | ✅ (metrics + structured logs) |
| Distributed Safe | ❌ | ✅ (DB-backed locking) |
| Backfill Control | ❌ | ✅ (skip old runs) |
| Graceful Degradation | ❌ | ✅ (multiple failure modes) |
## Quick Start with Existing Tools
If building custom is too heavy, combine:
1. **Temporal.io** (workflow engine) + **Prometheus** + **Grafana**
2. **Apache Airflow** (with `SequentialExecutor` for cron replacement)
3. **Kubernetes CronJob** + **Vertical Pod Autoscaler** + ** custom metrics adapter**
**Minimal viable implementation** (500 lines):
```python
# scheduler.py
import schedule, time, random, redis, psycopg2
from datetime import datetime, timedelta
class CronReplacer:
def __init__(self):
self.redis = redis.Redis()
self.db = psycopg2.connect(...)
def run(self):
for job in self.get_due_jobs():
jitter = random.uniform(-job['jitter'], job['jitter'])
run_time = job['next_run'] + timedelta(seconds=jitter)
# Dedup check (minute granularity)
dedup_key = f"{job['id']}:{run_time.strftime('%Y%m%d%H%M')}"
if self.redis.setnx(dedup_key, 1):
self.redis.expire(dedup_key, 3660) # 61min TTL
self.enqueue(job, run_time)
```
This design provides **production-grade replacement** with:
- Zero duplicate runs (within jitter window)
- Controlled concurrency (never exceed limits)
- Automatic failure escalation
- Full observability (metrics, logs, traces)
- Safe distributed operation
- Graceful degradation paths
- Migration compatibility
The system can start simple (single-node + SQLite) and scale to distributed (PostgreSQL + Redis + multiple workers) without architectural changes.