edozi.ai@edozi.ai
INTERMEDIATE BUILD · 30 min

Run an always-on worker

Deploy a persistent queue worker with leases, clean shutdown, backoff, and health reporting.

Use a worker when latency matters

The process stays alive, but each agent run remains a separate leased job. Deploy it as a worker service with restart-on-failure; do not expose the worker directly to the public internet.

1. Poll safely

worker.mjs
const shutdown = new AbortController();
for (const signal of ["SIGTERM", "SIGINT"]) {
  process.on(signal, () => shutdown.abort());
}

let delayMs = 1_000;
while (!shutdown.signal.aborted) {
  const job = await reserveJob({ leaseSeconds: 300 });
  if (!job) {
    await wait(delayMs, shutdown.signal);
    delayMs = Math.min(delayMs * 2, 30_000);
    continue;
  }

  delayMs = 1_000;
  await processBoundedJob(job, {
    signal: shutdown.signal,
    maxTurns: 20,
    maxCostUsd: 2,
  });
}

The queue reservation must be atomic. Renew the lease during long work, and stop renewing when shutdown begins so another worker can recover the job.

2. Report liveness and usefulness

A process can be alive while doing no useful work. Track both a heartbeat and queue lag.

health response
{
  "status": "ok",
  "workerId": "worker-7f3a",
  "lastHeartbeatAt": "2026-09-27T00:00:00Z",
  "activeJobId": null,
  "queueLagSeconds": 12
}

3. Configure deployment

  • One start command for the worker; no public port unless your host requires a private health endpoint.
  • Restart on non-zero exit with a bounded backoff.
  • Secrets supplied by the host, never committed or printed.
  • Database connection pooling sized for the worker count.
  • Graceful shutdown longer than the normal checkpoint interval.
  • A maximum concurrency that respects model, tool, and downstream rate limits.

Failure drill

  1. Kill the worker mid-job and verify another worker resumes only after the lease expires.
  2. Return a rate limit and verify backoff honours the provider’s retry window.
  3. Send malformed input and verify it is quarantined rather than retried forever.
  4. Activate the kill switch and verify no new jobs are claimed.

Continue building

All tutorials ↗