Scheduling Tasks: Cron, Queues, and Background Jobs
Updated: Oct 19
A subscription business runs two kinds of background work. A nightly cron job on one server creates the day's invoices. A queue of "charge this invoice" jobs is processed by a pool of workers. Both have worked for a year.
Then two things happen in the same month. The server is rebuilt, and nobody reinstalls the crontab. No invoices are created for nine days, and the team finds out when a customer asks why they haven't been billed. Separately, 14 customers are charged twice. A worker charged the card, then was stopped by a deployment before it could mark the job done, and the queue handed the same job to another worker.
Neither failure produced an error. Background jobs fail by not running, or by running twice, and both are silent unless you design for them. This post covers the choices that decide whether yours will.
Decide what runs outside the request
Move work out of the user's request when it's slow, unreliable, or not triggered by the user at all. Then pick the mechanism by what starts the work:
What starts the work | Example | Mechanism | Main risk |
A clock | Nightly invoices, hourly cleanup | A scheduler: cron, a cloud scheduler, Kubernetes CronJob | The run that never happens |
An event in your app | Send a receipt, resize an upload | A queue plus workers | The job that runs twice |
A slow user action | Generate a 50-page report | A queue, plus a status the user can check | The user never hears it finished |
A schedule that fans out | Charge every invoice due today | A scheduler that enqueues one job per item | Both of the above |
The last row is the common shape for anything that matters. The scheduler only decides when work starts. Each unit of work goes on a queue, where it can be retried on its own.
The test: for each background job you run, write down what starts it and what happens if it doesn't run tonight. If you can't answer the second, that's the job to look at first.
Cron: make silence visible
Cron is simple and reliable at what it does: start a command at a time. Everything else is up to you.
It runs with a minimal environment. Cron sets SHELL to /bin/sh and takes HOME and LOGNAME from the user's account. It doesn't load your login profile, so a script that works in your terminal can fail under cron because a variable or tool path is missing. Use full paths and set what you need at the top of the crontab.
It doesn't stop overlapping runs. If an hourly job takes 90 minutes, two copies run at once. Wrap it in a lock: flock -n /var/lock/invoices.lock /opt/jobs/invoices.sh skips the new run if the old one still holds the lock.
It reports failure only by email. Output goes to the address in MAILTO, or to the crontab owner. On many servers, nobody reads that mail.
It can't tell you it didn't run. If the server is down or the crontab is gone, nothing runs and nothing reports it.
The last one caused the nine-day gap. The fix is a heartbeat, sometimes called a dead man's switch. At the end of a successful run, the job pings a monitoring endpoint. If no ping arrives within the expected window (26 hours for a daily job, for example), the monitor alerts. Several uptime and cron-monitoring services offer this, or you can build it with a timestamp in a database and a check that runs elsewhere.
If you run on Kubernetes, CronJob gives you some of this. concurrencyPolicy: Forbid skips a run while the previous one is still going, and startingDeadlineSeconds sets how late a missed run can still start. The documentation is explicit that scheduling is approximate: in some circumstances two Jobs may be created, or none, so your jobs "should be idempotent". A controller that has missed more than 100 schedules won't start the job at all.
The test: if your most important scheduled job stopped running tonight, when would you find out, and who would tell you? If the answer is "a customer", add a heartbeat.
Design every job to run twice
Queues guarantee that a job is delivered at least once, not exactly once. Amazon SQS's documentation says it directly: you might receive a message again, so "design your applications to be idempotent". The same is true of most queue systems.
Duplicates come from ordinary events, not rare ones. A worker takes a job, does the work, then crashes, times out or is stopped before it acknowledges the job. The queue can't tell the difference between "never processed" and "processed but not confirmed", so it hands the job to someone else. SQS calls the waiting period the visibility timeout. It defaults to 30 seconds. If your job can take longer than that, a second worker will pick it up while the first is still running.
The fix is to make the job's effect happen once, however many times the job runs. For anything with side effects, use an idempotency key:
job: charge_invoice(invoice_id = 8841)
1. Look up invoice 8841. If status is "paid", stop: already done.
2. Call the payment provider with idempotency key "invoice-8841".
The provider returns the original result for a repeated key
instead of charging again.
3. Mark invoice 8841 as "paid" in the same transaction that
records the payment reference.
4. Acknowledge the job.
Step 1 handles the common case cheaply. Step 2 handles the dangerous one: a crash between charging and recording. Many payment and messaging APIs accept an idempotency key for exactly this reason. Where an external service doesn't, record what you're about to do before you do it, and check that record on retry.
Then set the visibility timeout above your slowest normal run, and extend it from the worker for jobs that vary. SQS supports extending it while a job runs, up to 12 hours.
The test: in a test environment, run every job type twice with the same input. Any job that produces a second charge, email, row or file isn't safe yet.
Retry with backoff and jitter, and only what can succeed
Retries fix transient failures: a timeout, a rate limit, a dependency restarting. They make things worse when the failure isn't transient, or when everyone retries at once.
Marc Brooker's article in the Amazon Builders' Library shows how retries multiply. If each of several layers retries independently, load on the bottom layer can increase 243 times, "making it unlikely to ever recover". Backoff spaces retries out. A cap stops waits growing forever. Jitter, a random element in each wait, stops a batch of failed jobs retrying in lockstep. And, from the same article: "APIs with side effects aren't safe to retry unless they provide idempotency."
Not every error deserves a retry:
Error | Retry? | Why |
Timeout, connection reset, 503 | Yes, with backoff and jitter | Usually transient |
429 rate limited | Yes, after the time the service asks for | The service told you when |
400 bad request, validation error | No; send to the dead-letter queue | The same input will fail the same way |
401 or 403 | No; alert someone | Credentials or permissions changed |
Your own bug (exception in job code) | A few times at most, then dead-letter | Retrying won't fix the code |
The test: look at your retry configuration. Is there a cap on attempts, a maximum wait, and jitter? Does a validation error get retried? If it does, it's wasting attempts and delaying the alert.
Give the dead-letter queue an owner
A dead-letter queue (DLQ) holds jobs that failed every retry. SQS moves a message there after it has been received a set number of times (maxReceiveCount) without being deleted. Its documentation warns against setting that too low, so transient failures get enough retries first.
A DLQ is only useful if someone looks at it. Treat it as an inbox:
Alert when anything arrives. For a payment or billing queue, one message is an incident. SQS recommends monitoring a DLQ by the number of visible messages.
Name an owner for each DLQ, the same way you'd name an owner for an alert.
Keep messages longer than the source queue does. SQS keeps a message's original timestamp when it moves to the DLQ, so a DLQ with the same retention period deletes messages early.
Replay deliberately. Fix the cause, then move messages back with the queue's redrive feature. Because jobs are idempotent, replaying one that partly succeeded is safe.
The test: how many messages are in your dead-letter queues right now, and how old is the oldest? If nobody knows, nobody owns them.
Watch the age of the oldest job, not just the count
Queue depth tells you how much is waiting. Age tells you whether anyone is waiting too long. A queue of 10,000 small jobs draining fast can be healthy, and a queue of 12 that haven't moved in an hour isn't.
SQS publishes ApproximateAgeOfOldestMessage for this. One catch from its documentation: in a standard queue, a "poison pill" message that's repeatedly received but never deleted is excluded from that metric. A job that fails forever can hide from your age alarm, which is another reason to have a DLQ and alert on it.
Alert on:
Age of the oldest job, against how quickly the work needs to happen.
Messages in any DLQ.
Job failure rate, by job type.
For scheduled jobs, a missing heartbeat.
The test: for your most important queue, what age of the oldest job would mean users are affected? Set the alarm there, not at an arbitrary depth.
Stop workers without losing work
Deployments and scaling stop workers constantly. A worker should finish or hand back its current job when asked to stop, not die mid-job.
Handle the stop signal. Most platforms send SIGTERM first. On it, stop taking new jobs, finish the current one, acknowledge it, then exit.
Fit the grace period to the job. If the platform kills the process before a long job finishes, either lengthen the grace period or split the job into smaller ones.
Rely on idempotency for the rest. Some jobs will still be interrupted. The visibility timeout returns them to the queue, and idempotent design makes the rerun safe.
The test: deploy your workers while a long job is running. Does the job finish, or reappear and run cleanly a second time? Either is fine. A half-done job that never completes is not.
A worked example
Here is the composite business from the opening. The figures are illustrative.
Before
Invoice creation cron on one server, no heartbeat
Charging queue workers, visibility timeout 30 s (default)
Slowest charge job about 45 s when the provider is slow
Failures none logged as errors
Missed invoice runs after a server rebuild 9 days, found by a customer
Customers charged twice in one month 14
Changes
Scheduler moved off the single server; overlap blocked
Heartbeat ping after each successful run; alert after 26 h of silence
charge_invoice made idempotent: paid-status check plus
provider idempotency key "invoice-<id>"
Visibility timeout 3 min, extended by the worker for slow calls
Workers finish the current job on SIGTERM before exiting
DLQ alarm at 1 message; retention 14 days, longer than the source queue
Alarm on oldest charge job older than 15 min
Next quarter
Duplicate charges 0
Missed runs caught by the heartbeat 1, within 26 h
Jobs replayed from the DLQ after a fix 6, none charged twice
The team didn't switch queue systems or add more workers. They assumed jobs would run twice or not at all, and designed for both.

