Zeeshan Adil
Book a call
← All writing
Cover of When RabbitMQ Isn't Enough: Building Durable, Retryable Jobs

When RabbitMQ Isn't Enough: Building Durable, Retryable Jobs

by Zeeshan Adil·in DatabasesUpdated 22 min read
Listen to this articleWhen RabbitMQ Isn't Enough: Building Durable, Retryable Jobs 19 min · read by an AI voice
0:00 / 18:42

Database-backed jobs with atomic claiming, backoff, circuit breakers and an outbox, and what each piece does and does not guarantee.

THE SHORT VERSION

  • For this workload, we needed queryable and editable jobs, long delays and per-resource health; keeping jobs as database rows made those needs easier to handle.
  • Atomic claiming gives one worker a given claim. A crash or expired lease can still lead to another execution, so side effects need their own duplicate-handling strategy.
  • A transactional outbox records the event with the business write; reliable relay and broker configuration are also needed. Publishing can repeat, so give each event a stable id and deduplicate at the consumer.
  • Exactly-once effects are possible within a stated idempotency boundary. A crash or timeout can still cause the code to run more than once.

We had a queue. A good one. RabbitMQ, properly configured, durable queues, the works. Push a "send email" message, a worker picks it up, calls Microsoft Graph API, done. Textbook stuff.

Except sometimes Microsoft would return a 429. Sometimes our OAuth token expired mid-flight. Sometimes the worker crashed right after sending but before acknowledging the message. And sometimes our RabbitMQ node itself would go down for maintenance.

The queue wasn't the problem. The queue was doing exactly what queues do. The problem was that we were treating an unreliable operation like a reliable one.


Reading path: This assumes you have used a message queue and a database transaction. Follow one job from its stored row through claiming, retries, and completion. If you are troubleshooting an integration, start with backoff or OAuth failures. Read the guarantee boundaries before adapting the examples.

Can't queues handle this?

Before I go further, let me address the obvious question: can't you just configure your queue to handle retries, backoff, and rate limiting?

Yes. You can.

RabbitMQ has dead letter exchanges with TTL for delayed retries. BullMQ has built-in exponential backoff. SQS has visibility timeouts and redrive policies. You can implement rate limiting on the consumer side, check circuit breaker state before processing, use separate queues per resource.

So why didn't we?

A few reasons specific to our situation:

We needed to query jobs. "Show me all failed email jobs for this user in the last hour." "How many jobs are stuck on this OAuth connection?" With a database, that's a SQL query. With a queue, messages are opaque until consumed. You'd need to build a separate tracking system.

We needed to modify jobs after enqueueing. Cancel a scheduled email because the user deleted it. Update priority because something became urgent. Change the payload because upstream data changed. With queues, once a message is in, it's in. With a database, it's just an update.

We had very long delays. Some retry scenarios meant waiting days before trying again. Queues with multi-day delays get awkward. A runAt timestamp in a database is trivial.

We wanted one place to look. No separate monitoring for queue depth, no message broker to manage, no RabbitMQ dashboard plus application logs plus database queries to piece together what happened. Everything in one table.

The tradeoff is real. Polling adds database queries and can add latency while a job waits for the next poll. At high throughput, the load and query design deserve careful measurement. But for external API integrations, the API itself is usually the bottleneck, not your job processing speed. We weren't trying to process 10,000 jobs per second. We were trying to process a few hundred per minute reliably, with full visibility into what was happening.

If you're doing high-throughput internal microservice communication, use a queue. That's what they're built for. If you're integrating with external APIs where you need observability, modifiability, and long delays, a database-backed approach might be simpler.

Now, here's how we built it.


The database is your friend

Instead of treating jobs as ephemeral messages that exist only in transit, we persist them. Every job becomes a row in a table with a status, an attempt count, a scheduled execution time, and a resourceKey that identifies which external resource it's talking to.

