How to Integrate Async 3D Generation Into a Backend
Follow a real TRELLIS job from HTTP 202 to a verified GLB. See the polling trace, a live 404, restart behavior and runnable Python.

A product backend should be able to restart halfway through a 3D generation job and still retrieve the original result. On November 14, 2026, our TRELLIS request returned HTTP 202 with an ID. Four later status requests reported running, and the fifth returned a completed result with a GLB URL. We saved the file, restarted retrieval using only the recorded ID, and got the same bytes. This walkthrough uses that live HTTP trace to show where to persist state, what to retry and when a generated file is ready for downstream review.
Key takeaway
- One POST returned 202 and pending. Five GET requests used the same ID. Completion was first observed 30.07 seconds after the submit response in this run. The polling interval limits the precision of that observation.
- The output downloaded with HTTP 200 and contained 1,820,056 bytes, 17,500 triangles and one embedded image. It rendered in Three.js and reported zero validator errors and warnings.
- A GET for a deliberately unknown ID returned HTTP 404 and
prediction not found. The saved real ID still returned completed and could download the same GLB again. - Persist the provider ID as soon as it arrives. A transient lookup failure is a reason to retry the GET with that ID. An unresolved submission calls for checking what happened before issuing another POST.
1. Read the contract of the selected route
SandBase documents POST /v1/run for capability requests and GET /v1/run/{id} for asynchronous results. Capability fields live beside model in the request. Use the operation’s own schema. The TRELLIS route used an image URL, seed 73 and texture size 1024. Other routes can require different fields or return a different output shape. This tutorial uses the HTTP API. Its fields come from that interface. SandBase run API · TRELLIS image-to-3D

