Replacing five ad-hoc job runners with one Postgres queue

Client system Published Jun 30, 2026 Reviewed Nov 21, 2026

Consolidating five incompatible background-job patterns in a support AI platform, plus an n8n enrichment flow, into Postgres-backed job queues with atomic claiming, heartbeats, fencing and idempotent external writes.

At a glance

Problem
A support AI platform had accumulated five separate ways to claim background work, and reply drafting had no durable state at all, letting deploys drop drafts and slow actions execute twice.
Constraint
Jobs post public customer replies and cancel live subscriptions against APIs with no built-in deduplication, so retry safety had to be enforced on our side.
System built
One Postgres job table with atomic claims, dedupe indexes, heartbeats, per-attempt deadlines and centralized retries, paired with action idempotency ledgers and a leased Go queue replacing n8n enrichment.
Outcome
In-flight drafts survive deploys, every job exposes explicit status and failure details, and the short-lease bug behind duplicate public replies was eliminated at the root.

Overview

A consumer subscription business operates an AI support agent that drafts Zendesk replies and, once approved, posts responses and cancels subscriptions. Supporting that loop requires continuous background jobs: model drafting, executing approved actions, running evaluations, scanning for new tickets to draft, and enriching tickets with BigQuery purchase records.

Over time, each job type invented its own answer to exclusive work claiming. The answers diverged, and several carried subtle failure modes that surfaced only under traffic spikes or rolling deploys.

Five mechanisms, one table

Before consolidation, five different concurrency schemes coexisted in one codebase:

  • Evaluation runs used FOR UPDATE SKIP LOCKED with heartbeats and worked reliably.
  • Automatic drafting relied on an advisory lock plus a cooldown ledger.
  • A stale-draft sweeper combined an advisory lock with a high-water-mark row.
  • Manual drafting used a TTL lease whose own docs admitted it gated nothing.
  • Action execution used a two-phase reclaim whose lease expired faster than the work it protected.

Drafting had zero durable persistence: it ran as a fire-and-forget promise inside the HTTP server, tracked progress in memory, and left the browser guessing outcomes behind a 150-second timeout. Any deploy killed in-flight drafts and stranded users on spinners.

All five patterns collapsed into one job table carrying kind, key, state, attempt budget, per-attempt deadline, heartbeat and progress:

  • Claiming happens in one UPDATE over FOR UPDATE SKIP LOCKED, recording state, attempt increment and initial heartbeat atomically.
  • Deduplication uses a partial unique index on (kind, key) across pending and running rows, turning duplicate enqueues into silent no-ops so double clicks never spawn twin jobs.
  • Wakeup combines NOTIFY on enqueue with a 5-second polling fallback against dropped notifications.
  • Liveness tracks heartbeat_at, refreshed every 15 seconds on an independent timer. A reaper resets rows silent for 60 seconds back to pending, or marks them failed once attempts run out.
  • Deadlines start at claim time rather than enqueue time so queue wait never steals execution budget (drafting receives 300 seconds and 2 attempts).
  • Fencing checks id, claimant and running state on every post-claim write, returning a clean boolean when a worker has lost ownership.

Retry scheduling lives in one single SQL settlement query:

UPDATE job
SET state  = CASE WHEN $outcome = 'failed' AND attempts < max_attempts
                  THEN 'pending' ELSE $outcome END,
    run_at = CASE WHEN $outcome = 'failed' AND attempts < max_attempts
                  THEN now() + make_interval(secs =>
                       least(300, 5 * 2 ^ attempts) * (0.5 + random() * 0.5))
                  ELSE run_at END,
    claimed_by = NULL, heartbeat_at = NULL, error = $error
WHERE id = $id AND claimed_by = $worker AND state = 'running'
RETURNING state;

Exponential backoff from the row's own attempt count, capped at 5 minutes, with half-to-full jitter

Job handlers are forbidden from wrapping model calls in private retry loops. Progress persists directly on the row, and finished jobs prune after 30 days.

Leases have to outlive the work

The bug that forced consolidation lived inside action execution. An approved action took a fixed 30-second lease while running a Zendesk write (30-second timeout) followed by sequential subscription cancellations (30-second timeout each). Whenever external calls ran past 30 seconds, a concurrent caller or retry reclaimed the action and executed the entire sequence again, posting duplicate public comments and repeating cancellations.

Adding an active heartbeat that renews the lease while the worker remains alive aligned execution with the job table: leases now expire only when a worker actually dies.

Idempotency where the API offers none

Zendesk comment creation has no idempotency key; sending the same request twice posts two public comments. Protection therefore had to live before the network call.

Every proposed action receives a deterministic key ({proposalId}:{actionIndex}) backed by a unique index on account and key. Actions transition through pending and applying into terminal states, with only applied short-circuiting reruns. If the Zendesk comment lands but a downstream cancellation fails, the action enters a dedicated partial-failure state so retries run only the remaining cancellations.

Cancellations maintain their own per-subscription ledger. Before calling the billing API, the executor filters out subscriptions already marked complete. Immediately after the call returns or throws, it persists every outcome before re-raising so crashes after partial success still leave an accurate record.

Reserving an action acquires the same per-ticket Postgres advisory lock used by the ticket-mirroring worker, serializing writes cleanly against mirror refreshes.

The enrichment queue and its cutover

Ticket enrichment from BigQuery originally ran in n8n. I replaced it with a Go service built around a leased Postgres queue with five states: queued, leased, done, failed and dead_letter.

Rows become eligible 10 minutes after new ticket creation (absorbing BigQuery replication lag) or 2 minutes after follow-up activity. A partial unique index enforces at most one open queued row per ticket so bursts collapse. Workers claim rows with a lease_owner and 60-second lease_expires_at, a sweeper recovers expired leases every 30 seconds, and rows dead-letter after 5 attempts.

The first sweeper reset all expired rows to queued in one statement. Whenever two expired rows existed for the same ticket, the second collided with the unique index and broke the sweep every 30 seconds. Updating the sweeper to promote the newest expired row per ticket and dead-letter duplicates inside one transaction fixed it permanently.

Cutover began in shadow mode. The Go worker wrote exclusively to new tables, a build test blocked any import touching legacy tables, and a parity job verified order coverage against n8n output. Early production traffic caught three real bugs: an int4 overflow past 2.1 GB of billed BigQuery bytes, a BigQuery job ID written into a UUID column triggering duplicate retries, and an unwired lookup log. Once fixed and verified, the first-generation Go worker, its budget ledger and old projection tables were retired.

Limitations

  • If Zendesk commits a write but drops the network response, an operator explicitly re-approving the action can still double-post. This trade-off beat silently treating uncertain failures as completed.
  • Two separate queue implementations remain: the Go enrichment queue and TypeScript job table share design patterns rather than code.
  • The enrichment queue exposes a heartbeat API, yet its live worker still uses a fixed lease TTL, leaving slow runs reclaimable in a path where reruns are cheap.
  • A separate set of n8n workflows was also rewritten in Go with its own queue and cron scheduler, ran only in dry-run, never migrated its event trigger off n8n and was eventually scrapped; its queue deleted jobs upon dispatch rather than completion, faithfully porting the old flow's bug. Cutover plans and corrected failure semantics must come before rewriting.

Related case studies

Bring one real problem

One hour, €80. You leave with a written plan for what belongs in AI, what belongs in code, and what a first release takes, whether we work together or not.