Code
model ResilientJob {
  id           String    @id @default(uuid())
  type         String    // 'send-email', 'sync-data', whatever
  resourceKey  String    // The specific API account/connection this job uses
  payload      Json
  
  status       JobStatus @default(PENDING)
  attempts     Int       @default(0)
  maxAttempts  Int       @default(3)
  runAt        DateTime  @default(now())
  lockedAt     DateTime? // When a worker claimed this job
  errorMessage String?
  createdAt    DateTime  @default(now())

  @@index([status, runAt])
}

That resourceKey field is doing more work than it looks. It's the key to everything that follows.

When you're sending email through a connected Outlook account, each connection has its own credentials and can fail independently. A broken connection for User A shouldn't automatically block User B. Rate limits may also apply at broader scopes, such as an application or tenant, so choose resource keys and limiters to match the provider's documented limits.

We track the health of each resource separately:

Code
model ResourceRateLimit {
  resourceKey         String    @id
  nextAvailableAt     DateTime  @default(now())
  consecutiveFailures Int       @default(0)
  lastErrorAt         DateTime?
}

This gives us per-resource rate limiting and per-resource circuit breaking. The granularity matters.


The processing loop

A scheduled worker wakes up every few seconds and looks for work. The example below shows the shape of its decisions; helpers such as deferJob, handleFailure, and markComplete are omitted, so it is a starting point rather than a complete worker.

Code
const LOCK_TIMEOUT_MS = 5 * 60 * 1000; // 5 minutes
const MAX_ATTEMPTS = 3;

while (true) {
  const now = new Date();
  const staleThreshold = new Date(now.getTime() - LOCK_TIMEOUT_MS);

  // Find the next job that's ready to run
  const job = await db.resilientJob.findFirst({
    where: {
      OR: [
        // Ready to run
        {
          runAt: { lte: now },
          status: { in: ['PENDING', 'FAILED'] },
          attempts: { lt: MAX_ATTEMPTS }
        },
        // Stale lock - worker probably crashed
        {
          status: 'RUNNING',
          lockedAt: { lt: staleThreshold }
        }
      ]
    },
    orderBy: { runAt: 'asc' }
  });

  if (!job) break;

  // Optimistic lock - try to claim this job.
  // Matching lockedAt too means two workers cannot both reclaim the same stale job.
  const claimed = await db.resilientJob.updateMany({
    where: { id: job.id, status: job.status, lockedAt: job.lockedAt },
    data: { status: 'RUNNING', lockedAt: now }
  });

  if (claimed.count === 0) continue; // Someone else got it

  // Check if this resource is healthy before we even try
  const healthy = await checkResourceHealth(job.resourceKey);
  if (!healthy) {
    await deferJob(job.id, getCircuitBreakerDelay());
    continue;
  }

  try {
    await executeJob(job);
    await markComplete(job);
    await resetResourceHealth(job.resourceKey);
  } catch (error) {
    await handleFailure(job, error);
  }
}

The lockedAt timestamp handles a failure mode that's easy to miss: what if a worker crashes mid-execution? Without it, the job stays in RUNNING forever. With it, we can reclaim jobs where the lock has gone stale. If a job has been RUNNING for more than 5 minutes, something probably went wrong and another worker can pick it up.

Be clear about what this buys you. Each conditional claim is atomic: only one worker wins that particular race. But the job can still run twice. A worker can finish the API call and crash before markComplete, or it can simply be slower than the lock timeout. Either way the job is picked up again and executeJob runs a second time. The atomic claim prevents two workers from winning the same claim at once, but lease expiry can let a new worker start while the old one is still running. It does not make execution happen once, so anything executeJob does needs a strategy for repeated execution.

Completion, failure, and defer updates also need to check the current claim token or generation: an old worker must not overwrite the state of a newer claim. The illustrative helpers above don't show that check.


