The credits side of this is covered in the hold/charge credit ledger; this post is about the transport that decides when a run can settle. The queue layer is BullMQ, whose retries cover the internal job; the postback covers the provider’s delivery.
Why use a postback instead of polling?
Polling wastes requests in proportion to how long the job takes and how often you ask. A fifteen-minute job checked every ten seconds is 90 status calls per check; checked every second, it is 900. None of those calls makes the job finish sooner, and each one costs a request against a provider rate limit and a worker’s time.
Postbacks invert the relationship. The provider holds one URL per task and calls it once when the result exists. The cost is one request per completed job, and the system learns about completion at the moment it happens rather than on the next tick.
There is a second benefit: a postback carries the result. A polling design fetches it after the status flips, which is another call and another failure point. The callback delivers the payload, so the handler stores it immediately.
The trade-off is that callbacks are not guaranteed. Networks drop requests, endpoints restart, and a postback without a fallback poller waits forever for a message that was lost. That is why both exist here.
How the task post carries a callback
The flow has six steps, and each one owns a distinct failure:
- Create the fetch row. Before posting, write a cache row with the key (phrase, location, language, device, UTC day) and a status of queued. The row’s id is the handle for everything that follows.
- Mint a per-fetch token. Sign a token that names the fetch, so a callback can only resolve the fetch it was issued for. A shared global secret would let one leaked URL settle any job.
- Post the task with the callback. The task includes the keyword, location, language, device, depth 100, normal priority, a tag holding the fetch id, and the callback URL with the token and the provider’s
$idplaceholder. - Wait. No worker blocks on the result. The queue holds the work, and the run stays open.
- Receive the callback. Verify the token, load the fetch by id, and check whether it is already settled.
- Fan out and settle. Store the trimmed items, then resolve every run item pointing at that fetch. When the last item resolves, the run is charged and closed.
The $id placeholder matters: the provider substitutes its own task id into the callback URL, so the handler receives both the fetch token and the provider’s identifier. The token proves the callback was issued for this fetch; the task id exposes a mismatch between row and payload.
What the handler writes
The handler stores a trimmed result, not the raw provider body: organic items with positions and URLs, the SERP features, and the measured cost. Everything else is dropped at the boundary, so undocumented provider fields never reach the data model.
A fetch moves from queued to settled exactly once. A second callback finds a settled row and returns success without writing anything, because a duplicate is not an error; it is the behaviour of a retrying sender.
Signing a callback you can trust
Two directions need authentication. Callbacks arriving from the provider carry a per-fetch token in the URL. Deliveries leaving the app for a customer webhook carry an HMAC signature over a timestamp and the raw body. The signature is the part teams usually get wrong.
The signature covers the timestamp and the raw body, not a parsed object. Re-serialising JSON before verifying is a classic bug: key order and whitespace change, the signature stops matching, and the fix is usually to loosen verification rather than to sign the bytes.
import { createHmac, timingSafeEqual } from "node:crypto";
export function verifyCallback(raw: string, header: string, secret: string, now = Date.now()) {
const parts = Object.fromEntries(header.split(",").map((p) => p.split("=") as [string, string]));
const timestamp = Number(parts.t);
if (!Number.isFinite(timestamp) || Math.abs(now / 1000 - timestamp) > 300) return false;
const expected = createHmac("sha256", secret).update(`${parts.t}.${raw}`).digest();
const received = Buffer.from(parts.v1 ?? "", "hex");
if (received.length !== expected.length) return false;
return timingSafeEqual(received, expected);
}
Three details are easy to miss. The comparison is constant-time, so an attacker cannot learn the correct digest byte by byte. The length is checked before the comparison, because a length mismatch throws rather than returning false. The timestamp window is five minutes, which is short enough to limit replay and long enough to survive clock skew.
For the provider’s own callbacks, the token in the URL is the credential. The handler verifies it, then checks the fetch status before writing. The token is per fetch, so a leaked token compromises one result, not the account.
Idempotency and retries
Duplicate delivery is normal. Providers retry on timeouts, and a worker that crashes after writing but before acknowledging sees the same message again. The system has to be correct when the same callback arrives three times.
Four rules make that true:
- Every delivery has an identity. An outbound delivery carries a stable event id across retries, and an inbound callback is keyed by its fetch. A duplicate finds an existing identity and returns success.
- Settlement is a state transition, not an increment. A fetch moves to settled once, and a second attempt sees the state and stops.
- The charge is keyed by the run. If two paths try to charge, the second finds an existing charge and does nothing.
- The delivery log is append-only. Every attempt records status, duration and attempt count, so a duplicate is visible.
Retries need a schedule, not a loop. Outbound deliveries go at 1m, 5m, 30m, 2h, 6h, 12h and 24h, eight attempts in total. A ten-second timeout and a no-redirect rule stop a slow or hostile receiver from holding a worker. After 20 consecutive failed deliveries, the endpoint is disabled and the owner is emailed, because a dead endpoint that retries forever is a queue that never drains.
BullMQ provides the same primitive for internal jobs: an attempts count plus a fixed, exponential or custom backoff. The queue’s retry is for the job; the webhook’s retry is for the delivery. They are separate budgets.
When the postback never arrives
When a callback never arrives, a fallback poller fetches the result directly. Every five minutes it looks for fetches still open past their expected window, calls the provider’s “tasks ready” endpoint, then fetches the specific result. It is the callback’s data path, entered from the other side.
Two thresholds matter. The poller’s job is to catch a missing callback before a customer notices; the run’s 60-minute limit is the backstop. When the limit is reached, unresolved items are refunded and the run is marked PARTIAL, which is honest: some work completed and some did not. Marking it FAILED would hide the completed work; marking it DONE would charge for work that never happened.
The admin console shows callback latency next to queue depth. That pairing is what makes the failure visible: a rising latency with a flat queue is a provider problem, while a flat latency with a growing queue is a worker problem.
Queues: fan-out without competing consumers
One completed fetch can resolve run items across many runs, so the handler does not fan out inline. It publishes an event, and a router worker copies that event to one queue per consumer: email, webhooks, alerts.
The subtle rule is one consumer per queue. Two workers on the same queue are competing consumers, so each event reaches only one of them and the email and webhook consumers split the stream. The event worker factory refuses that configuration rather than failing intermittently in production.
Each consumer retries on its own budget. A webhook endpoint that is down for an hour does not hold up the digest email. Fan-out by queue is what buys that independence.
Comparison: three ways to wait for a slow job
| Approach | Requests per 15-minute job | Result delivery | Failure handling |
|---|---|---|---|
| Poll every 10 seconds | About 90 status calls | Separate fetch after ready | Detects stalls, wastes requests |
| Postback with fallback poller | 1 callback, plus a poll only when missing | Payload arrives with the callback | Needs idempotency and a sweeper |
| Streaming or long-poll | 1 held connection | Pushed over the open connection | Connection limits and proxy timeouts |
Which should you choose?
Use a postback when the provider supports one and the job can take minutes: rank checks, report renders, batch imports. Add a fallback poller on a fixed interval, because some callbacks will be lost. Use polling when the provider has no callback support and the job is short enough that a few status calls cost less than the callback infrastructure. Avoid long-held connections for jobs measured in minutes; proxies time them out.
What broke and what we changed
The idempotency lock swallowed real retries. The Stripe webhook handler wrote its dedupe row before doing the work. If the handler then failed, the row stayed, and the retry was treated as a duplicate and dropped. The fix was to wrap the handler, delete the dedupe row on failure, and return a 500 so the sender retries. A dedupe key is a promise that the work is done, so it cannot be written before the work is.
A bot challenge would have blocked the callbacks. The app sits behind a proxy with managed rules and bot protection enabled. A challenge on the callback path would return an HTML page to a provider that expects a JSON 200, and the provider would retry until it gave up. The deploy configuration carries an explicit skip rule for the callback paths, and it sits in the deploy checklist, not in an incident review.
Two paths can settle the same fetch. The callback and the fallback poller can finish within milliseconds of each other. Settlement is a conditional update, so only one wins and the other reads the settled row and exits. The charge follows the same rule, which is why a duplicate callback cannot double-charge.
“Ready” is not “this result”. The provider’s ready endpoint reports that tasks are available, not which one. A fallback that treats a ready response as “this fetch is ready” retries in a tight loop. Poll the task by id and treat “not ready” as a normal outcome with a delay.
A retry schedule with no ceiling is a queue that never drains. A customer endpoint that returns 500 for a week would hold deliveries forever and make the delivery log useless. The eight-attempt schedule plus the 20-failure disable rule bounds the damage.
Related
Frequently asked questions
Why not just poll every second?
Because polling does not make the job finish faster, and it multiplies requests by the job's duration. A fifteen-minute job polled every second is 900 status calls, each one a request against a rate limit and a worker slot. The provider's queue is the bottleneck; the extra calls buy no latency.
What happens if the postback is delayed?
The result is still valid when it arrives. The handler stores it and settles the fetch, and the run closes when its last item resolves. If the run hits its 60-minute limit first, the pending items are refunded and the run is marked PARTIAL. A late callback for an already-settled fetch is a no-op.
How do you verify a callback came from the provider?
Two checks. The callback URL carries a per-fetch token that the handler verifies, which proves the request was issued for that fetch. The provider's own status and task id are then checked against the stored row. For outbound webhooks the system signs timestamp.body with HMAC-SHA256 and rejects anything older than five minutes.
Is a postback more reliable than polling?
No, it is faster and cheaper, but not more reliable. Postbacks get lost, which is why a fallback poller exists. The combination is more reliable than either alone: the callback gives low latency and payload delivery, and the poller catches what the callback missed.
Why is the callback handler idempotent if the provider only sends once?
Because "once" is a claim about the sender's intent, not the network's behaviour. A response timeout can make a provider retry a request that was already processed, and a crash between the write and the acknowledgement does the same. Idempotency makes both cases safe.
