Jobs
elements man jobsA job is a unit of work that a worker process runs outside a web request. Scheduling a job inserts a row in a queue, and a worker process takes the row from the queue and runs the job. Use a job for long-running or expensive work, so the web request that schedules the job responds without waiting for that work. Add workers to run more jobs at once.
Jobs and cron are built into Elements. Most applications need them: emails to send, payments to charge, exports to generate, digests to deliver. The build server boots a job server automatically, both locally and on every machine after deploy.
The job queue is the elements.jobs table, stored in the same Postgres
database as your app's tables. Because the queue is in your
database, enqueueing a job inside tx() joins the surrounding
transaction. The job row and your other writes commit together or not at
all. The queue is not stored in a separate system, so a job row never
exists without the writes it was committed with.
Call schedule() with no argument and the next available worker runs
the job. Call schedule() with a plain-English time string and the job
becomes eligible to run at that time.
Examplenew SendWelcomeJob({ userId, to, name }).schedule(); new SendFollowupEmailJob({ userId }).schedule("in 3 days"); new RetryPaymentJob({ orderId }).schedule("in 1h"); new ExpirePromoJob({ promoId }).schedule("tomorrow at 8am"); new WeeklyReminderJob({ userId }).schedule("next monday");
Cron runs code on a schedule, where a job runs when your code schedules
it. Send a daily digest at 9am,
score posts every five minutes, archive old rows nightly. app.cron(...)
is declared in the project's root index.ts. Every minute, each app
machine tries to update the single row in elements.cron_lease. Postgres
applies one of those updates, and the machine that made it runs the cron
callbacks due that minute, so each callback runs on exactly one machine.
Use cron and jobs together: the cron callback schedules a job, and the job does the work. A typical cron callback is one line that schedules a job and returns. The callback returns quickly, so the cron callbacks due in the next minute start on time. The work runs as a job, so it has retries, a timeout, and a worker pool you can scale.
index.tsapp.cron("every day at 9am", "daily digest", () => new SendDailyDigestJob().schedule()); app.cron("every 5m", "rank posts", () => new RankPostsJob().schedule()); app.cron("every day at 2am", "archive old rows", () => new ArchiveOldRowsJob().schedule());
At a Glance
app/jobs/send-welcome.tsimport { Job, email } from "@elements/app"; import WelcomeEmail from "#app/emails/welcome"; export interface SendWelcomeJobFields { userId: string; to: string; name: string; } export class SendWelcomeJob extends Job<SendWelcomeJobFields> { static maxAttempts = 5; static timeoutMs = 60_000; run() { let { to, name } = this.fields; email({ to, subject: "welcome", body: new WelcomeEmail({ name }), }); } }
Schedule it from an @rpc. Use tx() to make the user insert and the
job enqueue atomic:
app/shared/services/users.tsimport { tx, sql, ValidationError } from "@elements/app"; import { SendWelcomeJob } from "#app/jobs/send-welcome"; interface SignupForm { name: string; email: string; password: string; } /** @rpc */ export function signup(form: SignupForm): User { if (!form.email.includes("@")) { throw new ValidationError("invalid email"); } if (!sql(` select 1 from users where email = ${form.email} `).empty()) { throw new ValidationError("email taken"); } return tx(() => { let user = sql<User>(` insert into users ( name, email, passwordHash ) values ( ${form.name}, ${form.email}, crypt(${form.password}, gen_salt('bf', 12)) ) returning * `).firstOrThrow("insert returned no row"); new SendWelcomeJob({ userId: user.id, to: user.email, name: user.name, }).schedule(); return user; }); }
Because schedule() is called inside tx():
- The user row and the
elements.jobsrow are inserted in the same transaction. - If the transaction rolls back (validation failure, db error, anything thrown), neither row is written. There is never a user without a job or a job without a user.
- A worker can read the job row only after the transaction commits, so no worker runs a job whose transaction has not committed.
The Job Class
Type signatureexport abstract class Job<TFields extends object = {}> { static maxAttempts: number; // default 3 static timeoutMs: number; // default 30000 static priority: number; // default 100, 1 = top, higher = lower id: string; // uuid, set by Elements fields: TFields; // typed payload scratch: string; // absolute path to a per-job scratch dir abstract run(): void; schedule(arg?: string | JobScheduleArg): string; // sync-style; scheduleAsync returns Promise<string> }
Override run() with the work. Throws cause the job to be retried with
exponential backoff, up to maxAttempts times.
Per-class statics override the defaults:
app/jobs/heavy-import.tsexport class HeavyImportJob extends Job<{ url: string }> { static maxAttempts = 1; static timeoutMs = 600_000; static priority = 50; run() { /* ... */ } }
this.fields is the typed payload. this.id is the job uuid.
this.scratch is an absolute path to a private directory created before
run() and removed after (success or crash).
Scheduling
Usagenew SendWelcomeJob({ to, name }).schedule(); new SendWelcomeJob({ to, name }).schedule("in 1h"); new SendWelcomeJob({ to, name }).schedule({ at: "tomorrow at 8am" }); new SendWelcomeJob({ to, name }).schedule({ priority: 1 }); new SendWelcomeJob({ to, name }).schedule({ at: "next monday", idempotencyKey: `welcome:${userId}`, });
schedule() returns the job's uuid (a string).
JobScheduleArg:
at: when to become eligible. Time string. Omit for immediate.priority: 1-N. 1 = top. Default 100. Overridesstatic priority.idempotencyKey: dedupe key. At most one row per non-null key. Re-scheduling with the same key returns the existing id.
Time strings for at:
Time stringsin 5m, in 1h, in 3 days, in 2 weeks next monday, next tuesday, ... (case-insensitive, full weekday names) tomorrow, tomorrow at 8am next week
Transactional Scheduling
Called inside tx(), schedule() joins the surrounding transaction.
A worker can read the new job row only after that transaction commits.
If the transaction rolls back, the job row is never written.
Exampletx(() => { let order = sql<Order>(`insert into orders (...) values (...) returning *`).firstOrThrow("insert returned no row"); new ChargeCardJob({ orderId: order.id }).schedule(); new SendReceiptJob({ orderId: order.id }).schedule(); reserveStock(order); });
If reserveStock throws after both jobs were scheduled, the transaction rolls
back and the two job rows are never written: no card is charged and no receipt is
sent for an order that was never saved.
Every write in the transaction, the jobs included, commits together or not at all.
Cancel
Exampleimport { Job } from "@elements/app"; let id = new SendWelcomeJob({ ... }).schedule("in 1h"); let cancelled = Job.cancel(id);
Job.cancel(id) returns true if the job moved from pending to
cancelled. Returns false if the job is already running, completed,
failed, cancelled, or missing.
Retries
A throw from run() retries the job with exponential backoff up to
maxAttempts times: 2 seconds after the first failure, then 4, 8, and so on,
capped at an hour. A worker that crashes mid-job counts as a failed attempt
too. After the last failure, the job's state is set to failed. Failed rows stay
in elements.jobs for inspection.
A retry runs run() again from the top, so work it already did happens again.
A job that must never repeat a side effect, like charging a card, sets
static maxAttempts = 1 or records its progress and checks it on entry.
The timeoutMs static caps how long a single attempt can run. A worker
that exceeds it is killed and the job retries. Set timeoutMs higher
than the longest expected run, with margin.
The Scratch Directory
Each job invocation gets a private directory at this.scratch, created
before run() and removed after run() returns or throws. Use it for
temp downloads, intermediate files, and similar throwaway state.
File Layout
A job is one file under app/jobs/, scaffolded with
elements create job:
Terminalelements create job send-welcome -fields='to: string, name: string'
Generated fileapp/jobs/send-welcome.ts # exports SendWelcomeJob and its fields interface
Import it as #app/jobs/send-welcome. Tests for it go in a sibling
app/jobs/send-welcome.test.ts.
A class that extends Job is a job. The build finds every subclass of
Job and sets its path static, which a worker uses to load and
instantiate the class when it takes the job's row from the queue. A job
needs no build tag and no registration call.
Cron vs Jobs
- A cron callback runs at a scheduled time; a job runs when your code schedules it.
- Cron records each run in
elements.cron_runs; jobs persist inelements.jobs. - Jobs retry with exponential backoff up to
maxAttempts. - Jobs carry a typed
fieldspayload. - Cron runs on the elected leader app process; jobs run on a worker process.
- Use cron to start something at a set time. Use a job for work that must finish: a job is stored in the database and retried when it fails.
Cron + Jobs Together
Keep the cron callback small. Enqueue a job and return.
index.tsapp.cron("every 5m", "rank posts", () => new RankPostsJob().schedule()); app.cron("every day at 2am", "archive old rows", () => new ArchiveOldRowsJob().schedule()); app.cron("every monday at 9:30am", "weekly digest", () => new WeeklyDigestJob().schedule());
Why:
- The cron loop runs in the app process. The work runs in the worker. Long-running work in a cron callback would block subsequent ticks.
- Enqueuing a job gives the work retries, timeouts, and idempotency keys.
- Cron leader election and the job queue are both stored in the app's database, so using them together needs no other service.
Retention
Elements deletes old rows from the elements.* tables on a schedule. Success rows in
cron_runs and jobs are pruned to a 24-hour sliding window. Failed
rows are kept forever by default so you never miss an intermittent error.
Both windows are configurable per area in config.jsoc. Prune runs once
per day in an off-peak window (02:00–04:00 utc) in chunked transactions
that yield to live traffic. You never need to run delete on these
tables yourself.
config.jsoc{ jobs: { retention: { success: '24h', // delete completed/cancelled jobs after 24h error: 'never', // keep failed jobs forever }, }, crons: { retention: { success: '24h', error: 'never', }, }, }
Values are duration strings ('24h', '7d', '30d') or the literal
'never'. The two areas are configured independently. Defaults are
success: '24h', error: 'never'. Healthy apps have a near-zero error
rate, so failed-row growth stays tiny. Keeping failed rows is the safer
default: an intermittent failure you never see is the worse outcome.
Prune is implemented as chunked delete in batches of 1000 rows, each
batch its own short transaction with a 500ms lock_timeout and 2s
statement_timeout. A batch that waits over 500ms for a lock stops
the prune, and the next daily pass deletes the remaining rows. Inserts
from the running app do not wait behind the delete. The prune cron
entries are registered automatically as @elements/app:prune-cron-runs
and @elements/app:prune-jobs and show up alongside your own entries in
select * from elements.cron_runs.
Cron Leader Election
Only one app machine runs each cron tick, and a tick is one minute.
Each minute, every app process runs an update on the single row of
elements.cron_lease that succeeds only when no process has claimed
that minute yet. Postgres applies one of those updates, and the machine
that made it is the leader for the tick. Every other machine's update
returns zero rows, and that machine does nothing for the tick.
Each cron entry's cronFiresAt(schedule, tickBoundary) decides whether
it's due this minute. Due entries run sequentially within the leader.
Each run is recorded in elements.cron_runs (state, duration, error if
any).
Cron uses the database for leader election (elements.cron_lease) and
run history (elements.cron_runs). app.cron(...) throws at app start
if no database is configured.
The Worker
Worker processes connect to the same elements.jobs table. They pull
rows, instantiate the job class via its path static, populate id,
fields, and scratch, and call run().
Workers run independently, on one machine or many: every machine that shares
the app's Postgres cluster pulls from the same queue. Add workers or machines
to scale throughput.
Debugging
select * from elements.jobs where state = 'failed' order by updated_at desc;: failed jobs.select * from elements.cron_runs order by ran_at desc limit 50;: cron run history.- Per-job scratch directories are created under the worker's scratch root and are removed on completion.
Related
database:tx(), the transaction a job is scheduled in.channel: broadcast a message from the server to every listening browser.email: jobs are the right place to send transactional email.