Hardware FixRecommendedDevice not working? Your driver may be the problemCheck updates for common hardware issues.Fix DriversThanksgiving DealsAmazon USThanksgiving week: Black Friday picks start earlyAmazon US: current deals, useful picks and tech finds.Check DealsPC HealthRecommendedCrashes, freezes, slowdowns? Check your PC nowSpot repairable issues before they interrupt work.Check PC×
FREEDOM251

Freedom251 › Blog

Retrying Jobs and Refunds: Why Compensation Belongs on Terminal Failure

By Freedom251 Team · · 10 min read

What’s actually slowing this PC down?

Pick the symptom - the matching free tool is one click away.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Some links on this page are affiliate links: if you buy through them we may earn a commission, at no extra cost to you.

Refunding a user after every failed job attempt is a correctness bug when the job can retry. A transient failure may be followed by a successful attempt, leaving the user with both the completed result and an unnecessary credit. The safe rule is to refund only when the orchestrator declares the run permanently failed, then make the refund operation idempotent so a completion rollback, duplicate event, or race cannot issue a second credit.

Why is refunding inside a retry catch a bug?

A retryable task has two different failure states: an individual attempt can fail, or the entire run can fail after no more attempts remain. Those states are not interchangeable. Trigger.dev’s materials describe automatic retries for background work, and its failure-alert documentation distinguishes a run that has failed and will not be retried from an attempt that merely encountered an error. See the platform’s failed-run alert explanation for that distinction.

As an Amazon Associate I earn from qualifying purchases.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Imagine a mock-interview workflow in which submitting an interview costs one credit. The task processes uploaded videos, generates feedback, saves that feedback, removes source files, and emails the user. If the first attempt fails because a video service times out, a retry may complete the interview. A refund in the first attempt’s catch block would then leave the user with a completed interview and the credit back. The system has paid twice for one job.

The bug is not limited to money. The same mistake can create contradictory audit records, make account balances drift, and encourage users to resubmit work that is already running. Compensation must follow the business outcome, not the error observed by one attempt.

Popular on Amazon
Sale
Silkland 40Gbps USB C 90 Degree Right Angle Adapter 2 Pack, 240W USB4 | Male to Female Extender, 8K@60Hz, Thunderbolt 4/3, Steam Deck, ROG Ally, MacBook, Switch 2, iPhone 18/17/16/15, Quest 3 VR
  • 【90 Degree Full Function USB C Adapter】Supports the latest USB4 standard for up to 40Gbps of bandwidth, 8K video support, and up to 240W Fast charging; Support USB PD 3.1 Extended Power Range (EPR) including 140W, 180W and 240W. Your productivity is easily doubled. *Warm Tip: For the best fit, please make sure the USB-C port is fully exposed; thick or bulky cases may affect compatibility.
  • 【Reliable Quality】Made from high-quality, scratch-resistant aluminum alloy, delicate metal frame. get excellent wear resistance and heat dissipation. Non-Slip Design for easier insertion and removal.
  • 【Small and portable】Ultra thin size, ultra compact design, a petite physique that matches the minimalist design of your modern laptops. Coming with a slim figure that won't block the port next to the one it's plugged into.
  • 【Compatibility】Widely work with most usb c, thunderbolt 4/3 devices. Compatibilit for ROG Ally, Steam Deck, Switch, MacBook Pro, Quest 3 VR headset, Surface Book 2, iPhone 18/17/16/15, Samsung Galaxy S23/S22/S21, Note 20/10, Google Pixel, ChromeBook, etc.
  • 【Excellence Customer Support】If you experience any issues or cable failure, simply reach out to our dedicated customer service team. We provide a prompt response within 18 hours, providing you with the necessary technical support to resolve any concerns.

When should a retrying job issue the refund?

Issue the refund when the run reaches terminal failure: retries are exhausted, or the workflow has explicitly decided that no further retry is useful. Put that decision in the orchestrator’s final-failure hook when the installed SDK provides the required semantics. The exact callback names and signatures can change, so verify them against the documentation for the SDK version in your project rather than copying an old example verbatim.

