Scheduled jobs & workflows
Automate recurring business workflows like booking reminders, weekly digests, and expired-record cleanup with idempotent state checks that stay safe on retries.
How scheduled jobs differ from user-triggered routes
Most web app endpoints execute when someone clicks a button or submits a form. Scheduled jobs handle actions triggered purely by passing time, even when zero visitors are online.
Typical examples include emailing a guest 24 hours before an appointment, releasing unpaid checkout holds after 20 minutes, sending a Monday summary to admins, or archiving expired promo codes nightly.
Instead of slowing down visitor page loads with heavy loops, recurring workflows run through dedicated server job routes guarded by secrets and tracked cleanly inside your Cloud tables.
Common recurring workflow patterns
Define four details before implementing any scheduled task: run frequency, qualifying row filter, side effect, and the database marker proving a row was already handled.
| Workflow | Cadence | Qualifying rows filter | Idempotency marker |
|---|---|---|---|
| 24-hour booking reminders | Hourly | Confirmed bookings starting within 24 hours with reminder_sent_at null | Stamp reminder_sent_at immediately after send |
| Stale unpaid hold cleanup | Every 15 min | Pending holds older than 20 minutes | Guarded update pending to expired |
| Weekly member digest | Monday 09:00 UTC | Opted-in members missing a row for current ISO week | Unique key in digest_deliveries(user_id, week_key) |
| Trial expiry notices | Daily | Accounts with trial_ends_at under 3 days and flag unset | Stamp trial_warning_sent_at |
| Orphan upload cleanup | Nightly | Unattached draft files older than 24 hours | Delete object, then mark row purged |
Notice how the database itself tracks completion. Never filter by a razor-thin window like "starts in exactly 24 hours", or a brief scheduler delay will skip customers permanently.
Making scheduled jobs idempotent and safe to re-run
The golden rule of background automation is idempotency: running the exact same job twice — or resuming after a crash at row 35 of 50 — must never send duplicate emails or double-release inventory.
Four design rules for safe re-runs
- Filter by state flags, not exact clock ticks. Query
starts_at <= now() + 24 hoursANDreminder_sent_at IS NULL. Delayed runs catch up cleanly without missing rows. - Stamp progress per record. Update
reminder_sent_at(or insert the unique delivery key) right as each item completes, not at the very end of a big loop. - Cap batch size per invocation. Limit each call (
LIMIT 50 ORDER BY starts_at ASC) so sudden backlogs never hit timeouts; subsequent runs drain remaining rows safely. - Log every run in `job_runs`. Store job name, mode, start/end timestamps, processed count, and error count in Cloud for fast visibility.
{
"table": "job_runs",
"columns": {
"id": "uuid primary key",
"job_name": "text not null",
"mode": "text not null default 'live'",
"started_at": "timestamp with time zone not null",
"finished_at": "timestamp with time zone",
"processed_count": "integer not null default 0",
"error_count": "integer not null default 0",
"status": "text not null"
}
}Protecting job endpoints and separating Preview from Live
Unprotected automation endpoints let automated scanners spam your users or wipe pending records. Lock down every trigger path cleanly:
- Authenticate with a server secret. Store a random
CRON_JOB_SECRETin environment settings and verifyAuthorization: Bearer <secret>on every scheduled call. See Secrets & API keys. - Gate manual dashboard triggers by role. If admins have a "Run now" button in
/admin/jobs, verify the signed-inadminrole server-side; see Authentication & roles. - Build in `dryRun=true` mode. Dry runs execute the exact selection query and return matched IDs and counts without sending emails or updating rows.
Time zones, cron schedules, and email quotas
Storing UTC timestamps cleanly
Save every timestamp (starts_at, expires_at, reminder_sent_at) in UTC inside your database. Compute cutoffs server-side in UTC and format display times into the customer's local time zone strictly when rendering screens or emails.
# Clean cron cadence reference (UTC)
*/15 * * * * # Every 15 minutes (stale-cart or unpaid-hold cleanup)
0 * * * * # Top of every hour (24-hour booking reminder sweep)
0 8 * * * # Daily at 08:00 UTC (expiring trial notices)
0 9 * * 1 # Every Monday at 09:00 UTC (weekly digest email)Checking monthly email allowances
Automated reminders scale with active customers. Confirm your projected monthly volume fits your plan allowance before turning on daily sends:
- Free (`$0/mo`):
100emails/month — best for testing and early bookings. - Starter (`$4.99/mo` or `$3.99/mo` annual):
1,000emails/month — ideal for local studios, clinics, and memberships. - Pro (`$25/mo` or `$20/mo` annual):
10,000emails/month — suited for active SaaS digests and high-volume alerts.
Authenticate your custom sending domain in Branded email so automated reminders avoid spam filters.
Building and verifying a scheduled workflow
Add state columns and indexes in Cloud
Add nullable tracking fields (
reminder_sent_at) and index(status, starts_at)so sweeps stay fast at scale.Build the guarded job route with dry-run mode
Authenticate via
CRON_JOB_SECRET(or admin role for manual UI triggers), cap batches at 50 rows, and write ajob_runsaudit row.Verify selection with `dryRun=true` in Preview
Seed one past booking, one 12 hours away, and one 5 days away; confirm dry run selects solely the 12-hour booking.
Prove idempotency with two back-to-back runs
Run the real job twice in Preview and confirm the test email sends once while run two reports
0new rows.Configure Live secrets and monitor
Add a distinct
CRON_JOB_SECRETin Live, publish, point your scheduler at your Live URL, and inspectjob_runsin Cloud (Live).
Build an idempotent booking reminder job. Add nullable reminder_sent_at and an index on (status, starts_at) to bookings, plus a job_runs table. Create POST /api/jobs/booking-reminders protected by Authorization: Bearer process.env.CRON_JOB_SECRET (and callable by signed-in admins on /admin/jobs). Support dryRun=true, select up to 50 confirmed bookings starting within 24 hours with reminder_sent_at null, email each guest, stamp reminder_sent_at immediately per row, and log counts to job_runs.
Create POST /api/jobs/expire-holds protected by CRON_JOB_SECRET. Select pending bookings older than 30 minutes with no completed payment, run a guarded update setting status='expired' WHERE status='pending', release their slots, and record a job_runs entry so late Stripe confirmations are never overwritten.
Common mistakes and troubleshooting
| Symptom | Root cause | Exact fix |
|---|---|---|
| Customers get duplicate reminder emails | Query filters by time only without stamping a sent column | Add reminder_sent_at (or unique delivery table) and require IS NULL |
| Job times out past 500 rows | Unbounded query lacks an index or batch limit | Index (status, starts_at) and process LIMIT 50 rows per run |
| Late Stripe payment overwritten as expired | Cleanup updates rows blindly without checking status | Guard updates with WHERE status = 'pending' before expiring holds |
| Reminder times shift by an hour during DST | Stored local wall-clock strings instead of UTC | Store UTC timestamps and format using each booking's IANA time zone |
| Automated emails pause mid-month | Daily digests hit Free (100/mo) or Starter (1,000/mo) cap | Review job_runs, switch non-urgent sends to weekly, or upgrade in Plans & credits |