Worker 1 claims a job and starts an API call. If its claim expires while it is still running, worker 2 can claim the same job, so both workers may call the API. The external effect must be safe to repeat.

Getting backoff right

The naive approach to retry is exponential backoff. Wait 1 second, then 2, then 4, then 8. It's fine. It's also insufficient for real-world API integrations.

Different failures need different responses. A 500 error probably means "try again soon, the server is having a moment." A 429 means "you're going too fast" and may include a suggested wait. A 401 means "your credentials are wrong", but in OAuth land, that might just mean your token expired and you need to refresh it.

Code
function computeBackoff(error: any, attempt: number): number {
  const status = error?.response?.status;
  const headers = error?.response?.headers;

  // If they told us exactly when to retry, listen to them
  if (status === 429 || status === 503) {
    const retryAfter = parseRetryAfterHeader(headers);
    if (retryAfter !== null) {
      return retryAfter * 1000 * 1.2; // Add 20% buffer
    }
  }

  // Standard exponential backoff with jitter
  const base = Math.min(2 ** (attempt - 1), 60);
  const jitter = 0.8 + Math.random() * 0.4;
  return base * 1000 * jitter;
}

That jitter isn't optional. Without it, if you have 50 jobs that all failed at the same moment, they'll all retry at the same moment, fail again, and retry together again.

The Retry-After header parsing is also worth getting right. The example adds a fixed buffer to that delay; spreading retries further with jitter can prevent many workers from returning at once. Microsoft's Graph API uses it. So does Google. When they tell you to wait 47 seconds, they mean it. Ignoring it and hammering them again in 4 seconds just gets you blocked faster.

Code
// The HTTP-client adapter supplies a plain map with lowercase header names.
function parseRetryAfterHeader(
  headers: Record<string, string | undefined> = {}
): number | null {
  // Standard header (seconds or HTTP date)
  const retryAfter = headers['retry-after']?.trim();
  if (retryAfter) {
    if (/^\d+$/.test(retryAfter)) {
      const seconds = Number(retryAfter);
      if (Number.isFinite(seconds)) return seconds;
    } else if (/[a-z]/i.test(retryAfter)) {
      const date = Date.parse(retryAfter);
      if (Number.isFinite(date)) return Math.max(0, (date - Date.now()) / 1000);
    }
  }

  // Microsoft-specific (milliseconds)
  const msHeader = headers['x-ms-retry-after-ms']?.trim();
  if (msHeader && /^\d+$/.test(msHeader)) {
    const ms = Number(msHeader);
    if (Number.isFinite(ms)) return ms / 1000;
  }

  return null;
}

Trace a few inputs through both functions before using them:

ResponseParsed delayWhat computeBackoff does
429 with Retry-After: 4747 secondsReturns 56,400 milliseconds after the example's 20% buffer.
503 with Retry-After: 00 secondsHonors zero; it does not mistake it for a missing header.
429 with no usable retry headernullUses the exponential backoff and jitter below the header check.

Keep the units visible: the parser returns seconds, while the worker delay is in milliseconds. Also keep the retryAfter !== null test. A truthiness check would discard a valid zero delay.


Circuit breakers

The circuit breaker pattern gets talked about a lot but implemented poorly almost as often.

The idea is simple: if a resource keeps failing, stop trying for a while. Don't burn through your retry budget, don't spam a broken endpoint, don't waste everyone's time.

Code
async function checkResourceHealth(resourceKey: string): Promise<boolean> {
  const limit = await db.resourceRateLimit.findUnique({
    where: { resourceKey }
  });

  if (!limit) return true;

  const now = new Date();

  // Circuit breaker: too many consecutive failures
  if (limit.consecutiveFailures >= FAILURE_THRESHOLD) {
    if (limit.nextAvailableAt > now) {
      return false; // Circuit is open, don't even try
    }

    // Half-open: claim a probe using compare-and-set on nextAvailableAt.
    // The lease can expire while an earlier probe is still running.
    const claimed = await db.resourceRateLimit.updateMany({
      where: {
        resourceKey,
        nextAvailableAt: limit.nextAvailableAt, // unchanged since we read it
        consecutiveFailures: { gte: FAILURE_THRESHOLD }
      },
      data: { nextAvailableAt: new Date(now.getTime() + PROBE_LEASE_MS) }
    });
    return claimed.count === 1; // one winner, everyone else stays deferred
  }

  // Rate limiting: respect the cooldown
  return limit.nextAvailableAt <= now;
}

