Engineering

Postgres SKIP LOCKED vs BullMQ vs Temporal: Choosing a Job Queue for Flaky Nigerian APIs

C
Chidi OkekeVP of Frontend Engineering
November 7, 202612 min read
Postgres SKIP LOCKED vs BullMQ vs Temporal: Choosing a Job Queue for Flaky Nigerian APIs

When upstream bank APIs fail or network partitions last for hours, basic queueing strategies break down. We evaluate Postgres SKIP LOCKED, BullMQ, and Temporal across infrastructure costs, state resilience, and developer overhead for Nigerian engineering teams.

When an upstream switch or bank API goes silent in Nigeria, your backend API doesn't just wait a few seconds. It gets stuck holding open HTTP connections while handling incoming payment webhooks, identity verifications, or disbursement calls. If your system relies on naive in-memory processing or poorly configured queues, server memory balloons, processes crash, and transactions vanish into the void.

At Neobot Tech, we have built settlement engines, logistics dispatch queues, and verification pipelines operating against third-party providers prone to multi-hour outages. Building for this environment requires background job queues that don't lose job state when a worker restarts, don't drop payloads when RAM limits are reached, and don't cost thousands of dollars in cloud infrastructure overhead.

Here is a realistic evaluation of three architectural patterns for async job processing—Postgres FOR UPDATE SKIP LOCKED, Redis-backed BullMQ, and Temporal durable execution—tailored to the operational realities of software teams building in Nigeria.

Architecture diagram comparing state persistence between Postgres SKIP LOCKED, Redis BullMQ, and Temporal engine

The Nigerian Engineering Context: Heavy Retries and Long Outages

Most job queue benchmarks assume your background tasks finish in 50 milliseconds and that third-party APIs maintain 99.99% availability. That assumption crumbles when you integrate with local payment gateways, switch networks, or government identity databases.

When building a pipeline to handle NIMC 504 gateway timeouts, your background jobs might need to sleep, retry with exponential backoff over 12 hours, or poll a status endpoint 40 times before obtaining a definitive response.

This introduces three core engineering constraints:

  1. Payload Durability Over Raw Throughput: If a Redis node runs out of memory while holding 500,000 pending payout retries, default eviction policies (volatile-lru or allkeys-lru) will silently drop job data. Unhandled payment state means manual database reconciliation.
  2. Infra Costs Under FX Pressure: Hosting managed queue infrastructure like AWS SQS or AWS Step Functions costs valuable foreign exchange. Running lightweight services on cheap bare metal or self-hosted virtual servers often yields massive savings. This is why many teams choose to move from AWS EKS to $140/mo Hetzner bare metal.
  3. State Visibility: When a user's transfer is stuck in PENDING_PROVIDER for six hours, support engineers must inspect the exact execution history of that single workflow without running complex SQL joins across five audit tables.

Option 1: PostgreSQL FOR UPDATE SKIP LOCKED (The Zero-Infra Queue)

Before adding Redis or specialized orchestration clusters to your infrastructure stack, consider using the relational database you are already running. Introduced in PostgreSQL 9.5, the SKIP LOCKED clause allows worker processes to select and lock rows that aren't locked by other workers, skipping over locked rows instantly.

How It Works

You create a jobs table directly in your PostgreSQL database. Workers run a transaction that fetches available jobs, locks them, updates their status to processing, and commits upon completion.

-- Worker polling query
BEGIN;

SELECT id, payload, retry_count
FROM background_jobs
WHERE status = 'pending'
  AND run_at <= NOW()
ORDER BY priority DESC, created_at ASC
LIMIT 10
FOR UPDATE SKIP LOCKED;

-- Update selected job status to prevent re-execution
UPDATE background_jobs
SET status = 'processing',
    updated_at = NOW()
WHERE id = ANY($1);

COMMIT;

The Engineering Trade-offs

  • Pros: Zero additional infrastructure costs. Full ACID guarantees mean your job state transitions occur inside the same database transaction as your business domain updates. If your application server dies mid-execution, PostgreSQL releases the row lock, allowing another worker to immediately claim the job.
  • Cons: High-frequency polling places unnecessary I/O read load on your primary database. If your worker pool queries PostgreSQL every 100 milliseconds across 20 pods, CPU usage spikes purely from lock overhead and Write-Ahead Log (WAL) bloat. Scaling past 5,000 jobs per second requires careful indexing, partition maintenance, and vacuum tuning.

For deep technical details on database locking primitives, refer to the PostgreSQL Documentation on Locking Clauses.


Option 2: Redis + BullMQ / Asynq (The High-Throughput Workhorse)

Redis-backed queue libraries like BullMQ (TypeScript/Node.js) or Asynq (Go) move job state out of your primary database and into RAM. They rely on Redis Lua scripts to atomically manage delayed jobs, worker heartbeats, and failure dead-letter queues.

import { Queue, Worker } from 'bullmq';

const connection = { host: '127.0.0.1', port: 6379 };

export const payoutQueue = new Queue('payout-retries', { connection });

// Enqueue job with exponential backoff
await payoutQueue.add(
  'process-disbursement',
  { reference: 'TX-904821', amount: 4500000, bankCode: '058' },
  {
    attempts: 10,
    backoff: {
      type: 'exponential',
      delay: 5000 // initial delay 5s
    }
  }
);

The Engineering Trade-offs

  • Pros: Extremely low latency and high throughput. Pushing and popping jobs happens in sub-millisecond speeds. Built-in primitives for delayed retries, rate limiting, and parent-child job dependencies make it trivial to throttle calls to restrictive third-party APIs (e.g., limiting NIMC lookups to 20 requests/second).
  • Cons: Memory management is brittle. Redis stores queue state entirely in RAM. If your background queues accumulate millions of retries during a bank network outage, Redis memory usage explodes. If configured with maxmemory-policy noeviction, job insertions crash. If configured with an eviction policy, Redis drops data. You must configure AOF (Append Only File) persistence carefully to avoid losing queues during Redis restarts.

