# Two failure handlers, one refund: idempotent cleanup in an async AI image pipeline

By Farhad Rezaei (https://farhad-rezaei.com) · Published 2026-12-03
Canonical: https://farhad-rezaei.com/blog/two-failure-handlers-one-refund
Product: MrPicasso (https://mrpicasso.ir)

> In MrPicasso, three handlers can see the same failed render: the worker's catch block, BullMQ's failed event and the Telegram bot's listener. Two Redis SET NX claims keyed on the image ID keep it to one slot release and one refund; there are two because the settlement claim is also taken on success, and a render that worked but never reached Telegram must still be refunded. The refund fails closed when Redis is down, refunding zero rather than twice, and the claims expire and don't commit together with the credit store.

MrPicasso is an AI advertising studio where I lead engineering. You describe the ad you want, maybe attach a reference image, and an image model renders it. Each render costs a credit up front, so when one fails, the credit has to come back exactly once.

In MrPicasso's image worker, a render that throws is reported as failed twice: once by the catch block around the render, and again by BullMQ's `failed` event, which fires for every failed job, including the ones the catch block already cleaned up. If the render came from our Telegram bot, a third listener hears the same failure. Three pieces of code, each correct on its own, all trying to refund the same render.

For a user, this decides whether a failed render costs them nothing, quietly hands them free credits, or, in the case that actually happened, keeps their credit for an image they never received.

Think of a shop's returns desk with several clerks. Whoever gets there first stamps the receipt "refunded" before opening the till, and a clerk who sees the stamp sends the customer on their way.

## One failed render, followed through the code

The API route charges the credit and enqueues a BullMQ job whose ID is the image's own `imageId`, assigned before the job exists. The job has `attempts: 1`, so the queue never reruns a render by itself.

The model call throws. The catch block calls `settleOnce(data, { refund: true })`, which releases the user's concurrency slot and refunds the credit, then rethrows so the job is recorded as failed. BullMQ marks it failed, and the worker's `failed` handler calls `settleOnce` again. That handler exists for a job that dies mid-render, when the process is killed before any catch block runs; its alert blames memory or a container restart.

For a bot render, the bot's own queue listener also hears `failed` and refunds, and so can its periodic sweep and the two-hour TTL that gives up on renders that never finish.

## Why the sum was wrong

Releasing the slot twice would push the user's in-flight counter below the renders still running; the script floors it at zero, which limits the damage without fixing the count. Refunding twice is simply a free credit.

The first guard went in with the queue itself in July, since the catch block and the failed event were there from day one. The third path came later. On 19 August one failed fetch to the Telegram API lost a paid image: it rendered fine, never reached the chat, and, being a private category, had no stored copy to resend. The fix made every bot path that ends without an image refund the user, which added a refunder outside the worker.

## Two stamps, not one

Both guards are a Redis `SET` with `NX`, which succeeds only for the first caller, keyed on the same `imageId`:

```ts
// settle: slot release + optional refund, once per job, for an hour
redis.set(`img:settled:${imageId}`, "1", "EX", 3600, "NX");
// refund: credits back, once per image, for a day
redis.set(`img:refunded:${imageId}`, "1", "EX", 86400, "NX");
```

Why not one key? The settlement key is also taken when a render succeeds, with `refund: false`, which is what stops a late failed event from refunding a render that worked. That makes it useless to the bot: an image that rendered and then failed delivery is settled but still owed. So the refund has its own stamp, and every refunder goes through `refundImageOnce`, carrying the bucket the render was charged from, since bot images are usually paid from the Telegram wallet.

![Three failure paths, the worker catch block, the worker failed event and the Telegram bot, converge on two Redis claims keyed by imageId, so one failed render releases one slot and refunds one credit.](https://farhad-rezaei.com/images/blog/two-failure-handlers-one-refund/paths.svg)

The two claims fail differently when Redis itself errors. `settleOnce` swallows the error and releases the slot. `refundImageOnce` returns `false` and refunds nothing. For money, it fails closed: never twice, but possibly zero.

![What each claim does when it wins, when it loses and when Redis is unreachable, and the case neither covers: a claim taken before a refund that then fails.](https://farhad-rezaei.com/images/blog/two-failure-handlers-one-refund/failure-modes.svg)

## How I checked it

`settleOnce.test.ts` runs against a real Redis: "survives both paths racing" fires eight claims at once and expects exactly one winner. `imageRefunds.test.ts` mocks Redis and the quota store and checks that an image "refunds only once, so worker and bot cannot double-credit", even when the second call names another bucket, that separate images stay independent, that the credit returns to the wallet it came from, and that nothing is refunded "when the claim cannot be taken".

They don't prove everything. The race test exercises the claim, not `settleOnce` inside a live worker. Nothing tests a crash between taking the refund claim and applying the refund, and Redis and the quota store don't commit together: if the refund throws after its stamp is taken, the stamp stays for a day and nothing retries it. The claims also expire, so the design relies on duplicates arriving well inside an hour, which they do here: the worker's lock is 15 minutes and the bot gives up after two hours, both inside the refund claim's day.

## What carries over

- List every path that can observe a job's failure, including framework events that fire after your own catch block.
- Key the guard on an ID that exists before the work starts.
- Don't reuse a "done" marker as a "refunded" marker when success also sets it.
- Decide how each guard behaves when its store is down; for money, never twice beats never.
- Write down what a claim-before-effect guard can lose.

The user's side of this is small: a failed ad costs nothing, and an undelivered one comes back. Underneath, it takes one ID shared by an API route, a queue, a worker and a bot, two claims with deliberately different scopes, and a plain statement of which way each fails. It isn't an exactly-once financial guarantee, and I wouldn't sell it as one; it's a bounded, tested guard against the duplicates this pipeline actually produces.

## Further reading

- BullMQ, stalled jobs: https://docs.bullmq.io/guide/workers/stalled-jobs
- Redis `SET` with `NX` and `EX`: https://redis.io/docs/latest/commands/set/
- Stripe, idempotent requests: https://docs.stripe.com/api/idempotent_requests
- Martin Kleppmann, How to do distributed locking: https://martin.kleppmann.com/2016/02/08/how-to-do-distributed-locking.html
