All posts
databasebackend

You Probably Don't Need Redis for Your First Job Queue

One Postgres table, one query with FOR UPDATE SKIP LOCKED, and a worker loop. How I queued WhatsApp messages without adding another server, and when I'd stop.

Muhamad Choirul Adam 4 min readPhoto: Unsplash

The reseller system I'm working on sends a lot of WhatsApp messages: login codes, order updates, payment reminders. Sending them inside the HTTP request was a mistake I made exactly once. The provider was slow for a minute, every request that touched it hung, and the checkout page went down with it.

The fix is a queue. The usual answer is Redis with BullMQ. But we already had Postgres, and adding a second stateful server for a few thousand messages a day felt like the wrong trade.

The table

A job is a row. The worker needs to know what to do, when it may run, and how many times it already failed.

create table jobs (
  id          bigserial primary key,
  kind        text        not null,
  payload     jsonb       not null,
  run_at      timestamptz not null default now(),
  attempts    int         not null default 0,
  locked_at   timestamptz,
  done_at     timestamptz,
  last_error  text
);
 
-- the worker only ever looks for runnable, unfinished jobs
create index jobs_runnable on jobs (run_at) where done_at is null;

Enqueueing is an insert. The nice part: it can sit in the same transaction as the order it belongs to. If the order rolls back, the message was never queued. With Redis you'd have to think about that gap yourself.

begin;
insert into orders (...) values (...);
insert into jobs (kind, payload) values ('whatsapp.order_created', '{"orderId": 812}');
commit;

The one query that makes it work

Several workers asking "give me the next job" at the same time is the whole problem. FOR UPDATE SKIP LOCKED solves it: each worker locks the row it picks, and other workers skip locked rows instead of waiting for them.

update jobs
set locked_at = now(), attempts = attempts + 1
where id = (
  select id from jobs
  where done_at is null
    and attempts < 5
    and run_at <= now()
    and (locked_at is null or locked_at < now() - interval '5 minutes')
  order by run_at
  limit 1
  for update skip locked
)
returning id, kind, payload, attempts;

The locked_at < now() - interval '5 minutes' clause is the safety net. If a worker crashes halfway through a job, the lock goes stale and another worker picks the job up again.

The worker

worker.ts
async function work() {
  for (;;) {
    const job = await claimNext(); // the query above
    if (!job) {
      await sleep(1000);
      continue;
    }
    try {
      await handlers[job.kind](job.payload);
      await db.query("update jobs set done_at = now() where id = $1", [job.id]);
    } catch (err) {
      // retry later, waiting longer each time: 30s, 2m, 8m...
      const delay = 30 * 4 ** (job.attempts - 1);
      await db.query("update jobs set locked_at = null, last_error = $2, run_at = now() + make_interval(secs => $3) where id = $1", [
        job.id,
        String(err),
        delay,
      ]);
    }
  }
}

The attempts < 5 filter is the dead-letter rule: after five failures the row stays put, with its last error, for a human to look at. A job that failed five times is telling you something.

Rendering diagram…

The catch: handlers must be safe to repeat

A worker can send the WhatsApp message and then crash before it marks the job done. The job runs again and the customer gets the message twice. No queue fixes this for you, Redis included. Make the handler idempotent: record what was sent, keyed by job id, and check before sending.

When I'd stop doing this

This setup is boring in a good way, but it has a ceiling:

  • Thousands of jobs per second. Every claim is a write, and the table churns. Vacuum has to keep up.
  • You need fan-out or pub/sub. One message, many consumers, is what a real broker is for.
  • Jobs need sub-second latency. Polling once a second is fine for a reminder, not for a chat app. LISTEN/NOTIFY can wake workers early, but by then you're building a broker.

None of those were true for us. One table and one query bought us retries, crash recovery, and transactional enqueueing, with nothing new to run in production.