Stage 3 · Build
Caching, Queues & Background Jobs
Background Scheduling
Run cron-like jobs with robfig/cron, distributed locks, idempotency keys, and job observability.
Why Background Jobs
Not all work belongs in an HTTP handler. Sending emails, generating reports, cleaning up stale data, and syncing external services should run in the background. Scheduled jobs handle periodic tasks without user interaction.
robfig/cron
Distributed Locks
When running multiple instances, the same cron job runs on every instance. Use distributed locks to ensure only one instance executes the job.
Idempotency
Job Observability
Scheduling Patterns
- Cleanup jobs: Remove expired sessions, stale data, old logs.
- Sync jobs: Pull data from external APIs, update caches.
- Report jobs: Generate daily/weekly reports, send summaries.
- Health jobs: Check dependency health, restart failed services.
- Rotation jobs: Rotate API keys, certificates, encryption keys.
Always log when a job starts, completes, or fails. Include the job name, duration, and any errors. This makes debugging scheduled job issues possible.
Mark this lesson complete to store local progress and unlock a cleaner resume path the next time you visit.