r/softwarearchitecture • u/Healthy_Camel • 35m ago
Discussion/Advice Scheduling tasks in production
I have a FastAPI with Postgres db app in production running on several instances behind a load balancer. Users can schedule some API external call to get some data to run at a specific date and time. These are one-off jobs, not recurring ones.
What I need:
• A job never runs before its scheduled time. A few seconds late is fine.
• A job runs once, not once per instance.
• Jobs survive restarts and deploys.
• Users can update or cancel a job, and that takes effect no matter which instance handles the request.
What I've considered:
- APScheduler inside the app. This breaks with multiple instances. Each instance keeps its own jobs in memory, so on startup every instance reloads the pending jobs and they all fire. An update that lands on instance B can't change the job held by instance A. As far as I can tell, APScheduler 3.x also doesn't support several schedulers sharing one job store.
- Celery with eta/countdown. I've read that jobs scheduled for a future time sit in the worker's memory, and that with Redis they can be delivered again after the timeout (1 hour by default). That sounds risky for jobs scheduled hours or days ahead. Cancelling also means keeping the database and the queue in sync.
- Postgres as the queue. Store jobs as rows, and have a separate worker poll every second or so with UPDATE … WHERE id IN (SELECT … WHERE status='pending' AND run_at <= now() FOR UPDATE SKIP LOCKED) RETURNING …. Updating or cancelling a job is then just a row update. This is my current favourite, but I'm not sure whether to write it myself or use something like Procrastinate.
- A managed scheduler (AWS EventBridge Scheduler, Google Cloud Tasks). I'd have nothing to run myself, but I'd have to keep my database and the scheduler in sync whenever a job is updated or cancelled.
Questions:
• What do you use for this in production, and how has it held up?
• If you went with Postgres as the queue: did you write the worker yourself or use a library? How do you handle a worker crashing mid-job and leaving it stuck as "running"?
• Is there a clean way to keep the scheduler inside the FastAPI process, or is a separate worker the standard answer?
• How can I cache the data if the job can never run before its scheduled time?
Thanks!