Option 3: Temporal (Durable Execution Engine)

Temporal takes a fundamentally different approach. Instead of managing short-lived stateless job messages, Temporal turns your code into a stateful, event-sourced workflow. It guarantees that code runs to completion, surviving process crashes, server migrations, and multi-day network failures.

Learn more about the architectural concepts behind this pattern at the Temporal Documentation on Durable Execution.

import { proxyActivities, sleep } from '@temporalio/workflow';
import type * as activities from './activities';

const { verifyBankAccount, initiateNIBSSDisbursement } = proxyActivities<typeof activities>({
  startToCloseTimeout: '30 seconds',
  retry: {
    initialInterval: '10 seconds',
    maximumAttempts: 100,
    backoffCoefficient: 2
  }
});

export async function payoutWorkflow(disbursementId: string): Promise<void> {
  const isVerified = await verifyBankAccount(disbursementId);
  if (!isVerified) throw new Error('Account verification failed');

  // Wait 15 minutes before triggering actual settlement
  await sleep('15 minutes');

  await initiateNIBSSDisbursement(disbursementId);
}

The Engineering Trade-offs

  • Pros: Complete execution history. If a payment workflow stalls step 3 out of 7, you can inspect the exact variables, exception stack trace, and retry attempt number inside the Temporal Web UI. You can write long-running loops that sleep for 30 days without consuming active memory or DB connections.
  • Cons: Operationally complex. Running Temporal self-hosted requires running a Temporal Server cluster, PostgreSQL/Cassandra for history storage, and ElasticSearch for visibility indexing. The learning curve for developers is steep, as state determinism rules restrict the use of non-deterministic functions (like Math.random() or direct fetch() calls) inside workflows.

Head-to-Head Comparison Matrix

| Criteria | Postgres SKIP LOCKED | Redis + BullMQ / Asynq | Temporal ||---|---|---|---| | Infrastructure Overhead | None (Uses existing DB) | Low (Requires Redis server) | High (Requires Temporal cluster + storage) | | Max Throughput (Ops/sec) | 1,000 – 5,000 | 20,000 – 100,000+ | 2,000 – 10,000 | | Data Loss Risk on Crash | Zero (ACID compliant) | Medium (Depends on Redis AOF/RDB) | Zero (Event-sourced log) | | Long-Running Workflows (>24h)| Hard (Requires manual polling schema) | Medium (Consumes memory while waiting) | Native (sleep('30 days') consumes zero RAM) | | Operational Cost (Naira/USD) | Minimal ($0 additional) | Low ($10–$50/mo for Redis) | High ($100–$500/mo self-hosted or managed) | | Developer Learning Curve | Low (Standard SQL queries) | Low (Simple queue primitives) | High (Requires understanding determinism) | | Observability & Debugging | Poor (Custom admin views required) | Good (BullMQ Board / Arena UI) | Excellent (Native execution tree inspection) |


Clear Architectural Recommendations

Use Postgres SKIP LOCKED If:

  • You run a early-to-mid stage application processing under 500 jobs per minute.
  • You want to avoid operational complexity and run your backend entirely on a single database and app server cluster.
  • Your background tasks represent financial state changes where job creation must commit atomically with domain records (e.g., deducting user balance and enqueueing withdrawal in a single SQL transaction).

Use Redis + BullMQ / Asynq If:

  • You process high-volume, ephemeral background tasks such as sending push notifications, processing image uploads, or dispatching batch webhooks.
  • You need granular rate-limiting capabilities out of the box to comply with upstream third-party throttle limits.
  • Your team writes primarily Node.js or Go microservices and wants simple, rapid integration without managing cluster control planes.

Use Temporal If:

  • You are building critical financial workflows (e.g., loan disbursement cycles, multi-bank reconciliation engines, cross-border remittance pipelines).
  • Your execution paths involve complex multi-step sagas that take hours or days to complete due to manual approval steps or intermittent bank switch outages.
  • You have a dedicated platform/DevOps engineering capacity to run and maintain Temporal's underlying infrastructure.

Frequently Asked Questions

Does Postgres SKIP LOCKED cause database table bloat?

Yes, if left unmanaged. Frequent UPDATE queries on your jobs table produce dead tuples in PostgreSQL. To mitigate this, run an aggressive autovacuum policy on the jobs table, or periodically partition the table by date and drop completed partitions rather than running DELETE statements.

What happens to active BullMQ jobs if my Redis instance crashes?

If Redis restarts without AOF persistence enabled, active in-flight jobs in RAM are lost. If AOF is enabled with appendfsync everysec, you risk losing up to one second of enqueued job operations. For zero-data-loss requirements on Redis queues, ensure Redis Sentinel or Cluster configurations with proper persistence flags are enforced.

Can I mix Postgres SKIP LOCKED and Temporal in the same codebase?

Yes. A common pattern in high-growth payment engineering is using Postgres SKIP LOCKED or BullMQ for fast, transient tasks (sending emails, clearing cache keys), while delegating high-value, long-running transaction sagas (settlement orchestration) to a dedicated Temporal cluster.

Neobot Engineering Standard

Every system deployed by Neobot Tech incorporates enterprise baseline practices. We continuously audit our database topologies, REST API query paths, and frontend modular bundles to prevent latency spikes and ensure top-tier security posture.

Tags:#Software Architecture#PostgreSQL#Redis#Temporal#System Design#Node.js#Go

Discussion

Comments Coming Soon

We are currently migrating our discussion engine to a new real-time database schema. Check back shortly to join the conversation.