Writing

One scheduler, many workers

Every scheduled job looks harmless until the application runs in more than one process.

A nightly cleanup is written once and tested once. Then the service is deployed with a Node cluster, or two containers, or a rolling release. The cleanup starts running twice. The digest email goes out twice. A season transition is applied to the same data from two directions. Nothing looks wrong in the code because the code is not wrong. The ownership model is.

This is the problem I keep coming back to in Deadlink Protocol: how do you make sure exactly one process owns the schedule, while the rest of the system is allowed to scale?

The bug is not the cron expression

A Node cluster has one primary process and several workers. Each worker has its own event loop, memory and timers. If a worker calls setInterval, that timer belongs to that worker. If every worker calls it, every worker gets a timer.

primary
  |-- worker 0  -> setInterval(cleanup, 60_000)
  |-- worker 1  -> setInterval(cleanup, 60_000)
  |-- worker 2  -> setInterval(cleanup, 60_000)
  `-- worker 3  -> setInterval(cleanup, 60_000)

HTTP load balancing does not save you here. Four workers are useful because four requests can be handled at the same time. They are not useful as four independent clocks.

The same mistake appears with queue libraries. Bull and BullMQ are good at distributing work to many consumers. That is not the same as distributing the registration of recurring work. If every worker registers the same repeatable job on startup, the queue can end up with duplicate schedules. The consumers then process those schedules faithfully, which is exactly what you asked them to do.

The shape that works: one scheduler, many workers

In Deadlink Protocol the backend uses Node's cluster module. Request traffic is spread across the workers, but only worker 0 runs as the scheduler worker. The other workers keep serving HTTP and processing jobs, but they do not register the recurring schedules.

The simplified shape looks like this:

                         +----------------------+
                         |      primary         |
                         |  forks and supervises|
                         +----------+-----------+
                                    |
          +-------------------------+-------------------------+
          |                         |                         |
  +-------v--------+       +--------v--------+       +--------v--------+
  | worker 0       |       | worker 1        |       | worker 2        |
  | SCHEDULER=true |       | HTTP only       |       | HTTP only       |
  | owns schedules |       | consumes jobs   |       | consumes jobs   |
  +-------+--------+       +--------+--------+       +--------+--------+
          |                         |                         |
          +-------------------------+-------------------------+
                                    |
                         +----------v-----------+
                         |  Redis / Valkey      |
                         |  Bull queue          |
                         |  scheduler lock      |
                         +----------------------+

The state of the schedules lives in a shared place, not in one worker's memory. The scheduler is a role, not a hard-coded process ID. That distinction matters when worker 0 dies and the primary forks a replacement.

A bad version, then a better one

This is the version that creates duplicate work in a cluster:

const cluster = require('node:cluster');

if (!cluster.isPrimary) {
  setInterval(async () => {
    await cleanupOldSessions();
  }, 60_000);
}

Every worker starts its own interval. This is fine on a laptop with one process. It is not fine in production.

A better version gives the schedule one owner:

const cluster = require('node:cluster');
const Queue = require('bull');

const isScheduler = process.env.SCHEDULER_WORKER === 'true';
const queue = new Queue('maintenance', process.env.REDIS_URL);

async function registerSchedules() {
  await queue.add(
    'session-cleanup',
    {},
    {
      jobId: 'session-cleanup',
      repeat: { cron: '0 3 * * *' },
      removeOnComplete: 100,
      removeOnFail: 500,
    },
  );
}

if (!cluster.isPrimary && isScheduler) {
  registerSchedules().catch((error) => {
    console.error('scheduler registration failed', error);
    process.exitCode = 1;
  });
}

queue.process('session-cleanup', async (job) => {
  await cleanupOldSessions();
});

Now every worker can process jobs, but only one process registers the schedule. The HTTP workers are still good at their job, and the scheduler worker has one clear job.

Registration is not leadership

One process owning the registration is a good first step. It is not enough during deploys.

Imagine a rolling release. The old scheduler worker is still running while the new one starts. For a few seconds there are two processes that both believe they own the schedule. A fixed worker number does not protect you from that. A restart can also briefly create two primaries if the deployment orchestration is careless.

For that reason, the scheduler role should be protected by a shared lease. The lease does not have to be complicated. It needs to answer one question: who is allowed to register and run the schedule right now?

async function tryBecomeScheduler(redis, workerId) {
  const result = await redis.set(
    'scheduler:lease',
    workerId,
    'PX',
    15_000,
    'NX',
  );

  return result === 'OK';
}

async function renewSchedulerLease(redis, workerId) {
  const current = await redis.get('scheduler:lease');
  if (current !== workerId) return false;

  await redis.pexpire('scheduler:lease', 15_000);
  return true;
}

The process that owns the lease registers the repeatable jobs. The other processes wait. If the owner dies, the lease expires and another process can take over. The exact Redis command and the renewal interval are less important than the invariant: there is one decision point.

Bull can also help because it stores repeatable jobs in Redis, but do not assume that a repeatable job automatically solves process ownership. The registration path still has to be controlled. Queue consumers can be many. Schedule owners should be one.

Make the job safe to run twice anyway

Even with a good lease, the world is messy. A process can be paused. A deploy can overlap. A queue can deliver a job after a retry. The safest scheduled jobs are idempotent.

An idempotent job does not depend on the optimistic assumption that it runs once. It checks the state it is about to change:

async function closeExpiredSeason(seasonId) {
  await db.transaction(async (transaction) => {
    const season = await Season.findByPk(seasonId, {
      transaction,
      lock: transaction.LOCK.UPDATE,
    });

    if (!season || season.status !== 'ACTIVE') {
      return;
    }

    await season.update({ status: 'CLOSED' }, { transaction });
    await ledger.addEntry({
      reason: 'SEASON_CLOSE',
      referenceId: season.id,
      transaction,
    });
  });
}

The row lock and the status check do two different things. The lock serializes two workers trying to change the same row. The status check makes the second worker a no-op instead of a duplicate action. That is the pattern I want in every scheduled mutation.

For jobs that send email, write a message with a unique key and let the mail worker claim it. For jobs that create reports, give the report a deterministic key such as the date and job name. For jobs that delete data, make the query safe to repeat.

Observe the schedule, not only the job

A queue dashboard is useful, but it does not tell you whether a job was supposed to run and did not. Add an expected-run heartbeat.

+----------------------+       +----------------------+
| job runs at 03:00    | ----> | JobLog: success      |
+----------------------+       +----------+-----------+
                                         |
                                         v
                              +----------------------+
                              | alert if no success  |
                              | within 90 minutes    |
                              +----------------------+

Three signals are enough to start:

  • last successful run per job key

  • current queue depth and failed job count

  • time since the scheduler lease was renewed

Without the last one, you can have a perfectly healthy queue with no schedule owner. The workers will happily process nothing.

What happens when the scheduler dies

There is no magic failover in a single-process scheduler. You need a plan:

  1. The lease expires.

  2. Another worker tries to acquire it.

  3. The new owner loads the active schedule definitions from the database.

  4. It reconciles the repeatable jobs in the queue.

  5. It records that ownership moved.

That sequence should be visible in logs. A scheduler takeover is an operational event, not a silent implementation detail. If it happens every few minutes, the lease is too short or the process is unhealthy.

The checklist I would use in another service

  • Only one process registers recurring jobs.

  • The scheduler role is held by a lease or an equivalent leader election.

  • All workers may consume jobs, but not all workers may create schedules.

  • Every scheduled mutation is idempotent.

  • Repeatable jobs have stable job IDs and a reconciliation path.

  • There is an alert for a missing successful run.

  • A scheduler takeover is logged and tested.

  • Deploys are assumed to overlap briefly, even when they usually do not.

Scaling HTTP workers and scheduling time are two different problems. Let as many workers as you need serve requests. Give the clock one owner, a lease, and a way to prove that the work actually happened.