# 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.

- **Canonical URL**: https://opslint.dev/cron/flock-prevent-overlapping-cron-flock-wrappers/
- **Category**: `CRON`
- **Interactive Workbench**: [Open in Live Workbench](https://opslint.dev/cron/#expr=*%2F5%20*%20*%20*%20*&tz=UTC)
- **Normative Specifications**: `Linux flock(2) Kernel Advisory File Locking Syscall`, `util-linux flock(1) Non-Blocking (-n) & Conflict Exit Code (-E)`, `Kubernetes CronJob concurrencyPolicy: Forbid`

## Incident Symptom & Root Cause

**Production 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.

**Protocol / Engine Root Cause**: 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).

## Remediation Diff (Broken vs Verified Fix)

### Fragile PID-File Lock (Sticks Permanently After OOM / SIGKILL!)

```text
# 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
```

### Kernel-Managed flock -n Wrapper (Auto-Releases on SIGKILL!)

```text
# 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
```

## Engineering 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

| Case / Engine | Protocol Behavior | Production Remediation |
| :--- | :--- | :--- |
| **Linux VM Crontab (util-linux flock)** (`#flock-nonblocking-skip`) | 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 mount** (`#flock-nfs-caveat`) | Local /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 + .service** (`#systemd-service-singleton`) | Singleton 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 CronJob** (`#k8s-forbid-deadline`) | concurrencyPolicy: Forbid skips overlap across the whole cluster via API server Job state. | Pair with jobTemplate.spec.activeDeadlineSeconds to prevent hung pods. |

## Frequently Asked Engineering Questions

### 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.

## Related Problem-Cluster Guides

- [Kubernetes CronJob .spec.timeZone, CRON_TZ Rejection, and ConcurrencyPolicy Guide](https://opslint.dev/cron/kubernetes-cronjob-timezone-and-concurrency-policy/) — Configure IANA timezones safely in Kubernetes v1.27+ CronJobs, fix rejected CRON_TZ/TZ prefixes in .spec.schedule, and choose between Forbid and Replace.
- [systemd OnCalendar vs POSIX Cron: AND Logic, Reverse Offsets (~), and Persistent=true](https://opslint.dev/cron/systemd-oncalendar-to-cron-and-logic-differences/) — Avoid critical translation bugs between systemd.timer OnCalendar expressions and 5-field POSIX cron, including DOM+DOW intersection, seconds, and missed boot catch-up.
- [Fix Cron Jobs That Work in Terminal SSH But Fail Silently in Crontab (PATH, SHELL, Env)](https://opslint.dev/cron/cron-environment-path-locale-silent-failures/) — Diagnose why cron runs with minimal PATH=/usr/bin:/bin, /bin/sh (dash) instead of bash, missing SSH/cloud credentials, and C locale.
- [Prevent Duplicate Cron Execution During Daylight Saving Time Fall Back (01:00–01:59 Overlap)](https://opslint.dev/cron/dst-fall-back-duplicate-execution/) — Diagnose and prevent double-firing cron jobs during the November DST fall-back hour across Kubernetes CronJob, Vixie Cron, and AWS EventBridge.
