Retry on API Errors? For Document Tasks, First Distinguish Which Failures Are Recoverable

Retrying after an error is very common, but retrying endlessly turns small faults into big ones. Permission errors, overdue account payments, corrupted files, and temporarily busy services should not all follow the same retry path. Once they are classified, you can then decide how long to wait, how many times to try at most, and whether user intervention is needed.

Key points of this article

  • After an API error, do not retry uniformly; first handle each failure category separately.
  • When a POST times out, the server may already have created the task. Without an idempotency key or a query mechanism, blindly resending will create duplicate tasks.
  • In the example, only transient failures are retried with bounded backoff of 1, 2, and 4 seconds; once the retry limit is reached, retrying stops and should not continue indefinitely.
  • Expired permissions, account arrears, and input errors should be handled separately: prompt re-authorization, stop and report, or ask the user to correct the input.
  • Distinguish between logical tasks and attempt records, and accept only one verified result, to avoid mistakenly counting the number of attempts as the number of requests.

Retrying after an error is a very common practice, but if you retry indiscriminately and without limit, a minor fault can be amplified. Permission errors, overdue account payments, corrupted files, and temporary service busyness should each take a different handling path.

This article is suitable for developers and product teammates working on asynchronous tasks such as document translation and conversion. After reading it, you can first classify failures, then decide how long to wait, how many times to retry at most, and when user intervention is needed.

The code and workflow below are all based on synthetic samples. Before processing important files, keep the originals, and review them against the boundaries and acceptance items described in the text.

How should I retry after a document task error? One-sentence conclusion

First classify the failure, then decide whether to retry: transient faults get bounded backoff, permission and account problems stop and are handed to the user, and input errors are returned to the user to fix.

Your situationRecommended PracticesCause
Service Temporarily CongestedBounded backoff: limit the number of retries and the total wait timeAvoid intensive simultaneous retries of all tasks at once
Login or permission expiredPrompt the user to re-authorizeRepeatedly using old credentials will only keep failing.
Account or billing anomalyStop and reportShould not automatically recharge or switch accounts
Input structure errorLet the user fix the inputResending the exact same document is pointless.
POST request timeoutFirst confirm whether the interface supports an idempotency key or a task query.The client not receiving a response does not mean the server did not create the task.

First determine whether retrying would produce duplicate tasks

POST timeouts are especially troublesome. When the client receives no response, that does not mean the server failed to create the task. If the API has no idempotency key and no task query mechanism, blindly retrying may create multiple translation tasks.

Therefore, the retry strategy should prioritize following the interface contract, rather than looking only at the HTTP status code.

Writing the attempt count and wait budget as pure functions

from enum import Enum

class Failure(Enum):
    TRANSIENT = "transient"
    AUTH = "auth"
    BILLING = "billing"
    INVALID_INPUT = "invalid_input"

def delay_for(kind, attempt, replay_safe):
    if type(attempt) is not int or attempt < 0:
        raise ValueError("invalid attempt")
    if not replay_safe or kind is not Failure.TRANSIENT:
        return None
    schedule = (1, 2, 4)
    return schedule[attempt] if attempt < len(schedule) else None

assert delay_for(Failure.TRANSIENT, 0, True) == 1
assert delay_for(Failure.TRANSIENT, 2, True) == 4
assert delay_for(Failure.TRANSIENT, 3, True) is None
assert delay_for(Failure.TRANSIENT, 0, False) is None
assert delay_for(Failure.BILLING, 0, True) is None
assert delay_for(Failure.INVALID_INPUT, 0, True) is None

This code only computes the retry schedule; it neither actually waits nor sends any requests. The fixed one-, two-, and four-second values are numbers from a synthetic demo, not general service recommendations.

In a production environment, the following points also need to be considered:

  • Retry-After returned by the server
  • Random jitter to avoid many tasks resuming at the same time
  • Overall deadline
  • Concurrency limit

If the wait time required by the server exceeds the local budget, retries should be stopped rather than sending the request early.

Error types map to different actions

FailedOptional actionsShould not be done by default.
Temporary congestionBounded backoffAll tasks are being resent densely at the same time.
Login or permission expiredExplicitly prompt for re-authorizationRepeatedly reusing old credentials
Account or billing anomalyStop and reportAuto-recharge or switch account
Input structure errorLet the user fix the inputResend the exact same file

Saving Logic for Tasks and Attempt Records

One user action corresponds to one logical task, and this logical task can have multiple attempts. Each attempt records its start time, failure category, and remote task ID. In the end, only one accepted result is selected.

The benefit of doing it this way is that when troubleshooting retry issues, there is a complete record, and attempt counts won't be mistakenly counted as user request counts.

📊 Core Comparison

ConceptWhat to recordFunction
Logic TaskOne user actionThe same request as seen by the user
Attempt to recordStart time, failure category, remote task IDUsed for troubleshooting the retry process
Acceptance ResultsAn accepted outputAs the final deliverable

Translation Experience Stability Comes from Clear Explanation

When integrating with OmniDoc, the frontend should clearly tell users the current status: whether it is waiting, needs re-authorization, or requires checking the account. Do not display every situation as "Generating."

Users are willing to wait for a stateful task that has a clear exit, but they are unwilling to repeatedly click a button that gives no feedback at all.

References: Python enum.

🎯 Which Approach Suits You?

If you are waiting for a service to recover

Use bounded backoff: set a maximum number of attempts and a total waiting time, and respect the Retry-After sent by the server.

If you encounter permission or account issues

Stop automatic retries and prompt the user to re-authorize or check their account status.

If your input file has an incorrect structure

Ask the user to fix the file before resubmitting, rather than resending the same file.

If the API you're calling is POST and may time out

First check whether the endpoint supports an idempotency key or a task-status query, then decide whether to resend the request.

❓ Frequently Asked Questions (FAQ)

1. Can all errors simply be retried?

No. Permission errors, account arrears, corrupted files, and temporary service overload should be handled separately; only transient failures are suitable for bounded backoff.

2. Can I resend a POST directly after a timeout?

It is not recommended to resend directly. If the client receives no response, that does not mean the server failed to create the task. Without an idempotency key or a task-query mechanism, this may result in duplicate tasks.

3. How should the number of retries and wait times be determined?

The fixed one, two, and four seconds are only a synthetic demonstration. In production, you should decide based on Retry-After, random jitter, an overall deadline, and concurrency limits.

4. Will the number of attempts affect the statistics of user request counts?

No. As long as one user operation is recorded as one logical task and each retry is recorded as an attempt record under that task.

📝 Summary

The key to retrying is not trying more times, but first distinguishing the type of failure, and then deciding what to do. Faults that can be recovered from are retried a bounded number of times, while problems that require human intervention are promptly handed back to the user.

Try it now: upload a document and start translating right away, with the original layout preserved.

Updated 2026-11-29