Making Cron Jobs Idempotent With flock and a Lock Table
Bottom line: Overlapping schedules and retries cause most duplicate cron runs, and you can stop both with flock for host-local exclusion plus a database lock row for cross-host exclusion, in under 20 lines of shell.
The pattern below assumes you run the same job on more than one host — a pair of app servers, a primary/standby pair, or a small fleet behind a scheduler. flock alone handles the single-host case cleanly and costs nothing. It cannot see other machines, so on a fleet you also need a shared arbiter. A row in your existing database is the cheapest arbiter you already have.
Why duplicates happen when your code is correct
Three failure modes produce the same symptom — the job runs twice — without any bug in the job itself:
- Overlap. A schedule fires every 5 minutes but the job occasionally takes 7. Nothing in cron knows the previous run is still going.
- Retries. Your wrapper, your orchestrator, or a human reruns the job because the first attempt timed out. The first attempt is still alive and working.
- Multi-host scheduling. A cron entry is deployed by configuration management to every host in a group. All of them fire at the same minute.
Only the third one needs a shared lock. The first two are solved locally, and the local lock is what makes the shared lock safe to hold for a long time.
Host-local exclusion with flock
flock takes an advisory lock on a file or directory and holds it for the lifetime of the wrapped command. Two forms matter here:
1 | # non-blocking: exit immediately if another run holds the lock |
-n is the right default for a scheduled job. If the previous run is still going, you want this run to exit fast and log a skip, not queue up behind it and start a backlog. -w is useful when the previous run is expected to finish imminently.
The lock file is created if it does not exist, assuming permissions allow it. Put it somewhere with a predictable owner — /var/lock or /run/lock if your distribution supports it, otherwise a path under /var/lib owned by the cron user.
Two flags worth knowing:
| Flag | Effect | When you want it |
|---|---|---|
-n / --nonblocking |
Fail instead of waiting if the lock is held | Scheduled jobs; skip-and-log semantics |
-w / --timeout |
Wait up to N seconds (decimals allowed; 0 means non-blocking) |
Short expected overlap |
-E / --conflict-exit-code |
Exit status on lock conflict, default 1, range 0–255 |
Distinguish “busy” from “job failed” |
-o / --close |
Close the lock fd before running the command | The child spawns long-lived helpers that must not inherit the lock |
-F / --no-fork |
Exec the command directly instead of forking | Saves a process; incompatible with -o |
Exit status is the part people get wrong. With -n or -w, a failure to acquire the lock exits with the -E value, default 1. But when the command does run, flock returns the child’s exit status. So a wrapper that treats any non-zero as “job failed” will page you every time a run is skipped. Set -E to something distinct — 75 (EX_TEMPFAIL from sysexits.h) is a defensible choice — and handle it explicitly.
Cross-host exclusion with a lock row
A database row gives you an atomic test-and-set across every host that can reach the same database. PostgreSQL’s SELECT ... FOR UPDATE with NOWAIT and SKIP LOCKED makes this a single statement.
Create the table once:
1 | CREATE TABLE job_lock ( |
Acquire, then run, then release:
1 |
|
Three things make this correct:
- The
ON CONFLICT ... WHERE expires_at < now()clause is the atomic test-and-set. Two hosts racing get exactly one winner because the row update is serialized by the primary key. - The
trap ... EXITreleases the row on any exit path, includingset -efailures. expires_atis a lease. If a host dies mid-job, the row goes stale and the next scheduled run on any host can take it. Set the lease comfortably longer than the worst observed runtime.
The flock around the whole thing is not redundant. It serializes the acquire and release sequence on each host, which means a slow psql call cannot interleave with a retry on the same machine and produce a second acquire after the first released.
Choosing the lease duration
The lease is the only knob with real consequences. Too short and a slow run loses its lock and a second host starts a duplicate. Too long and a crashed host blocks the job for that duration.
| Job runtime profile | Lease | Notes |
|---|---|---|
| Under 1 minute, stable | 5–10 minutes | Covers normal jitter with wide margin |
| 1–15 minutes | 2× p99 runtime | Measure p99, not the average |
| 15–60 minutes | 2× p99, cap at 2 hours | Longer leases need monitoring |
| Over an hour | 2× p99 plus a heartbeat | Renew from inside the job |
For anything past 15 minutes, add a heartbeat: an UPDATE job_lock SET expires_at = now() + interval '10 minutes' WHERE job_name = ... AND owner = ... every few minutes from inside the job. If the update affects zero rows, another host has taken over and the job should abort immediately.
Pitfalls and how to diagnose them
flock silently fails on NFS and CIFS. The manual page is explicit: some filesystems have a limited flock(2) implementation and flock may always fail, depending on mount options. If your lock file lives on a network mount, you get either permanent skipping or no exclusion at all. Diagnose by checking mount | grep <lockdir> and moving the lock file to a local filesystem. The lock is per-host anyway; there is no reason for it to be shared.
The lock is inherited by children. If your job spawns a daemon or a long-lived subprocess, it inherits the file descriptor and holds the lock after the parent exits. The next run then skips forever. Use flock -o or, when invoking from a script, flock -n 9 with the fd explicitly closed in the child. Symptom: flock never blocks, but the job never runs either.
The lock file gets deleted by cleanup. tmpwatch, systemd-tmpfiles, or a logrotate rule removes the lock file while a job holds it. The lock still exists on the open file description, but the next run creates a new file and acquires a different lock. Keep lock files out of /tmp, or exempt them from cleanup. Symptom: exclusion works most of the time and fails after a specific interval.
The lease expires while the job is still running. The second host acquires, both run, and you get duplicate writes. Diagnose by logging acquired_at, expires_at, and job end time on every run; if end time exceeds expires_at more than occasionally, the lease is too short or the job needs a heartbeat.
The trap does not fire. trap ... EXIT does not run if the shell is SIGKILLed. In that case the lease is your only recovery, which is why it must exist. Symptom: job_lock shows a row owned by a host that has been down for hours. The lease handles this automatically; do not “fix” it by deleting the row manually unless the job is known to be dead.
Two schedules for the same job. A systemd timer and a cron entry both invoke the script. Neither lock is wrong; they just both work. Audit with systemctl list-timers and crontab -l on each host before adding the locks, so you know what you are actually serializing.
FAQ
Does flock work on macOS or BSD?
Not the same way. The flock(1) command is Linux-specific; macOS ships shlock or you use mkdir-based locking. The shell pattern is identical, but you need a different primitive. If you run mixed fleets, put the exclusion in the database row and treat the local lock as an optimization.
Why not just use flock -w instead of -n?
-w makes a second run wait for the first, which turns an overlap into a queue. For a job scheduled every 5 minutes with 7-minute runtimes, that queue grows until you are permanently behind. Skipping is the correct behavior when a job is already running; the next scheduled invocation will pick it up.
Is SELECT ... FOR UPDATE NOWAIT better than the ON CONFLICT upsert?
Both work. FOR UPDATE NOWAIT requires a row to already exist and needs a transaction spanning the job, which is a bad idea for a long-running process. The ON CONFLICT upsert with a lease is a single statement with no transaction to manage. Prefer the upsert unless you already have a transaction-shaped wrapper.
What happens if the database is unreachable?
The psql call fails, set -e aborts, the job does not run. That is the safe default: no lock, no work. If you need to fail open, you must decide explicitly whether a duplicate run is cheaper than a missed run, and log the choice. Most reporting and billing jobs should fail closed.
Can I use Redis or etcd instead of a database row?
Yes, and the pattern is the same: SET key value NX PX <ttl> in Redis, or a lease with a TTL in etcd. The database is the default recommendation because you already operate it, back it up, and can inspect the lock table with the same tools you use for everything else. A second datastore is a second thing to page on.
How do I test that this actually works?
Run the job under flock from two terminals simultaneously and confirm the second exits with your -E code. Then simulate the cross-host case by pointing two shells at the same database with different HOST values. Finally, kill -9 a running job and confirm the next invocation acquires the lock only after expires_at passes. All three tests take a few minutes and catch every mistake listed above.









