Prevent Overlapping Cron Jobs with Linux flock -n Non-Blocking Locks

Stop runaway duplicate cron processes and database lock pileups using kernel-managed util-linux flock -n file descriptors instead of brittle PID files.

Linux flock(2) Kernel Advisory File Locking Syscallutil-linux flock(1) Non-Blocking (-n) & Conflict Exit Code (-E)Kubernetes CronJob concurrencyPolicy: Forbid

Incident Symptom & Protocol Root Cause

Production Failure Symptom

When an external API or database query slows down from 90 seconds to 8 minutes, a */5 * * * * cron job spawns a new overlapping worker every 5 minutes until 40 stacked processes exhaust RAM, OOM-kill the server, or leave stale /tmp/job.pid lockfiles after a crash.

Scheduler Parser & Clock Mechanics

Standard cron daemons are fire-and-forget: crond never checks whether the previous PID finished before launching the next tick. Homegrown touch /tmp/lock or PID-file checks suffer from TOCTOU race conditions and wedge permanently after a reboot, power loss, or SIGKILL (-9).

Broken vs Verified Configuration

BrokenFragile PID-File Lock (Sticks Permanently After OOM / SIGKILL!)
# ANTI-PATTERN: If OOM killer sends SIGKILL (-9), trap NEVER runs!
# /tmp/sync.lock stays on disk and blocks all future cron runs until manual SSH!
#!/usr/bin/env bash
if [ -f /tmp/sync.lock ]; then
  exit 0
fi
touch /tmp/sync.lock
trap 'rm -f /tmp/sync.lock' EXIT
/opt/jobs/heavy-report.py
Verified FixKernel-Managed flock -n Wrapper (Auto-Releases on SIGKILL!)
# 1. Inline crontab wrapper with flock -n (non-blocking) and -E 0 (clean exit 0 on skip):
*/5 * * * * /usr/bin/flock -n -E 0 /run/lock/heavy-report.lock /opt/jobs/heavy-report.py

# 2. Self-locking bash script idiom (fd 9 tied to kernel open-file table):
#!/usr/bin/env bash
set -euo pipefail
exec 9>/run/lock/heavy-report.lock
if ! flock -n 9; then
  echo "Previous heavy-report instance still active; skipping tick." >&2
  exit 0
fi
# Add bounded runtime ceiling with GNU timeout so hung sockets cannot hold lock forever:
exec timeout --signal=TERM --kill-after=30s 25m /usr/bin/python3 /opt/jobs/heavy-report.py

Operational Deep Dive

Unlike userspace lockfiles, util-linux flock(1) acquires an advisory lock via the kernel's flock(2) syscall attached to an open file description in kernel memory. Even if your Python or Go process crashes with a segmentation fault or gets terminated instantaneously by the Linux OOM killer via SIGKILL (-9), the kernel closes all open file descriptors belonging to that process group and releases the lock atomically in zero milliseconds—stale locks are impossible!

Pay attention to two subtle pitfalls when deploying flock in production! First, NEVER delete (rm) the lockfile inside an EXIT trap! Deleting an inode while another process is waiting or opening the path creates a classic two-inode split-brain race where Process B locks the old unlinked inode while Process C creates and locks a brand-new inode at the same path, letting B and C run simultaneously! Leave the zero-byte lockfile in /run/lock/ permanently; only the kernel fd state determines whether it is locked.

Second, keep child background daemons from inheriting the lock file descriptor! If heavy-report.py forks a long-lived background helper without FD_CLOEXEC, that grandchild keeps fd 9 open and holds the lock even after the main job exits. Pairing flock with exec timeout 25m ... ensures both a hard execution ceiling and clean process cleanup, and passing -E 0 ensures skipped ticks exit 0 rather than triggering false error alerts (util-linux flock defaults to exit 1 when -n fails to acquire the lock unless -E 0 is given).

Cron Concurrency & Overlap Protection Patterns

Engine / CaseRuntime BehaviorProduction Remediation
Linux VM Crontab (util-linux flock)flock -n -E 0 /run/lock/app.lock cmd skips overlapping runs cleanly with exit code 0.Always pair with timeout(1) so a hung network socket cannot hold the lock forever.
Multi-node cluster / Shared NFS mountLocal /run/lock only protects a single host; flock over older NFS mounts can be unreliable.Across multiple hosts, use PostgreSQL pg_try_advisory_lock(key) or Redis lease locks.
systemd.timer + .serviceSingleton by default: systemd will not start a second instance of an active .service unit.Add RuntimeMaxSec=25m in [Service] to enforce hard timeout protection.
Kubernetes CronJobconcurrencyPolicy: Forbid skips overlap across the whole cluster via API server Job state.Pair with jobTemplate.spec.activeDeadlineSeconds to prevent hung pods.

Edge Cases & Engineering FAQs

Does macOS / FreeBSD ship util-linux flock by default?

FreeBSD ships lockf(1) natively (lockf -k -t 0 /tmp/app.lock cmd — notice -k keeps the file to avoid the unlink race!), while macOS uses lockf or launchd singletons.

How do I prevent overlapping runs across 3 active HA servers in PostgreSQL?

Acquire a session-level or transaction-level PostgreSQL advisory lock: SELECT pg_try_advisory_lock(hashtext('billing-sync')); returns true immediately for the winning worker and false for peers, and automatically releases if the TCP database connection drops!

Where should lock files live on modern Linux distributions?

Use /run/lock/ (tmpfs in RAM, cleared automatically on reboot) for root jobs, or $XDG_RUNTIME_DIR / /tmp/ with restrictive permissions (umask 077) for unprivileged service accounts to prevent symlink/DoS lock pre-creation by other local users.

Runtime Dead-Man's-Switch Verification

Heartbeat & Cron MonitoringBetter Stack →

Dead-man's-switch heartbeat checks that page on-call when a scheduled job skips a DST gap, stalls on a lock, or exits non-zero.