Daniel Pertu’s implementation article places the permanent-failure refund in an onFailure callback and keeps per-attempt error handling focused on retry behavior. The example task is configured for three attempts with exponential backoff and randomization; those values illustrate a policy, not a universal recommendation. Your retry count and delays should reflect the services involved and the user’s tolerance for waiting.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Event What it means Refund action
Attempt fails and retries remain The run may still produce the paid outcome. Do not refund.
Error is classified as unrecoverable Continuing would be wasteful or harmful. Skip further retries, then let terminal-failure compensation run.
Final retry fails The orchestrator has declared the run permanently failed. Call the idempotent refund helper.
Completion handoff cannot be submitted The paid outcome may never enter the worker. Use a rollback path that calls the same idempotent helper.

How do retry eligibility and refund timing differ?

Retry eligibility answers, “Should the system try this work again?” Refund timing answers, “Has the customer definitively lost the paid outcome?” They are related but separate decisions.

A transient network timeout, rate limit, or temporary provider outage can justify another attempt. A malformed upload, invalid account state, or a known permanent provider error may justify stopping immediately. In either case, compensation belongs only after the run is known to be terminally unsuccessful. An unrecoverable error can therefore shorten the path to the refund, but it should not move the refund into a generic per-attempt catch.

Keep error classification explicit. A handler can mark an error as non-retryable, abort additional attempts, and allow the final-failure mechanism to perform compensation. This makes operational policy visible in logs and prevents a future maintainer from accidentally refunding every exception.

Also popular on Amazon
Sale
Anker USB C Hub, 5-in-1 USBC to HDMI Splitter with 4K Display | 85W Max PD, 1 Powered USB-C 5Gbps & 2 Powered USB-A 3.0 5Gbps Data Ports, for MacBook Pro, MacBook Air, Dell and More (Black)
  • 5-in-1 Connectivity: Equipped with a 4K HDMI port, a 5 Gbps USB-C data port, two 5 Gbps USB-A ports, and a USB C 100W PD-IN port. Note: The USB C 100W PD-IN port supports only charging and does not support data transfer devices such as headphones or speakers.
  • Powerful Pass-Through Charging: Supports up to 85W pass-through charging so you can power up your laptop while you use the hub. Note: Pass-through charging requires a charger (not included). Note: To achieve full power for iPad, we recommend using a 45W wall charger.
  • Transfer Files in Seconds: Move files to and from your laptop at speeds of up to 5 Gbps via the USB-C and USB-A data ports. Note: The USB C 5Gbps Data port does not support video output.
  • HD Display: Connect to the HDMI port to stream or mirror content to an external monitor in resolutions of up to 4K@30Hz. Note: The USB-C ports do not support video output.
  • What You Get: Anker 332 USB-C Hub (5-in-1), welcome guide, our worry-free 18-month warranty, and friendly customer service.

What does a terminal-failure implementation look like?

The following is conceptual TypeScript, not a guarantee of the current Trigger.dev API. Names such as onFailure, catchError, or AbortTaskRunError must be checked against the version installed by your application.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
async function runInterview(input) {
  try {
    const feedback = await createFeedback(input.videos);
    await saveFeedback(input.userId, feedback);

    // The paid outcome is now complete.
    await bestEffortDeleteVideos(input.videos);
    await bestEffortEmail(input.userId, feedback);
  } catch (error) {
    if (isPermanent(error)) {
      // Tell the orchestrator not to spend another attempt.
      throw markAsNonRetryable(error);
    }
    throw error; // obey the configured retry policy
  }
}

async function onTerminalFailure(run) {
  await refundCreditOnce({
    userId: run.userId,
    spendId: run.originalSpendId,
    reason: "interview-run-terminal-failure"
  });
}

The important sequence is semantic rather than syntactic: the task either reaches its paid completion boundary or eventually enters the final-failure path. Do not infer terminal failure merely because the current invocation threw.

For production code, record a stable spend identifier when the credit is consumed. Pass that identifier through the task and into the refund helper. A user ID alone is usually too broad: it cannot distinguish two legitimate purchases or two separate interviews submitted close together.

How do you make the refund helper idempotent?

