Publishing Operations
Making WordPress Cron and Background Queues Reliable in Production
A practical design for deterministic WordPress scheduling, idempotent workers, overlap prevention, retries, dead-letter handling, and operational visibility.
Author: Fahad Bin Shakir · Published: · Updated: · 6 min read

Introduction
WordPress can schedule future work, but its default trigger is opportunistic: a web request checks whether events are due. Low traffic can make jobs late, while a traffic surge can make several processes compete to run expensive work. Imports, newsletter preparation, image processing, cache warming, and scheduled publication then become coupled to visitor behavior even though their reliability requirements are completely different.
A production queue needs a deterministic trigger, exclusive claims, bounded work, safe retries, and evidence about what happened. The same design should survive a worker crash after an external side effect, a database slowdown, a deployment during processing, and a malformed record that can never succeed. Reliability comes from explicit state transitions rather than a larger timeout around one long PHP request.
Inventory scheduled work and its real service level
List every recurring and single event, its callback owner, expected frequency, typical duration, peak duration, and consequence of delay. A cache cleanup can be late without visible harm; a scheduled article or security feed may have a strict window. Inspect duplicate hooks and abandoned plugin schedules. The inventory should include application queues that use custom tables or Action Scheduler, not only entries visible through the core cron API.
Classify each task by whether it is safe to run twice, can be split into batches, calls an external system, and needs ordered execution. Capture current queue age, success rate, retry count, and resource use before changing triggers. Without that baseline, moving cron to the operating-system scheduler may make timing consistent while leaving overlap, poison messages, and silent failure unchanged.
Use a deterministic trigger without creating overlap
Disable request-driven spawning only after a system scheduler is configured to invoke the due-event runner at an appropriate interval. Run through the application environment and correct PHP version, with the same configuration and permissions as production. Capture exit status and duration. A scheduler that invokes the wrong release path or ignores failures provides false confidence.
Protect jobs that cannot overlap with an atomic lease or database-backed claim. A plain option check followed by an update has a race between the two operations. The lease needs an owner token and expiry so a crashed worker does not block the job forever. Renewal should occur only while real progress continues, and release should verify the owner token before clearing another worker's lease.
Make every unit idempotent
Assume a worker can stop after sending a request but before recording success. Give each logical operation a stable idempotency key and store its state transition transactionally where possible. For publication, the key might combine content ID and target revision. For an external API, send the same key if the provider supports it and reconcile uncertain responses before retrying.
Separate claiming work from performing it. A worker should atomically move a limited set from pending to processing with an owner and lease deadline. Completion records the result; failure records a categorized reason and next attempt. Avoid loading an unbounded pending set into memory. Small batches keep locks short, allow fair progress, and make deploy or shutdown behavior predictable.
Retry transient failures without amplifying them
Retry only failures likely to recover: temporary network errors, rate limits, or bounded service unavailability. Use exponential backoff with jitter and a maximum attempt count. Immediate synchronized retries can turn a dependency incident into sustained overload. Respect a valid Retry-After value, but cap it within the business deadline and queue policy.
Validation errors, missing required data, and unsupported operations should not cycle forever. Move them to a failed or dead-letter state with a safe operator view that excludes secrets. Record the code path, attempt count, sanitized error category, and correlation identifier. Replaying a failed item should create an auditable transition and preserve the original evidence rather than silently resetting history.
Design deployment and shutdown behavior
A deployment can replace code while an old worker still owns a job. Keep payloads versioned and backward-compatible across the rollout window, or drain workers before switching. Workers should stop claiming new items when shutdown begins, finish or safely release the current bounded unit, and exit within the process manager's grace period. Long monolithic callbacks make graceful behavior impossible.
Database migrations and worker code must deploy in compatible phases. Add new columns or states first, release code that understands both shapes, backfill in bounded batches, then remove legacy behavior later. Include the scheduler and worker in smoke tests: enqueue a harmless synthetic item, observe it move through the expected states, and confirm duplicate delivery does not duplicate the side effect.
Monitor progress rather than process existence
A running PHP process does not prove the queue is healthy. Alert on oldest pending age, ready count, processing count, lease expirations, success throughput, retry rate, permanent failure rate, and duration by job type. Compare these with database load and external-service errors. A flat queue size can hide a stuck high-priority class if other tasks continue completing.
Provide operators with safe controls to pause a class, retry selected failures, and inspect sanitized history. Avoid a public diagnostic endpoint that exposes payloads, paths, or environment details. After an incident, retain enough event history to reconstruct claims and retries, then convert the failure into a test that covers the exact transition rather than only the happy-path callback.
Practice failure injection with harmless jobs
Build a synthetic job type whose side effect is confined to a test record, then use it to exercise delayed execution, duplicate delivery, worker termination after the side effect, lease expiry, store timeout, and a permanently invalid payload. Verify the resulting state transitions and alerts rather than only the final row. Run these drills in staging and selected safe production windows because scheduler permissions, process signals, and database contention often differ from development. Never use a real customer message or publication as the failure probe.
Record recovery steps for each injected fault: whether the system retries automatically, an operator replays an item, or a deployment must roll back. Confirm that two operators cannot trigger conflicting recovery actions and that replay preserves the idempotency key. Time the oldest-item alert and compare it with the service deadline. These exercises prove that the queue is observable and recoverable before a high-value scheduled action becomes the first time the team sees an expired lease or uncertain external response.
Deployment checklist
- Inventory every hook and queue with its owner, duration, deadline, and side effects.
- Use the system scheduler for deterministic triggering before disabling request spawning.
- Claim bounded work atomically with owner tokens and expiring leases.
- Assign stable idempotency keys to externally visible operations.
- Back off transient retries and dead-letter permanent failures.
- Version payloads and drain or gracefully stop workers during deployments.
- Alert on queue age, lease expiry, throughput, retries, and permanent failures.
- Test duplicate delivery, worker crash, dependency outage, and safe replay.