With many workers, a check-then-act version ("the cooldown has passed, so go") can let them all send probes at once. The conditional UPDATE gives one worker the claim for a particular version of the row. The new nextAvailableAt acts as a lease (say PROBE_LEASE_MS of 30 seconds), allowing another worker to try if the prober crashes.

A lease is not a guarantee that only one probe is running. If a slow probe outlives it, another worker can claim the next attempt. Production code needs a bounded probe timeout and a way to reject stale results, such as a generation or claim token checked when updating breaker state. A Redis SET key owner NX PX 30000 can coordinate a claim too, but has the same lease-expiry limitation.

When a job fails, we increment the consecutive failure count. When it succeeds, we reset it to zero. Once failures hit a threshold (we used 3), the circuit opens and all jobs for that resource get automatically deferred by a longer period (we used 5 minutes).

This protects you and the API provider. If someone's OAuth connection is broken, you're not going to fix it by retrying every 10 seconds. You're just going to rack up rate limit violations and make your logs unreadable.


Handling 401s in OAuth land

There's one failure mode that deserves special handling: the 401.

A 401 means the request lacks valid authentication credentials. An expired access token is one possible cause, and a valid refresh token may let the client obtain a new one. A revoked credential or other authentication failure may require a different response.

Code
async function executeEmailJob(payload: EmailPayload): Promise<void> {
  const account = await db.getAccount(payload.accountId);

  try {
    await emailProvider.send(account.accessToken, payload.email);
  } catch (error) {
    if (error.response?.status === 401) {
      // Token expired - try to refresh
      const newTokens = await emailProvider.refreshToken(account.refreshToken);
      
      // Persist new tokens for future jobs
      await db.updateAccountTokens(account.id, newTokens);
      
      // Retry immediately with fresh token
      await emailProvider.send(newTokens.accessToken, payload.email);
      return;
    }
    
    throw error;
  }
}

When refresh succeeds, the job can continue without waiting for the next scheduled attempt. In production, also handle failed or revoked refresh tokens and coordinate concurrent refreshes, especially if refresh tokens rotate. Retrying the send is safe only when the provider's response and idempotency behavior make it safe.


Making other infrastructure reliable

One pattern that emerged later was using this system to make other infrastructure more reliable.

We use RabbitMQ for event broadcasting. When an email comes in, we publish an event so other services can react. But RabbitMQ can go down. Network partitions happen. What do you do?

You don't publish directly. You write the event to your database in the same transaction as your business logic, then create a resilient job to publish it. Give the event a stable id in that same transaction, so every attempt to publish it carries the same identity.

Code
import { randomUUID } from 'crypto';

async function handleIncomingEmail(email: Email): Promise<void> {
  // Both operations in same transaction
  await db.$transaction(async (tx) => {
    // 1. Save to database (source of truth)
    const saved = await tx.receivedEmail.create({ data: email });

    // 2. Create a job to publish to RabbitMQ, with a stable event id
    await tx.resilientJob.create({
      data: {
        type: 'publish-email-event',
        resourceKey: 'rabbitmq-main',
        payload: { eventId: randomUUID(), emailId: saved.id }
      }
    });
  });
}

