Scheduled job stuck after server crash or restart, and the obvious fix breaks with multiple servers

Hi all

We run Moqui in production with scheduled service jobs. We are moving from a single server to multiple servers sharing one database, so we need this to work safely in a multi-server setup.

The problem:
If a server crashes or restarts while a scheduled job is running, the job’s lock stays in the database and the run never gets an end time. After the server is back, the scheduler thinks the job is still running and skips it on every check. The job stays blocked until the lock expires (the default is 24 hours) or someone clears it manually in the database. For jobs that run every few minutes, that means a full day of missed runs, and the job history shows a run that never finished.

Why the simple fix does not work for us:
The obvious fix is to clear all job locks when a server starts. That is fine with one server, but with several servers it causes new problems:

  • A restarting server cannot tell which locks belong to a dead run and which belong to a job that is still running on another server.
  • It would clear the lock of the running job, and the same job would start a second time. That can mean duplicate processing for jobs like order sync, inventory sync or feed generation.
  • The lock does not say which server owns it. Server IP or hostname is not reliable, because servers get replaced and change address with auto-scaling.
  • Lowering the 24-hour expiry only trades one problem for another. A short expiry can unlock jobs that are legitimately running for a long time, and a long expiry keeps jobs blocked after a crash.

Question:
How do you handle stale job locks in production, especially with more than one server? Is there a recommended or safe way to recover from a crash without risking duplicate runs?

Any experience or advice would be a big help. Thanks!

Related: Last run time in ScheduledJobRunner covers the lastRunTime side after a lock expires. Our question is about getting the stuck lock released safely in the first place, with multiple servers.