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.

WorkflowCadenceQualifying rows filterIdempotency marker
24-hour booking remindersHourlyConfirmed bookings starting within 24 hours with reminder_sent_at nullStamp reminder_sent_at immediately after send
Stale unpaid hold cleanupEvery 15 minPending holds older than 20 minutesGuarded update pending to expired
Weekly member digestMonday 09:00 UTCOpted-in members missing a row for current ISO weekUnique key in digest_deliveries(user_id, week_key)
Trial expiry noticesDailyAccounts with trial_ends_at under 3 days and flag unsetStamp trial_warning_sent_at
Orphan upload cleanupNightlyUnattached draft files older than 24 hoursDelete 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 hours AND reminder_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.
json
{
  "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_SECRET in environment settings and verify Authorization: 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-in admin role 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.

text
# 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`): 100 emails/month — best for testing and early bookings.
  • Starter (`$4.99/mo` or `$3.99/mo` annual): 1,000 emails/month — ideal for local studios, clinics, and memberships.
  • Pro (`$25/mo` or `$20/mo` annual): 10,000 emails/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

  1. 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.

  2. 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 a job_runs audit row.

  3. 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.

  4. 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 0 new rows.

  5. Configure Live secrets and monitor

    Add a distinct CRON_JOB_SECRET in Live, publish, point your scheduler at your Live URL, and inspect job_runs in Cloud (Live).

Starter prompt · App

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.

Starter prompt · App

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

SymptomRoot causeExact fix
Customers get duplicate reminder emailsQuery filters by time only without stamping a sent columnAdd reminder_sent_at (or unique delivery table) and require IS NULL
Job times out past 500 rowsUnbounded query lacks an index or batch limitIndex (status, starts_at) and process LIMIT 50 rows per run
Late Stripe payment overwritten as expiredCleanup updates rows blindly without checking statusGuard updates with WHERE status = 'pending' before expiring holds
Reminder times shift by an hour during DSTStored local wall-clock strings instead of UTCStore UTC timestamps and format using each booking's IANA time zone
Automated emails pause mid-monthDaily digests hit Free (100/mo) or Starter (1,000/mo) capReview job_runs, switch non-urgent sends to weekly, or upgrade in Plans & credits

Next steps

Still have a question?Ask our team and other builders on Discord.

From the blog