// The job processor:
async function publishEmailEvent(
  payload: { eventId: string; emailId: string }
): Promise<void> {
  const email = await db.receivedEmail.findUnique({
    where: { id: payload.emailId }
  });

  // At-least-once: the same eventId goes out on every attempt
  await rabbitMQ.publish('email-events', transformToEvent(email), {
    messageId: payload.eventId,
    persistent: true
  });

  // Bookkeeping for dashboards and cleanup. NOT a duplicate guard.
  await db.receivedEmail.update({
    where: { id: email.id },
    data: { isPublished: true }
  });
}

Notice what the isPublished flag does not do. Publishing to RabbitMQ and updating the row are two separate systems, so there is no transaction around them. The crash window looks like this:

Code
1. worker publishes the event      -> RabbitMQ accepts it
2. worker crashes                  -> row still says isPublished = false
3. job is reclaimed and retried    -> worker publishes the same event again

The outbox keeps the event alongside the business write so a relay can retry it, but a publish can happen more than once. Checking isPublished before publishing may save work; it cannot close the crash window. At-least-once publishing also depends on a durable database, a relay that keeps retrying, publisher confirms, appropriate broker durability, and handling unroutable messages. The rabbitMQ.publish call above is illustrative: its promise must represent a confirmed, successfully routed publish before the job is marked complete.

Duplicates are then the consumer's problem, and the consumer solves it with the event id. It records every event id it has handled, with a unique key, in the same transaction as its side effect:

Code
model ProcessedEvent {
  eventId     String   @id // unique: one row per event, ever
  processedAt DateTime @default(now())
}
Code
async function handleEmailEvent(msg: Message): Promise<void> {
  const eventId = msg.properties.messageId;

  await db.$transaction(async (tx) => {
    // Insert-if-absent. count === 0 means we have seen this event before.
    const inserted = await tx.processedEvent.createMany({
      data: [{ eventId }],
      skipDuplicates: true
    });
    if (inserted.count === 0) return; // duplicate: do nothing

    // The side effect commits or rolls back together with the inbox row
    await applyEmailEvent(tx, msg);
  });

  channel.ack(msg); // a crash before this just redelivers; the inbox absorbs it
}

Because the inbox row and the side effect commit together, a redelivered message either finds the row and does nothing, or finds no row because the first attempt rolled back and so runs again. That only holds when the side effect lives in the same database. If the consumer calls an external API instead, use the event ID as an idempotency key only if the provider supports and enforces one for that operation. Otherwise, reconcile ambiguous results or accept that duplicates may need manual handling.


What each piece guarantees, and what it doesn't

Most of the bugs in this area come from asking one piece to promise what only a combination can.

PieceWhat it guaranteesWhat it does not
Durable queue storageA message survives a broker restart (with durable queues and persistent messages)Delivery to a consumer, or that a message was ever processed
At-least-once deliveryA message is redelivered until acknowledgedThat it arrives once: crashes before the ack produce duplicates
Atomic job claimingOne worker wins a particular conditional claimOverlap after lease expiry, or a job running again after a crash
Consumer idempotencyHandling the same event twice has the effect of handling it onceProtection for effects outside the idempotent boundary
Transactional outboxThe event record commits with the business writeDelivery by itself: relay and broker durability matter, and publishing can repeat
Provider idempotency keysThe provider applies one request once for a given key (where the provider supports it, for the window it stores keys)Anything if the provider ignores the key, or after its key expires
Recovery after ambiguous failuresA timeout or crash becomes a retry or a safe check, not silenceKnowing whether the first attempt worked: only an idempotent retry or a status lookup settles that

An ambiguous failure is the hard one: the request timed out, and you don't know whether the API did the work. You can't tell from the timeout. So you retry with the same idempotency key, or ask the provider for the state, rather than guess.

The line to draw is this. Exactly-once effects can be achieved within a defined boundary, such as a database transaction with a unique event ID, or a provider operation with a supported idempotency key. That guarantee does not automatically extend to every email or external action. After a crash, the code may execute a step again; whether the repeated step is harmless depends on the system receiving it.


When to use what