The time column starts at receipt of the submit response. Each row represents a real HTTP response. The server may have finished between polls.
| Request | HTTP | Observed status | Seconds after submit response | Output items |
|---|---|---|---|---|
| Submit | 202 | pending | 0.00 | 0 |
| Poll 1 | 200 | running | 6.01 | 0 |
| Poll 2 | 200 | running | 12.05 | 0 |
| Poll 3 | 200 | running | 18.05 | 0 |
| Poll 4 | 200 | running | 24.08 | 0 |
| Poll 5 | 200 | completed | 30.07 | 1 |
A completed response for this run contained an outputs array with one item containing content_type and url. The initial response contained id, model and status. A status lookup with HTTP 200 can still say running. Use the body state to decide whether to schedule another lookup. Treat elapsed time in this trace as a single client observation, with no throughput or model speed conclusion.
2. Keep an application job and a provider run ID
For a product backend, create an application job before submitting. It can store the owner’s ID, model route, input reference, current state, provider ID when available, and the verified artifact location. Authorize the owner before revealing output or status. Keep the provider credential server-side and keep temporary URLs and keys out of logs. The example uses a local JSON record to demonstrate a single worker. A deployed service can use one database row and a worker lease or transaction to serialize job ownership.
The awkward state is submitting. If the HTTP request times out or the process exits after the server accepts it, the provider may already be working even though the application has no run ID. The example creates an exclusive local marker before the network call and leaves that marker on an unresolved submission. A real system should reconcile the attempt with its request logs or provider records. Treat a fresh application job ID as an application guard. Server-side idempotency, when available, needs its own documented contract.
3. Run the sample worker
Create an isolated Python environment and use a server-side SandBase key from your secret store. The example uses Python 3 and Requests. The test reused the route’s public example input. Use a URL the selected route can access.
python3 -m venv .venv
. .venv/bin/activate
python3 -m pip install requestsSave the following as run_job.py. The code separates submission and polling so a worker can restart with the same job record. It bounds poll attempts, handles transient GET errors and checks the downloaded file’s size and GLB header before saving it. Keep the job and output paths private to the worker. Run a single worker per job in this file-based example.
import argparse
import hashlib
import json
import os
from pathlib import Path
import struct
import time
from urllib.parse import quote, urlparse
import requests
BASE = "https://api.sandbase.ai/v1/run"
WAITING = {"pending", "running"}
TERMINAL_FAILURE = {"failed", "timeout", "cancelled"}
MAX_BYTES = 50_000_000
def save(path, value):
temp = path.with_suffix(".tmp")
temp.write_text(json.dumps(value, indent=2) + "\n")
temp.replace(path)
def download(url, destination):
if urlparse(url).scheme != "https":
raise ValueError("Expected an HTTPS output URL")
with requests.get(url, timeout=(5, 30), stream=True) as response:
response.raise_for_status()
data = bytearray()
for chunk in response.iter_content(65536):
data.extend(chunk)
if len(data) > MAX_BYTES:
raise ValueError("Output exceeds the download cap")
if len(data) < 20 or data[:4] != b"glTF":
raise ValueError("Expected a GLB container")
version, declared_size = struct.unpack_from("<II", data, 4)
if version != 2 or declared_size != len(data):
raise ValueError("Unexpected GLB version or length")
temp = destination.with_suffix(".partial")
temp.write_bytes(data)
temp.replace(destination)
return {"bytes": len(data), "sha256": hashlib.sha256(data).hexdigest()}
def submit(args, headers):
if not args.image:
raise SystemExit("--image is required for submit")
try:
with args.job.open("x") as job:
json.dump({"state": "submitting"}, job)
except FileExistsError:
raise SystemExit("Job already exists. Use poll with its saved run ID.")
try:
response = requests.post(
BASE, headers=headers, timeout=(5, 20),
json={"model": "trellis/trellis", "image": args.image,
"seed": 73, "texture_size": 1024},
)
response.raise_for_status()
body = response.json()
run_id = body["id"]
if not isinstance(run_id, str) or not run_id:
raise ValueError("Invalid provider run ID")
except (requests.RequestException, ValueError, KeyError) as error:
raise SystemExit(f"Submission unresolved. Keep the marker and investigate: {error}")
save(args.job, {"state": body["status"], "run_id": run_id})
print("Recorded", run_id, body["status"])
def poll(args, headers):
job = json.loads(args.job.read_text())
if not job.get("run_id"):
raise SystemExit("No run ID saved. Investigate the submission marker.")
url = f'{BASE}/{quote(job["run_id"], safe="")}'
for _ in range(24):
try:
response = requests.get(url, headers=headers, timeout=(5, 15))
except (requests.Timeout, requests.ConnectionError):
time.sleep(5)
continue
if response.status_code == 429 or response.status_code >= 500:
time.sleep(5)
continue
if response.status_code == 404:
raise SystemExit("Run lookup returned 404. Check the saved ID and credential.")
response.raise_for_status()
body = response.json()
state = body["status"]
save(args.job, {**job, "state": state})
if state == "completed":
output = next((item for item in body.get("outputs", [])
if item.get("content_type") == "model/gltf-binary"
and item.get("url")), None)
if output is None:
raise SystemExit("Completed run has no GLB output")
receipt = download(output["url"], args.output)
save(args.job, {**job, "state": "downloaded", **receipt})
print(json.dumps(receipt))
return
if state in TERMINAL_FAILURE:
raise SystemExit(f"Run ended in {state}: {body.get('error', '')}")
if state not in WAITING:
raise SystemExit(f"Unknown run state: {state}")
time.sleep(5)
raise SystemExit("Polling window ended. Resume polling the saved run ID.")
def main():
parser = argparse.ArgumentParser()
parser.add_argument("action", choices=("submit", "poll"))
parser.add_argument("--job", type=Path, default=Path("job.json"))
parser.add_argument("--image")
parser.add_argument("--output", type=Path, default=Path("asset.glb"))
args = parser.parse_args()
headers = {"Authorization": "Bearer " + os.environ["SANDBASE_API_KEY"]}
if args.action == "submit":
submit(args, headers)
else:
poll(args, headers)
if __name__ == "__main__":
main()Submit once. This command creates a real generation request and can incur a charge. It uses the same request fields as the observed trace.
python3 run_job.py submit --job character-job.json \
--image https://static.sandbase.ai/examples/trellis/trellis/input_image_0.pngOn a successful asynchronous submit, the job record contains the returned provider ID and pending or running state. The live trace was captured with a separate logging client. We exercised the worker’s submit guard and ID persistence with a mocked response, and used the real saved ID to run the poll and download path.
python3 run_job.py poll --job character-job.json --output asset.glbAfter a successful download, the local record has state downloaded, byte count and SHA-256. The downloaded state belongs to the application. The provider returned completed. Persist the completed state before fetching so a failed download can be retried with another lookup on the same ID. If a download was already accepted, the scheduler can skip it. The demonstration can fetch it again to prove byte identity.
4. Decide what to retry