A final-failure hook prevents most premature refunds, but it does not make duplicate delivery impossible. A completion-route rollback may race the worker’s failure callback; an event may be redelivered; an operator may replay a failed run. The helper must make all of those callers converge on one result.

Use a database transaction that locks the user’s balance row (or an equivalent account record), verifies that the original spend exists, checks whether a refund for that spend has already been recorded, and inserts the refund plus balance update only when no prior refund exists. Return a result such as issued: true or issued: false so callers can distinguish a new credit from an already-completed operation.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Also popular on Amazon
Sale
Anker USB C Hub, 7in1 Multi-Port USB Adapter, 4K@60Hz USBC to HDMI Splitter | 85W Max PD, 2 USB 3.0 & 1 USBC Data Ports, SD/TF Card Reader, for Laptops/Mac and Other Type C Devices (Charger Not Included)
  • Sleek 7-in-1 USB-C Hub: Features an HDMI port, two USB-A 3.0 ports, and a USB-C data port, each providing 5Gbps transfer speeds. It also includes a USB-C PD input port for charging up to 100W and dual SD and TF card slots, all in a compact design.
  • Flawless 4K@60Hz Video with HDMI: Delivers exceptional clarity and smoothness with its 4K@60Hz HDMI port, making it ideal for high-definition presentations and entertainment. (Note: Only the HDMI port supports video projection; the USB-C port is for data transfer only.)
  • Double Up on Efficiency: The two USB-A 3.0 ports and a USB-C port support a fast 5Gbps data rate, significantly boosting your transfer speeds and improving productivity.
  • Fast and Reliable 85W Charging: Offers high-capacity, speedy charging for laptops up to 85W, so you spend less time tethered to an outlet and more time being productive.
  • What You Get: Anker USB-C Hub (7-in-1), welcome guide, 18-month warranty, and our friendly customer service.
async function refundCreditOnce({ userId, spendId, reason }) {
  return db.transaction(async (tx) => {
    await tx.userBalance.lock(userId);

    const spend = await tx.creditSpend.findUnique({ id: spendId });
    if (!spend || spend.userId !== userId) {
      throw new Error("Original spend not found");
    }

    const existing = await tx.creditRefund.findUnique({
      spendId,
      unique: true
    });
    if (existing) return { issued: false, refundId: existing.id };

    const refund = await tx.creditRefund.insert({
      spendId,
      userId,
      reason,
      amount: spend.amount
    });
    await tx.userBalance.increment(userId, spend.amount);

    return { issued: true, refundId: refund.id };
  });
}

The transaction and a uniqueness constraint are complementary. The row lock protects the balance during the decision and update; the unique key protects against a second refund even if two requests pass through different application processes. If your database supports an atomic insert-on-conflict operation, use it as an additional safeguard, but still keep the balance update and refund record in one transaction.

Do not silently refund when the original spend is missing. That usually indicates a data-integrity problem and should be logged and surfaced for reconciliation. Likewise, never identify an existing refund by a loose time window or by the user alone.

Where does the completion boundary belong?

Define completion at the point where the customer’s paid outcome is durably available. In the interview example, persisting feedback marks the point of no return. Deleting source videos and sending an email are valuable follow-up actions, but they should be best-effort once the result has been saved. If either cleanup or notification throws back into the main task, the orchestrator could mark a successful interview as failed and issue a refund.

Your boundary may be different. For a document-conversion service, it might be the durable object-store write plus a status record. For a payment export, it might be an acknowledged handoff to the destination system. State the boundary in code and documentation, and make post-boundary work tolerant of retries: catch, log, and schedule it for separate repair rather than reversing the customer’s completed purchase.

Free tools Windows power users keep installed

One-click scans. No signup required.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

This does not mean ignoring cleanup failures. Emit an actionable event, attach the run and customer identifiers, and use a separate retry or reconciliation process. The key is to avoid coupling nonessential side effects to the refund decision.

