Distributed SystemsCompleted2025

JobFlow — Distributed Worker Platform

Turborepo monorepo with a polling-based distributed job processor, PostgreSQL-backed worker registry, heartbeat monitoring, and graceful shutdown with SIGTERM draining.

RoleBackend Systems Engineer
Timeline5 weeks
PublishedMarch 2025
Source Code
TypeScriptNode.jsExpressNext.jsPostgreSQLPrismaTurborepoDocker

A production-scaffolded distributed background job processing platform built as a Turborepo monorepo. The system separates concerns cleanly between a REST API (job submission), a Next.js dashboard (job monitoring), and an autonomous worker process (job execution) — all sharing types and database access through a shared package. The worker implements heartbeat-based liveness tracking and zero-loss graceful shutdown.

Fig 1. Job Processing Flow — Worker Lifecycle
JobFlow system architecture: Next.js web (port 3000) + Express API (port 3001) → PostgreSQL via Prisma (jobs + workers tables) → Worker process polls claimNextJob() → executes → updates job status; heartbeat updates worker.lastSeen every 15s

How a job moves from the API into the PostgreSQL queue, gets claimed by a worker, processed, and how heartbeats ensure stale worker detection.

What We Set Out to Solve

Background job systems seem simple until you face the hard questions: what happens when a worker process crashes mid-job? What if two workers race to claim the same job? How do you know which workers are alive versus stuck? This project was built to answer those questions with a clean, typed, production-quality scaffold — before adding specific business logic.

Architecture Highlights

  • Turborepo monorepo with three apps (api, web, worker) and a shared @jobflow/shared package exporting Prisma client, logger, config, and claimNextJob utility
  • PostgreSQL as the single source of truth for both job queue and worker registry — no separate message broker required
  • Each worker self-registers with a UUID on startup and maintains a 15-second heartbeat (worker.lastSeen) to signal liveness
  • claimNextJob() atomically selects and marks the next pending job, preventing two workers from processing the same job
  • Graceful SIGTERM/SIGINT shutdown: drains the current job to completion before marking the worker as stopped and exiting
  • Typed job payload schema shared between API and worker via @jobflow/shared, enforced at compile time across monorepo packages

End-to-End Data Pipeline

Key Engineering Decisions

01

PostgreSQL as the Job Queue (No External Message Broker)

Jobs are stored in a PostgreSQL `jobs` table with a `status` column (pending, processing, completed, failed). Workers call `claimNextJob(workerId)` from the shared package to atomically select and claim the next available job using a database-level atomic update.

Rationale: Introducing a Redis or RabbitMQ instance adds operational complexity and another failure mode. For the job volumes this system targets, PostgreSQL's `SELECT ... FOR UPDATE SKIP LOCKED` pattern provides the same atomic claim guarantee with one fewer infrastructure dependency.

02

Worker Heartbeat at 15-Second Interval

Each running worker updates `worker.lastSeen` in PostgreSQL every 15 seconds via `setInterval`. On startup, the worker upserts its record with `status: 'idle'`. On shutdown, it sets `status: 'stopped'`.

Rationale: Without a liveness signal, a dead worker appears identical to a healthy idle worker. The `lastSeen` field allows a monitoring process (or an admin query) to identify workers that haven't reported in over N seconds and treat their claimed jobs as candidates for reassignment.

03

Graceful Shutdown with Job Draining

SIGTERM and SIGINT handlers set an `isShuttingDown` flag. The worker loop exits on the next iteration. If a job is currently executing (`currentJobId !== null`), the shutdown waits in a 500ms polling loop until it completes before marking the worker stopped and calling `process.exit(0)`.

Rationale: Killing a worker mid-job without draining leaves the job in `processing` status permanently. The drain pattern guarantees that every job that started will either complete or fail cleanly, making job status a reliable record.

04

Turborepo Monorepo with @jobflow/shared Package

The shared package (`packages/`) exports the Prisma client instance, pino logger, environment config, and the `claimNextJob` function. All three apps import from `@jobflow/shared` rather than duplicating database access code.

Rationale: Type safety across service boundaries is the primary benefit. When the Prisma schema changes, TypeScript compilation of all three apps fails simultaneously, making schema drift between services impossible.

Core Code Pattern

apps/worker/src/index.tsTYPESCRIPT
const WORKER_ID = crypto.randomUUID();
let isShuttingDown = false;
let currentJobId: string | null = null;

async function startHeartbeat() {
  heartbeatInterval = setInterval(async () => {
    if (isShuttingDown) return;
    await prisma.worker.update({
      where: { id: WORKER_ID },
      data: { lastSeen: new Date() },
    });
  }, 15_000); // 15-second liveness pulse
}

async function shutdown(signal: string) {
  isShuttingDown = true;
  await stopHeartbeat();
  // Drain: wait for the current job to finish before exiting
  while (currentJobId) {
    await new Promise((resolve) => setTimeout(resolve, 500));
  }
  await prisma.worker.update({
    where: { id: WORKER_ID },
    data: { status: 'stopped' },
  });
  process.exit(0);
}

process.on('SIGTERM', () => void shutdown('SIGTERM'));
process.on('SIGINT',  () => void shutdown('SIGINT'));

Each worker instance generates a random UUID on startup and registers in the database. A 15-second heartbeat updates lastSeen, enabling dead-worker detection. SIGTERM triggers a graceful drain — the current job completes before the process exits.

Technical Challenges & Resolutions

Challenge 1

Preventing two workers from claiming the same job simultaneously

Resolution: The `claimNextJob` function in @jobflow/shared uses a database atomic update — selecting the oldest pending job and updating its status in a single statement. PostgreSQL's row-level locking ensures that concurrent workers cannot both successfully claim the same row.

Challenge 2

Ensuring a crashed worker does not permanently block its claimed job

Resolution: The `lastSeen` heartbeat field provides the data needed to detect dead workers. A monitoring query can identify jobs in `processing` status whose assigned worker's `lastSeen` is older than 2× the heartbeat interval, making those jobs eligible for reassignment. The infrastructure for detection is built in; the reassignment cron is the natural next extension.

Challenge 3

Preventing race conditions during graceful shutdown when a new job arrives

Resolution: The `isShuttingDown` boolean is checked at the top of every loop iteration. Once set, no new job claims are attempted. The heartbeat interval is also cleared on shutdown, so the worker stops sending liveness signals immediately — accurately reflecting its draining state.

Measurable Outcomes

Results based on local benchmarks and integration test runs during development.

  • Zero job double-processing across concurrent worker stress tests with multiple workers
  • 100% of in-flight jobs complete successfully under SIGTERM — verified by logging job completions and process exit in the same test run
  • Worker liveness detection gap of at most 30 seconds (2 × 15s heartbeat) — dead workers detectable within one minute

JobFlow — Distributed Worker Platform

This case study documents the architecture, engineering decisions, and key challenges for JobFlow — Distributed Worker Platform. The full implementation is available in the source repository.