When you build a control plane that runs SSH and Docker commands against a VPS, your first concurrency bug shows up fast: two deploys overlap, write .env and docker-compose.yml at the same time, and leave the app broken.

The obvious fix is a single mutex per server (lock(serverId)).

That stops overlapping deploys—and immediately creates a new operational headache. The moment App A kicks off a 20-minute Git Docker build or a long scheduled maintenance task, the entire server is locked. You cannot edit App B's environment variables, add a domain to App C, or run App D's backup until App A finishes.

Meanwhile, a second problem hides until your first unexpected panel restart: what happens if the control plane process dies halfway through a backup or restore that had already run docker compose stop on Postgres?

This is the design behind job locking, idle draining, and crash recovery in Nitrobase.

Nitrobase has only recently launched and is still in Beta. Its job runner is not a multi-region distributed workflow engine like Temporal; it runs inside a single control-plane process with pure, unit-tested lock rules (locks.ts), idle hooks (idle-hooks.ts), and boot recovery (recovery.ts).

1. Two-tier locks sharing one registry

Instead of choosing between "lock the whole server" and "lock only the app," Nitrobase combines two lock scopes in a single serverLocks set (jobs/locks.ts):

  • Server lock (<serverId>): Held by server-level jobs (bootstrap, deploy, backup, multi-server transfers via alsoLock) and short withServerLock mutations.
  • App lock (app:<appId>): Held by long-running app-scoped jobs (Git builds and scheduled task runs).

The two scopes cross-block asymmetrically depending on whether an operation affects one app or the whole host:

Incoming operation Blocked by <serverId>? Blocked by app:<appId>? Why
App-scoped job (build / task for App A) Only if held by a server-wide job (appId: null), another job for App A, or a bare withServerLock mutation Only if app:A is already locked Two builds on App A cannot overlap, but App B's tasks and settings stay free
Server-level job for App B (deploy / backup) Yes (including any alsoLock server) Only if app:B is locked App A's 20-minute build does not block deploying App B
Server-wide job (appId: null) (bootstrap, orphan wipe) Yes Yes—blocked by any active app:* lock on that server Host-wide operations never fight running builds or tasks
withServerLock mutation (settings, domains, resources) Yes Only app:<appId> when appId is passed; all app locks when server-wide Editing App B's domains stays responsive while App A compiles

When a long Git build finishes compiling under its app:<appId> lock and is ready for the short cutover phase, it temporarily upgrades via ctx.withServerLock(step)—waiting cleanly until no server-level job holds <serverId> without having blocked the server for the previous 20 minutes.

2. Cancel-safe critical sections and persisted side effects

Clicking Cancel on a running deploy is useful—until a user clicks it halfway through a restore between docker compose down and loading the backup dump.

Nitrobase's JobContext separates normal interruptible steps from atomic ones:

  • ctx.critical(label, step): Marks a step that must not be torn in half. If a cancel request arrives during a critical section, cancelPending is recorded and cancellation waits until the critical step finishes.
  • Persisted side-effect ledger (servicesStopped, setWorkDir, setRollback): Before a job stops containers (for example, stopping a database before a cold backup) or creates a staging directory on the VPS, it persists those exact service names and folder paths to the deployment row before returning.

Even if the job finishes with an error—or the Node process is killed with SIGKILL five milliseconds later—the database already knows which services were left stopped and which staging folder was left behind.

3. Boot-time crash recovery (and adoption)

Because running jobs live in the control-plane process, any deployment still marked pending or running in Postgres after a process restart was interrupted by a crash or restart.

On startup, recoverOrphanedJobs() runs once (deployments.server.ts + jobs/recovery.ts):

Control plane boots │ ├── Instance paused (restored/cloned DB)? ──► skip recovery (never fight the live owner!) │ v 1. hook.adopt() └─ Let features claim surviving jobs (e.g. a panel self-upgrade finished by the new panel) v 2. Mark remaining pending/running rows failed (JOB_INTERRUPTED) v 3. hook.onInterrupted(ids) + hook.removeWorkDir(...) └─ Notify owning features & delete orphaned staging folders on remote VPSes v 4. Group stoppedServices per app ──► launch one locked `app_recover` job per affected app └─ Brings back ONLY the services the dead job had stopped 

Notice two quiet details that prevent recovery itself from causing damage:

  • Paused-instance guard: If the panel booted from a restored or cloned database (instancePauseReason()), boot recovery is skipped completely so a cloned panel never reaches out and restarts containers on servers owned by the real production instance.
  • Adoption before failing: A panel self-upgrade intentionally restarts the control plane mid-job; calling hook.adopt() before marking jobs as JOB_INTERRUPTED lets the newly booted panel take over and complete the upgrade record cleanly.

4. Sequential draining with backoff-guarded idle hooks

What happens when you change Traefik routes on an app while another job currently holds the server lock?

Rather than rejecting the edit or spinning up a separate background queue daemon, Nitrobase records routesPending and attaches an idle listener (jobs/idle-hooks.ts) that fires inside releaseServer(serverId) whenever the server lock drops:

  1. pendingRoutesListener picks the oldest app with routesPending whose cooldown has elapsed and starts one routes job.
  2. When that job finishes and releases the server lock, releaseServer notifies the listener again—draining pending apps strictly one after another with zero extra queue infrastructure.
  3. To guarantee a broken route update can never spin in an infinite loop, each app has an in-memory backoffMs cooldown (attempts). If starting the job fails only because another job grabbed the lock first, the cooldown entry is immediately cleared so it runs on the very next lock release; if the job actually ran and failed, it backs off and the UI keeps offering a manual "Apply routes" button.

What an in-process job runner still does not give you

An in-process lock set and idle hook system keeps deployment simple on a single control-plane node (no Redis or external broker required), but it assumes one active control-plane process per database. Horizontal active-active scaling across multiple control-plane replicas would require moving locks and idle notifications into Postgres advisory locks or a shared queue.

My checklist for PaaS / control-plane job runners

  • [ ] Split host-level locks from app-level locks so a 20-minute build never blocks unrelated apps on the same server
  • [ ] Let long app-scoped jobs upgrade briefly (withServerLock) only for the final cutover step
  • [ ] Wrap destructive/non-interruptible steps in cancel-safe critical sections
  • [ ] Persist stoppedServices and workDir before mutating the host so boot recovery can clean up after SIGKILL
  • [ ] Guard boot recovery behind an adoption step (for self-upgrades) and a cloned-instance check
  • [ ] Add a per-app backoff to lock-release idle listeners so failing follow-up jobs cannot tight-loop

Good concurrency control in a self-hosted PaaS is mostly about shrinking the blast radius: keep unrelated apps moving while long jobs run, and leave enough breadcrumbs on disk to recover cleanly when the process dies.

Nitrobase source code: https://github.com/AydenGroup/nitrobase