Also popular on Amazon
Sale
BENFEI USB C Hub 5-in-1 with 4K HDMI(Certified), 100W Power Delivery, 3 USB-A, Silicone Cable, Aluminum Case Compatible with MacBook Pro/Air, iPad Pro, iMac, iPhone 15 Pro/Pro Max, XPS, Thinkpad
  • Portable and powerful USB-C HUB: BENFEI USB Type-C HUB, with super-soft and knot-free silicone woven design cable, meets most mobile office needs. Compact, lightweight, stylish, and powerful portable USB C Hub equipped with 1 x HDMI port, 1 x 100W charging, and 3 x USB ports. 18-month warranty, 24-hour response, to ensure you feel at ease when using our product.
  • Design centered on comfort and reliability: Thanks to BENFEI's end-to-end in-house cable production capability, in-house PCBA and assembly capability, using the industry's most advanced silicone woven design and process, 20cm cable in length, no knots, super-soft, the HUB is easy to use in all scenarios: laptop, tablet, stand etc. Super-soft, 25000+ life cycles, to meet your daily carrying and office needs.
  • 100W Charging: Support up to 90W USB C pass-through charging via Type-C port to keep your laptop powered. 10W is reserved for other interface operations. No data and video function on the Type-C port.
  • 4K HDMI Display: The HDMI port supports media display at resolutions up to 4K 30Hz, keeping every incredible moment detailed and ultra vivid. Please note that the C port of the Host device needs to support video output.
  • Transfer Files in Seconds: Transfer files and from your laptop at speeds up to 10 Gbps with USB A 3.2 port. Extra 2 USB A 2.0 ports are perfectly for your keyboards and mouse.

Can a refund live anywhere besides the final-failure hook?

Yes, but every path must call the same idempotent helper. “Refund in onFailure and nowhere else” is a useful rule against per-attempt refunds, not a literal prohibition on every other compensation path.

Suppose the submission service charges a credit, then fails before it can hand the interview to the task system. The submission route may need to roll back the charge immediately because no worker run exists to reach terminal failure. That route and the task’s final-failure callback can race if the handoff eventually appears or a delayed event is delivered. A spend ID, a unique refund record, and the transaction described above ensure that only one caller issues credit.

Document each caller and its trigger. One path should represent “handoff never accepted”; another should represent “accepted run permanently failed.” They must not both claim the same state without an explicit state machine or idempotency key.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

What should you log and monitor?

Log the run ID, spend ID, attempt number, error classification, retry decision, and refund result. Keep the refund result distinct: “refund issued,” “refund already existed,” and “refund failed” have different operational meanings.

  • Attempt failure: include the next scheduled attempt, if known.
  • Non-retryable classification: record the rule or error code that stopped retries.
  • Terminal failure: record the final attempt and the compensation request.
  • Duplicate request: treat an already-existing refund as a successful convergence, not as a new credit.
  • Missing spend: alert for reconciliation instead of creating money from nothing.

Use dashboards or alerts to find runs that are terminally failed without a refund record, and refunds that have no corresponding failed or rolled-back spend. These invariants catch outages in the compensation path rather than waiting for a customer complaint.

Also popular on Amazon
𝟒𝐏𝐚𝐜𝐤 𝐔𝐩𝐠𝐫𝐚𝐝𝐞𝐝 USB to USB C Adapter,Type-C Female to A Male Charger Converter for iPhone 18 Charger,iWatch Ultra SE 9 10,iPhone 17 Pro Max 16 15 14,Samsung S25,AirPods,iPad,Car,Xbox
  • 【Read before You Buy】 Note: This adapter is USB 2.0 version and cannot transmit HDM, VGA, or other video signals. Nevertheless, they are fully capable of charging devices,duplicating files, and can be seamlessly integrated with USB-C earphones, wireless network adapters, and SD card adapters.
  • 【Easy to Use and Safe】Thanks to modern manufacturing techniques, we've made these adapters sufficiently compact so that they can remain inserted in your device without noticeable protrusion or inconvenience. This means you don't have to constantly plug and unplug them, reducing the likelihood of wear and misalignment, and making them more convenient to carry around.
  • 【Reliable Quality】Engineered for enhanced durability, durable aluminum alloy shell material,get excellent wear resistance and heat dissipation,the male USB C and female USB connectors & the male USB and female USB C connectors are designed to be plugged and unplugged up to 20000 times. Provides data transfer, device charging, memory space expansion, and additional computer peripherals.
  • 【Think more for you】Do you need to connect a USB-C-enabled device to an odd device that only has USB-A ports? Then these USB-A male to USB-C female adapters are made for you.Simply insert the adapter into the USB-A port on the device, and you can instantly connect your USB-C device to the device that originally didn't have the correct connection port.
  • 【Trusted xiwxi Quality and Service】As a responsible brand seller, you will receive xiwxi's 12-month Quality assurance and lifetime friendly customer service, you're not just buying a product,you're investing in peace of mind with all-round quality and exceptional customer service.