The HTTP 200 and 404 cards come from live GET requests. The right card describes the local duplicate-submit check.
| Event | Action in the sample |
|---|---|
| Status remains pending or running | Wait and request the same ID again |
| GET times out, cannot connect, returns 429 or returns 5xx | Retry that GET within the bounded window |
| GET returns 404 | Stop and inspect the saved ID and credential |
| Body reports failed, timeout or cancelled | Persist that provider state and end the worker attempt |
| Completed download fails | Resume the same ID and retry retrieval |
| Submit result is unresolved | Preserve the submission marker and investigate |
In a local test with mocked responses, a 429 followed by a failed terminal response produced two GETs using the same ID and zero POSTs. The failed state was saved. In the live check, the unknown ID returned 404 and a short error, with no run state or outputs. That distinguishes a lookup error from a provider job reporting failed. If you need longer waits in production, store the next check time and use queue scheduling with backoff. The sample sleeps in one process for clarity.
5. Check the downloaded bytes before using the asset

The render is from the downloaded GLB. The displayed SHA-256 matched the second retrieval made after restoring the saved run ID.
The live download used the returned URL without sending the API authorization header to the storage host. The response came back as model/gltf-binary. The file began with the glTF signature, had version 2 and declared the same length as the received bytes. It contained 17,500 stored triangles and one image. A separate Khronos validator run reported zero errors and warnings. The Three.js viewer opened the file and rendered it at three angles. Those checks verify this artifact. A delivery project still needs to inspect whether the asset contains its required parts. Automated GLB intake
Run these commands to inspect the saved file and local receipt. The exact byte count below applies to the observed download. Another generation can produce a different file.
wc -c asset.glb
python3 -m json.tool character-job.jsonIf you save outputs to your own storage, update the application job only after confirming that the uploaded bytes match the local artifact. Store the hash with the destination, and use the temporary provider URL only during retrieval. If output URLs expire before you can retrieve them, inspect the documented behavior of the selected operation and record an explicit delivery failure if the artifact cannot be recovered.
Keep failures visible to the caller
The frontend should be able to distinguish a request that was accepted, a file that is waiting to download, and a verified asset it can open. Returning the provider status verbatim will merge some of those states. Map them to your application states and persist the last meaningful error and its timestamp. If a lookup is temporarily unavailable, retain the earlier confirmed state and display when the next check is due.
For several jobs at once, see batch 3D API submissions, retries and cost records.
FAQ
Is the observed 30.07 seconds the exact generation time?
It is the time between the client receiving its 202 response and observing completed at a poll. The provider finished at some point before that completed response. A latency report for a product should separately measure submission, observed completion, download and usable render.
Does this use webhooks for 3D jobs?
This integration uses polling. SandBase documents webhook support for eligible asynchronous image, video and audio tasks. Consult the selected route before adding callback assumptions to a 3D workflow. SandBase webhook guidance
What should happen after a worker restart?
If a job has a provider ID, resume with a status lookup. If a verified artifact already exists, continue from the saved application state. If all you have is the submission marker, investigate the original attempt before deciding whether to issue a new request.
Found this useful? Share it