Prompt
Need a job system that supports delayed execution and scheduling
Latest observation
Here’s a solid, practical job system design that supports both delayed execution and scheduled jobs.
Core idea
A job system usually has these parts:
- Job definition — what work to do
- Job queue — where jobs wait
- Scheduler — decides when jobs become runnable
- Workers — execute runnable jobs
- Storage — persists jobs so they survive restarts
Job states
Use a small state machine:
- Pending: created, not ready yet
- Scheduled: has a future execution time
- Ready: eligible to be picked up now
- Running: being executed by a worker
- Succeeded
- Failed
- Cancelled
Minimal data model
A job record might look like this:
{
"id": "job_123",
"type": "send_email",
"payload": { "userId": 42 },
"status": "scheduled",
"runAt": "2026-10-24T15:00:00Z",
"createdAt": "2026-10-24T14:30:00Z",
"updatedAt": "2026-10-24T14:30:00Z",
"attempts": 0,
"maxAttempts": 5,
"priority": 10
}
Key field:
runAt: when the job should be executed
How delayed execution works
When a job is created with a delay:
- set
runAt = now + delay - store it as
scheduled - a scheduler process periodically checks for due jobs:
- if
runAt <= now, move it toready
- if
Then workers only consume ready jobs.
How scheduling works
For recurring jobs, store a schedule expression:
- cron-like expression:
"0 9 * * *"for every day at 9 AM - or interval: every 5 minutes
Example:
{
"id": "job_456",
"type": "generate_report",
"payload": { "reportId": 7 },
"schedule": "0 9 * * *",
"nextRunAt": "2026-10-25T09:00:00Z",
"status": "scheduled"
}
Scheduler responsibilities:
- compute next run time
- enqueue a concrete job instance at that time
- update the next occurrence
Recommended architecture
1. Job API
Provides methods like:
enqueue(job)enqueueDelayed(job, delayMs)scheduleRecurring(job, cronExpr)cancel(jobId)
2. Persistent store
Use one of:
- PostgreSQL
- Redis
- MongoDB
For reliability, PostgreSQL is often the easiest and safest choice.
3. Scheduler service
Runs periodically or continuously:
- finds jobs where
runAt <= nowandstatus = scheduled - atomically marks them
ready
4. Worker pool
Workers:
- claim a ready job atomically
- process it
- mark success/failure
- retry if needed
Reliability concerns
To make it production-ready:
Atomic claiming
Prevent two workers from running the same job.
Example approach:
- worker updates job from
readytorunningusing a conditional update - only one worker succeeds
Retries
On failure:
- increment attempts
- if attempts < maxAttempts, reschedule with backoff
- else mark failed
Example backoff:
- 1 min, 5 min, 15 min, etc.
Idempotency
Jobs may run more than once in failure scenarios, so handlers should be safe to retry.
Lock timeout / heartbeat
If a worker crashes while running:
- use
lockedAt/leaseExpiresAt - scheduler can requeue expired running jobs
Simple workflow
Delayed job
- Client enqueues job with delay
- Job stored with
runAt = now + delay - Scheduler finds it when due
- Marks it ready
- Worker picks it up and runs it
Scheduled recurring job
- Client creates recurring schedule
- Scheduler calculates next occurrence
- When due, creates/activates job instance
- Worker executes it
- Scheduler computes the next run
Example SQL schema
CREATE TABLE jobs (
id UUID PRIMARY KEY,
type TEXT NOT NULL,
payload JSONB NOT NULL,
status TEXT NOT NULL CHECK (status IN ('scheduled', 'ready', 'running', 'succeeded', 'failed', 'cancelled')),
run_at TIMESTAMPTZ NOT NULL,
attempts INT NOT NULL DEFAULT 0,
max_attempts INT NOT NULL DEFAULT 5,
priority INT NOT NULL DEFAULT 0,
locked_at TIMESTAMPTZ NULL,
lease_expires_at TIMESTAMPTZ NULL,
created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
updated_at TIMESTAMPTZ NOT NULL DEFAULT now()
);
CREATE INDEX idx_jobs_status_runat ON jobs(status, run_at);
Picking jobs safely
Example pattern in SQL:
WITH cte AS (
SELECT id
FROM jobs
WHERE status = 'ready'
AND (lease_expires_at IS NULL OR lease_expires_at < now())
ORDER BY priority DESC, run_at ASC
LIMIT 1
FOR UPDATE SKIP LOCKED
)
UPDATE jobs
SET status = 'running',
locked_at = now(),
lease_expires_at = now() + interval '5 minutes'
WHERE id IN (SELECT id FROM cte)
RETURNING *;
This allows multiple workers without double-processing.
If you want something simpler
If you don’t need custom infrastructure, use an existing queue system that supports delayed jobs and cron-style scheduling:
- BullMQ (Node.js / Redis)
- Sidekiq (Ruby / Redis)
- Celery (Python)
- Hangfire (.NET)
- Quartz (Java)
- RQ (Python, simpler)
Suggested default design
If building from scratch, I’d recommend:
- PostgreSQL as storage
- a scheduler loop every few seconds
- workers using atomic claim + lease
- support for:
- delayed jobs
- recurring schedules
- retries with backoff
- cancellation
- priorities
If you want, I can also provide:
- a full database schema
- a sample implementation in Python/Node/Go
- an architecture diagram
- a Redis-based version