How do you review a retry-and-refund design?

  1. Write the business outcome first. Define exactly what must be persisted before the customer is considered to have received the paid service.
  2. List every failure point. Include submission, queue handoff, each external provider, persistence, cleanup, and notification.
  3. Classify errors. Decide which errors are transient and which should stop retries.
  4. Choose the terminal signal. Confirm the installed orchestrator’s final-failure semantics and callback behavior.
  5. Attach a stable spend ID. Never deduplicate refunds using only a user ID or run timestamp.
  6. Implement one idempotent helper. Put the existence check, lock or atomic write, refund record, and balance update in one transaction.
  7. Separate post-completion work. Make cleanup and email failures observable without turning a saved result into a refundable failure.
  8. Reconcile. Monitor spend, completion, terminal failure, and refund records for impossible combinations.

Before shipping, verify the current SDK documentation for the orchestrator callback and error classes. The source article supplies the pattern, while the available official materials confirm the broader distinction between retries and terminal run failure; API names may differ by version. Trigger.dev’s workflow and durable-agent feature overview is a useful starting point for understanding the platform’s execution model.

What are the common failure modes?

  • Refunding in a generic catch: a later retry succeeds, producing a free result. Move compensation to terminal failure.
  • Assuming “non-retryable” means “already refunded”: stopping retries only changes execution; it does not perform compensation unless the final-failure path does.
  • Relying on a callback exactly once: delivery can be duplicated or raced. Enforce idempotency in storage.
  • Refunding after persistence errors caused by email or cleanup: separate those side effects after the completion boundary.
  • Using a mutable run status as the only guard: concurrent readers can observe the same status. Use a transaction and a unique refund key.
  • Retrying the refund without an idempotency key: a temporary database or network error can turn one intended refund into several. Retry the operation by the same spend ID.

What is the practical rule?

Let retries decide whether the work gets another chance; let terminal failure decide whether the customer receives compensation. In the worker, do not refund an individual failed attempt. In the final-failure path, call a transactionally idempotent helper. If another route must roll back a charge before a run exists, have it call that same helper and use the same spend identity.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

This design preserves the core invariant: a customer who receives the paid outcome keeps the credit consumed, while a customer whose run definitively cannot complete receives exactly one refund.

Frequently Asked Questions

What happens if the user asks for a refund while the job is still retrying?

Treat a user-initiated refund as a separate business operation with an explicit cancellation state. Stop or detach future attempts, and ensure the eventual terminal-failure callback sees that the spend was already compensated through the same idempotent refund record.

Should the refund amount be copied from the current price?

No. Store the charged amount on the original spend record and refund that recorded amount. This prevents price changes, promotions, or currency conversions from altering compensation for an older run.

How should partial provider charges be handled?

Model provider-side charges separately from the user credit. A terminal-failure refund to the user does not automatically reverse an external provider charge; record that cost and use the provider’s own reversal or reconciliation process where available.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

What if the final-failure callback itself is unavailable?

Persist enough state to run reconciliation independently: the spend ID, run status, retry count, and completion marker. A periodic job can find terminal failures without refunds and invoke the same idempotent helper safely.

Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply. Prices as of November 23, 2026 9:53 pm GMT+0530.

Leave a Reply

Your email address will not be published. Required fields are marked *

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Recommended PC Tool
Recommended PC Tool
PC Slower Than It Used to Be?Free scan - under a minute
Outdated Drivers Are Slowing You DownFree scan - exact matches

Two free Windows tools

One Free Minute Could Fix That PC

Before you go - each of these free tools takes about a minute and tackles what quietly slows a Windows PC down.

Special offer. View Outbyte info, uninstall instructions, EULA, and Privacy Policy.