What to do this week
List your background jobs and, for each, what starts it and what happens if it doesn't run. Add a heartbeat to the most important scheduled job. Run each job type twice in a test environment and fix any that produce a second side effect. Check your retry settings for a cap, a maximum wait and jitter, and stop retrying validation errors. Make sure every dead-letter queue alerts someone by name. If your jobs send email, Email That Actually Reaches the Inbox covers what happens after the job succeeds.
Final takeaway
Background jobs fail by not running or by running twice, and neither raises an error unless you design for it. Choose a scheduler for clock-driven work and a queue for event-driven work, and let schedules fan out into individual jobs. Give scheduled jobs overlap protection and a heartbeat that alerts on silence. Assume every queued job will run more than once, and make its effect happen once with a status check and an idempotency key. Retry transient errors with capped backoff and jitter, send everything else to a dead-letter queue someone owns, and alert on the age of the oldest job.
Sources
Amazon Web Services, "Amazon SQS at-least-once delivery", Amazon SQS Developer Guide: a message copy may be received again; "Design your applications to be idempotent". https://docs.aws.amazon.com/AWSSimpleQueueService/latest/SQSDeveloperGuide/standard-queues-at-least-once-delivery.html
Amazon Web Services, "Amazon SQS visibility timeout", Amazon SQS Developer Guide: default 30 seconds; a message not deleted before the timeout becomes visible again; can be extended up to 12 hours. https://docs.aws.amazon.com/AWSSimpleQueueService/latest/SQSDeveloperGuide/sqs-visibility-timeout.html
Amazon Web Services, "Using dead-letter queues in Amazon SQS" and "Available CloudWatch metrics for Amazon SQS": maxReceiveCount, retention guidance, ApproximateAgeOfOldestMessage and its exclusion of repeatedly received messages. https://docs.aws.amazon.com/AWSSimpleQueueService/latest/SQSDeveloperGuide/sqs-dead-letter-queues.html and https://docs.aws.amazon.com/AWSSimpleQueueService/latest/SQSDeveloperGuide/sqs-available-cloudwatch-metrics.html
Brooker, M., "Timeouts, retries, and backoff with jitter", Amazon Builders' Library: independent retries across layers can increase database load 243 times; jitter spreads retries; "APIs with side effects aren't safe to retry unless they provide idempotency." https://builder.aws.com/content/3EumjoZascWd1oZiEgL8ORlv3qE/timeouts-retries-and-backoff-with-jitter
Kubernetes, "CronJob": concurrencyPolicy (Allow, Forbid, Replace), startingDeadlineSeconds, two Jobs or none may be created so Jobs "should be idempotent", more than 100 missed schedules stops the Job. https://kubernetes.io/docs/concepts/workloads/controllers/cron-jobs/
crontab(5), Linux manual page: SHELL set to /bin/sh, HOME and LOGNAME from the passwd entry, MAILTO behaviour. https://man7.org/linux/man-pages/man5/crontab.5.html
Related reading
Keep learning. This article is part of the Automation & Process Improvement path in the ShiftQuality Learning Center. Remove the repetitive work — and keep the automation from becoming new debt.


