ferrybox/docs

Retry failed jobs

Handlers fail: a database restarts, a provider rate-limits you, a deploy drops connections. This guide sets a retry policy that rides out short outages, makes repeats harmless, and gives you a clear way to recover the jobs that still fail.

  • 12 min read
  • Intermediate
  • Tested with API v2.4 and ferry 2.4.1
On this page
  1. What counts as a failure
  2. Set a retry policy
  3. Make the handler idempotent
  4. Test failures locally
  5. Work the dead-letter queue
  6. Next steps

Before you start

You need a queue and a handler that already receives jobs. If you don’t have one yet, follow the Quickstart first.

1What counts as a failure

Ferrybox decides what to do next from your handler’s response. Anything in the 2xx range is a success. Responses that suggest a temporary problem are retried; responses that say the request itself is wrong are not, because sending the same body again would fail the same way.

How Ferrybox treats each response
ResponseOutcomeWhat happens
2xxSucceededJob is marked done. Response body is stored (first 4 KB).
408, 429, 5xxRetryNext attempt scheduled from the retry policy. Retry-After is honored up to max_delay.
TimeoutRetryNo response within timeout (default 30 s). Counts as one attempt.
Connection errorRetryDNS failure, TLS error, or refused connection.
Other 4xxFailedNo retry. Job moves to the dead-letter queue immediately.

If you want a 4xx to be retried, for example a 404 while a record replicates, return 503 with a Retry-After header instead.

2Set a retry policy

Retry policies live on the queue, and any job can override them. Start with the defaults below and change one number at a time once you have attempt logs to look at.

queue.json

{
  "name": "emails",
  "concurrency": 10,
  "timeout": "30s",
  "retry": {
    "max_attempts": 8,
    "backoff": "exponential",
    "initial_delay": "10s",
    "max_delay": "1h",
    "jitter": 0.2
  }
}

CLI

$ ferry queues update emails \
    --max-attempts 8 \
    --backoff exponential \
    --initial-delay 10s \
    --max-delay 1h

Node.js

import { Ferrybox } from "@ferrybox/node";

const fbx = new Ferrybox(process.env.FERRYBOX_API_KEY);

await fbx.queues.update("emails", {
  retry: { maxAttempts: 8, backoff: "exponential", initialDelay: "10s", maxDelay: "1h" },
});

Python

import os
from ferrybox import Ferrybox

fbx = Ferrybox(os.environ["FERRYBOX_API_KEY"])

fbx.queues.update("emails", retry={
    "max_attempts": 8,
    "backoff": "exponential",
    "initial_delay": "10s",
    "max_delay": "1h",
})

With exponential backoff, each delay doubles from initial_delay until it reaches max_delay. Ferrybox adds ±20% jitter so that a burst of failures doesn’t retry in lockstep against a service that is trying to recover.

Delays for the default policy (8 attempts, 10 s initial delay)
AttemptBase delayWith jitter
10 simmediately
210 s8–12 s
320 s16–24 s
440 s32–48 s
51 min 20 s64–96 s
62 min 40 s128–192 s
75 min 20 s4 min 16 s – 6 min 24 s
810 min 40 s8 min 32 s – 12 min 48 s

Tip

The whole default schedule spans about 21 minutes. If your provider’s outages usually last longer, raise max_attempts before you raise initial_delay.

3Make the handler idempotent

An attempt can time out on Ferrybox’s side after your handler has already done its work. The next attempt will then repeat it. Every request carries a Ferrybox-Job-Id header that stays the same across attempts; record it when the work is done and check it first.

Warning

Retries make delivery at-least-once. Without this check, a slow mail provider can send the same welcome email two or three times.

handlers/welcome.js

export async function welcome(req, res) {
  const jobId = req.get("Ferrybox-Job-Id");

  // Skip work this job already finished on an earlier attempt.
  const done = await db.sentEmails.findOne({ jobId });
  if (done) return res.status(200).json({ skipped: true });

  await mailer.send({ to: req.body.email, template: "welcome" });
  await db.sentEmails.insert({ jobId, sentAt: new Date() });

  res.status(200).json({ sent: true });
}

handlers/welcome.py

def welcome(request):
    job_id = request.headers["Ferrybox-Job-Id"]

    # Skip work this job already finished on an earlier attempt.
    if SentEmail.objects.filter(job_id=job_id).exists():
        return JsonResponse({"skipped": True})

    mailer.send(to=request.json["email"], template="welcome")
    SentEmail.objects.create(job_id=job_id)
    return JsonResponse({"sent": True})

Write the job ID in the same transaction as the work when you can. If the work is an external call, as here, write it right after and accept a small window for duplicates.

4Test failures locally

Rehearse the policy before production does it for you. ferry dev routes a test queue to your machine and can fail attempts on purpose.

  1. Start a tunnel to your local server

    ferry dev forwards jobs from a test queue to a port on your machine. Test keys only; live jobs are never routed to localhost.

    Terminal
    $ ferry dev --queue emails --port 3000
    Forwarding emails (test) → http://localhost:3000
    Press Ctrl+C to stop.
  2. Send a job that fails twice

    --fail-first makes the tunnel answer 503 for the first N attempts without calling your handler, so you can watch the backoff.

    Terminal
    $ ferry jobs send emails --data '{"email":"dana@example.com"}' --fail-first 2
  3. Read the attempt log

    Each attempt shows the status, duration, and when the next one is due. Delays in test mode are divided by 10.

    Terminal
    $ ferry jobs attempts job_01JC9A7T3V
    #  STATUS  DURATION  AT        NEXT
    1  503     3ms       14:10:02  +1.0s
    2  503     2ms       14:10:03  +2.0s
    3  200     41ms      14:10:05  –

5Work the dead-letter queue

Jobs that run out of attempts, or fail with a non-retryable status, move to the queue’s dead-letter queue. They stay there for 14 days. Fix the cause first, then replay only what the fix covers.

Terminal
$ ferry dlq list emails --since 24h
JOB ID              FAILED AT         ATTEMPTS  LAST STATUS
job_01JC7Z0QWE      Nov 9, 22:14      8         503
job_01JC81H2MK      Nov 9, 23:40      1         422
job_01JC8B6RTA      Nov 10, 03:05     8         timeout

$ ferry dlq replay emails --since 24h --status 503,timeout
✓ Replayed 2 jobs. Skipped 1 (422 is not retryable).

Replayed jobs keep their original ID and start again at attempt 1, so your idempotency check still applies.

6Next steps

Palette

Palettes · 60 / 30 / 10