Asynchronous AI APIs in Production: Polling, Timeouts, Retries, and Task Recovery
A chat completion can often return in one request. A generated video usually cannot. Image, video, and audio systems may spend seconds or minutes scheduling work, running inference, applying post-processing, and transferring the result to storage. Treating that workflow like an ordinary request-response call creates a predictable class of production failures: duplicate submissions, abandoned tasks, misleading timeout errors, and workers that poll forever.
The correct abstraction is not “a slow API call.” It is a stateful job with a durable identity.
This guide explains how to design that job lifecycle, then maps the design to the current Ace Data Cloud SDK behavior. The goal is not to hide asynchronous work behind a convenient helper. It is to make completion, failure, cancellation, reconciliation, and cost boundaries explicit.
¶ Who this guide is for
This article is for backend engineers, AI application developers, and technical founders building products that submit long-running media generation or other task-based AI work.
You should already be comfortable with HTTP APIs and either Python or TypeScript. An Ace Data Cloud application API key is required for the authenticated examples. Keep it in a server-side environment variable rather than source code or browser bundles.
¶ 1. Begin with the response mode, not the modality
Developers often divide AI APIs into text, image, audio, and video. Operationally, a more useful division is:
- Synchronous: one request returns the final result.
- Streaming: one request keeps a connection open and emits incremental frames.
- Asynchronous: one request creates a task; later requests retrieve its state and result.
These modes have different reliability requirements. A streaming chat connection cannot simply be replayed after partial output reaches a user. An asynchronous video task should not be submitted again merely because the client stopped waiting. A synchronous image response does not need a polling loop.
Ace Data Cloud’s current SDK documentation identifies chat streaming as SSE-based and represents supported asynchronous media operations with a TaskHandle. It also warns that synchronous providers should not be forced through task polling. Always check the current endpoint documentation rather than inferring behavior from the word “image” or “video.”
¶ 2. The production state machine
A robust application should store its own job record before or immediately after submission. At minimum, record:
- your internal job ID;
- provider and operation;
- provider task ID;
- trace ID when returned;
- submission timestamp;
- last observed provider status;
- last polling timestamp;
- terminal result or normalized error;
- the user, workspace, or workflow that owns the task;
- an idempotency or deduplication key generated by your application.
A practical local state machine might be:
created -> submitting -> accepted -> running -> succeeded
| | -> failed
| -> reconciliation_required
-> submission_unknown
The provider may expose fewer states, such as pending, running, succeeded, and failed. Your application still needs the extra local states. They distinguish “the provider rejected this request” from “our process lost the response and does not know whether a task was created.” Those situations require different recovery actions.
¶ Acceptance is not completion
The most important rule is simple: receiving a task ID confirms acceptance, not success.
Do not grant a downloadable asset, mark a workflow complete, or submit dependent work until the original task reaches a terminal state. Conversely, do not label a task failed only because your web request, queue worker, or reverse proxy stopped waiting. A client-side timeout ends the wait, not necessarily the provider’s work.
¶ 3. Explicit polling with the Ace Data Cloud SDK
The official SDKs expose asynchronous work through TaskHandle. The documented interface includes a one-time state retrieval method, a completion check, a bounded wait method, and the most recently stored result.
The following Python pattern submits a task without blocking and then waits with explicit limits:
import os
import time
from acedatacloud import AceDataCloud
client = AceDataCloud(
api_token=os.environ["ACEDATACLOUD_API_TOKEN"],
max_retries=2,
)
handle = client.images.generate(
provider="midjourney",
prompt="a precision-machined dark slate module on an off-white workbench",
wait=False,
)
print("task_id", handle.id)
started = time.time()
try:
result = handle.wait(
poll_interval=3.0,
max_wait=180.0,
)
except TimeoutError:
print("wait window expired; preserve task_id and reconcile later")
raise
payload = result.get("response", result)
print("elapsed_s", round(time.time() - started, 1))
print("status", payload.get("status"))
The TypeScript equivalent uses milliseconds rather than seconds:
import { AceDataCloud } from '@acedatacloud/sdk';
const client = new AceDataCloud({ maxRetries: 2 });
const handle: any = await client.images.generate({
provider: 'midjourney',
prompt: 'a precision-machined dark slate module on an off-white workbench',
wait: false,
});
console.log('task_id', handle.id);
try {
const result: any = await handle.wait({
pollInterval: 3_000,
maxWait: 180_000,
});
const payload = result.response ?? result;
console.log('status', payload.status);
} catch (error) {
console.error('wait window expired; preserve the task ID for recovery');
throw error;
}
This unit difference is easy to miss during a language migration. Translating pollInterval: 3000 directly to poll_interval=3000 in Python creates a 50-minute interval between polls.
¶ 4. Polling is a scheduler, not a tight loop
A polling loop should protect both your system and the provider.
¶ Use a bounded interval
Poll quickly enough to meet the product’s latency requirements, but not so quickly that status requests dominate traffic. A three-second interval can be reasonable for an interactive job that normally finishes in tens of seconds. Longer batch jobs may tolerate a larger interval or an increasing schedule.
¶ Add jitter in distributed systems
If thousands of workers submit jobs at the same time and poll on the same fixed interval, they can create synchronized traffic spikes. Add a small randomized delay around your baseline interval when you implement polling outside the SDK helper.
¶ Set a wait window, not a completion deadline
max_wait should describe how long this process is willing to wait now. It should not automatically determine whether the provider task is dead. When the window expires:
- persist the task ID and latest known state;
- release the worker or return a non-terminal status to the caller;
- schedule later reconciliation;
- continue retrieving the original task rather than immediately resubmitting it.
This distinction prevents expensive duplicate generations.
¶ Stop only on documented terminal states
The SDK’s documented wait logic expects succeeded or failed. Some APIs may use a different schema. If an endpoint does not expose the expected status field, use one-time retrieval and parse the endpoint’s documented response rather than allowing a generic waiter to run until timeout.
¶ 5. Separate transport retries from task retries
“Retry” is overloaded in AI integrations.
¶ Transport retry
A transport retry repeats an HTTP request after a transient network or server failure. The Ace Data Cloud SDK documentation says the clients retry HTTP 408, 409, 429, 5xx responses, and network-layer failures with exponential backoff by default. Authentication and validation failures are not in that retry group.
This behavior is appropriate for safe retrieval operations. Submission is more complicated because a lost response can occur after the provider accepted the task.
¶ Task resubmission
A task resubmission creates new billable work. It must not be the automatic answer to every timeout, disconnected socket, or 5xx response.
Before creating a replacement, ask:
- Did the submission response include a task or trace ID?
- Can the original task be retrieved by that ID?
- Does the endpoint document idempotency behavior?
- Can your application locate an earlier task using its own deduplication record?
- Was the error definitely returned before acceptance?
If acceptance is uncertain, move the local job to submission_unknown or reconciliation_required. That state is operationally inconvenient, but it is safer than silently charging for duplicate work.
¶ 6. Build recovery around the original task ID
A production workflow should survive browser closure, worker restart, and proxy timeout.
The simplest architecture has four components:
- Submission API: validates the request, creates a local job record, and submits provider work.
- Job store: persists task IDs, trace IDs, ownership, and state.
- Reconciliation worker: retrieves non-terminal tasks and updates local state.
- Status API or event layer: lets the frontend obtain current state without holding the original request open.
A database record can be more valuable than an elaborate queue if it preserves the provider task ID reliably. The queue controls execution; the database records truth across retries and restarts.
When the provider returns a final asset URL, persist the complete terminal response needed by your product. Do not assume an external URL will remain your only system of record. If your retention or compliance requirements demand a copy, transfer the asset through an approved storage workflow after verifying its content type and size.
¶ 7. Handle failure as data
Avoid collapsing every unsuccessful outcome into a string called error.
Normalize at least these categories:
- authentication or permission failure;
- invalid request or unsupported parameter;
- account balance or spending-limit failure;
- moderation rejection;
- provider terminal failure;
- rate limit or concurrency limit;
- client wait timeout with provider task still non-terminal;
- unknown submission outcome;
- network failure during retrieval.
This classification determines whether the user should edit input, wait, contact an administrator, or let the system reconcile automatically.
The SDK exposes typed error classes for common HTTP failure groups. Use those classes in business logic instead of matching human-readable messages. Preserve the provider’s task ID and the platform trace ID in structured logs, but never log API keys, wallet secrets, complete private prompts, or sensitive generated content by default.
¶ 8. Streaming is not asynchronous task polling
SSE chat streaming and task polling solve different problems.
A streaming response has one request and many frames. Once frames have reached the client, replaying the request can duplicate visible output or tool effects. The current SDK documentation therefore says streaming requests are not automatically retried after output begins.
An asynchronous task has multiple requests: create, then retrieve. A retrieval failure does not imply creation failed, and a polling timeout does not cancel the task.
This distinction should appear in your product API. For example:
POST /generations -> creates local job and provider task
GET /generations/{id} -> returns durable current state
GET /chat/stream -> streams one conversational response
Do not hide both behaviors behind a single endpoint whose timeout semantics are impossible for clients to interpret.
¶ 9. Concurrency and spending boundaries
Long-running work can outlive the request that initiated it, so spending controls must be applied before submission and observed after completion.
Useful controls include:
- per-user and per-workspace concurrent-job limits;
- a maximum number of accepted but non-terminal tasks;
- credential-level usage limits;
- provider or model allowlists;
- an explicit queue for expensive operations;
- alerts for tasks that remain non-terminal beyond an operational threshold.
Ace Data Cloud applications and credentials can be separated by service and constrained with usage limits and allowed APIs. Those controls complement application-level quotas; they do not replace ownership checks and job limits in your product.
The platform documentation also notes a specific trial-account concurrency boundary: accounts without a qualifying paid recharge or administrator credit addition may run only one billable request at a time. Developers should consult the current account state and documentation rather than attempting to work around limits with additional keys.
¶ 10. A practical production checklist
Before shipping a task-based AI feature, verify that:
- the endpoint is actually asynchronous;
- submission returns and stores a durable task ID;
- polling intervals and units are correct for the SDK language;
- every wait has a finite local window;
- wait timeout is not treated as provider failure;
- transport retries are distinguished from task resubmission;
- the original task is reconciled after disconnects;
- terminal success and terminal failure are both persisted;
- typed errors drive user-facing recovery guidance;
- logs include task and trace IDs without secrets;
- concurrency and spending limits are enforced before submission;
- synchronous providers are not forced through a task poller;
- integration tests cover worker restart and lost submission responses.
¶ Conclusion
Reliable AI media generation is mostly a state-management problem. The model may be the most sophisticated component, but production incidents usually occur at ordinary boundaries: a response is lost, a worker restarts, a timeout is misclassified, or a retry creates a second task.
Use the provider task ID as a durable external reference. Keep a separate local state machine. Bound every wait. Retry retrieval safely, and resubmit only after reconciliation shows that new work is necessary.
Ace Data Cloud’s TaskHandle reduces the mechanics of polling in Python and TypeScript, but the application still owns job persistence, user authorization, deduplication, and recovery policy. That division of responsibility is what makes a long-running AI workflow understandable in production.
¶ FAQ
¶ Does a TimeoutError mean the generation failed?
No. It means the local wait window ended. Preserve the task ID and retrieve the original task again unless the provider has already returned a terminal failure.
¶ Should every image-generation request use wait=True?
No. Some image providers return final results synchronously. Use task polling only when the current endpoint documentation exposes a task creation and retrieval flow.
¶ Can I retry a failed task submission automatically?
Only when you can establish that no task was accepted, or when the endpoint provides documented idempotency that makes the retry safe. Otherwise reconcile the original request first.
¶ Why do Python and TypeScript examples use different timeout numbers?
The documented TaskHandle units differ: Python uses seconds, while TypeScript uses milliseconds.