Queues are optimized for throughput. They want to move messages as fast as possible. That's good for many use cases. But when you're dealing with external APIs that have their own opinions about how fast you should go, throughput isn't the goal. Reliability is.

A database-backed job system adds polling and database load; its throughput and latency depend on the implementation. In return, a job row makes it straightforward to query status, update a schedule, and make decisions using stored history. Durability still depends on the database's configuration and recovery plan.

Use queues when:

  • High throughput internal communication
  • Simple fire-and-forget messages
  • You don't need to query or modify messages after enqueueing
  • You have existing queue infrastructure and expertise

Consider database-backed jobs when:

  • External API integrations with rate limits and auth flows
  • You need to query job status, history, and failures
  • You need to cancel or modify jobs after creation
  • Long delays (hours, days) between attempts
  • Observability is more important than raw speed

After we deployed this, the difference was obvious. Jobs that failed were automatically retried with appropriate backoff. OAuth tokens that expired overnight were refreshed transparently. When a user's connection had a persistent issue, the circuit breaker opened, their jobs were deferred, and there was a clean log entry explaining exactly what was wrong.

It wasn't magic. It was just software that remembered what happened and made reasonable decisions about what to do next.

That's all resilience really is.

Sources and further reading

The primary material behind the patterns above, and the pieces worth reading in full.

  • Exponential backoff and jitter from the AWS Architecture Blog. The post that made jitter standard practice, with the simulation showing why plain exponential backoff still synchronizes clients.
  • Timeouts, retries and backoff with jitter in the Amazon Builders' Library. The operational version of the same argument: retry budgets, when a retry makes an outage worse, and why every retry needs a timeout above it.
  • Circuit breaker by Martin Fowler. The canonical description of the three states and what each one is for. The idea originates in Michael Nygard's Release It!, which is worth the whole book.
  • Addressing cascading failures and Handling overload from the Google SRE book. What actually happens when a dependency degrades and everyone retries into it, written by people who watched it happen at scale.
  • Timeouts, retries, and idempotency by Marc Brooker. Short, precise, and the clearest explanation of why retries are only safe when the operation is idempotent.
  • Transactional outbox on microservices.io. The pattern for making a database write and the message announcing it atomic, which is the gap this article's job table closes by hand.
  • Stripe: idempotent requests. A production API's idempotency key design, and a good model to copy when you own the endpoint being retried.
  • RFC 6749, the OAuth 2.0 framework. Section 6 covers refresh tokens, which is the specification behind the 401 handling above.

Continue learning

This design assumes work can be delivered more than once. For the failure windows behind that assumption, read Why Exactly-Once Processing Is Hard. The circuit breaker walkthrough goes deeper on timeouts, retries, and the half-open probe.

FAQ

Should I always use a database instead of a queue? No. This design suits jobs that are long-lived, queryable, modifiable after enqueue, or delayed by days. For high-throughput fire-and-forget work, a broker is simpler and faster.

How do I pick the maximum retry count? From the failure you are retrying. A temporary rate limit may resolve after the provider's indicated delay; choose a retry budget and backoff that fit that limit and the job's deadline. A broken credential will never resolve on its own, so retrying it at all is wasted work. Classify the error first, then choose.

Does a circuit breaker need to be shared across workers? Not always. Per-worker breakers can protect each worker without another shared dependency, but each discovers the outage separately and can send its own probe. Shared state can coordinate the fleet; if you use a database row, make claims atomic and handle expired leases and stale results.

CONCEPTS IN THIS ARTICLE

KEEP GOING

Get the next deep dive by email

New deep dives on how production systems really behave, from Kubernetes networking to PostgreSQL internals. About one email a month.

You will get one email to confirm. Unsubscribe from any email with one click. Your address is used for this newsletter and nothing else.

Written by Zeeshan Adil

I run systems like this for a living. If your team is fighting the same problem, or wants this as a talk, write to me.