Remove image backgrounds in Python with asyncio (2027)
Bria.ai

Updated 2026-12-01
TL;DR
Direct answer: to remove image backgrounds in Python at scale, use
BriaAsyncClientfrom thebria-clientSDK with RMBG 3.0, submit jobs on a paced schedule and cap how many wait at once.Limit: the Bria API allows 60 requests per minute per endpoint on Pay-as-you-go, 10 on Free and 1,000 on Enterprise. Status polls count toward it.
Pacing: at about 3 requests per image (one submit plus two polls), 60 requests per minute is about 20 images per minute. This is the author's arithmetic from the published limits, not a measured rate.
Webhooks: with a
webhook_urleach image costs 1 request, which is about 60 images per minute on Pay-as-you-go.Cost: $0.018 per image for RMBG 3.0 (checked 2026-11-29), so 1,000 images cost $18.
Tested: the control flow of the script below ran against a stub client. The webhook snippets and the receiver were not run at all, and nothing ran against the live API.
You can remove image backgrounds in Python with a few lines, but a loop that waits on each image does not scale. This guide shows an asyncio script for the Bria API that submits images at a paced rate and caps jobs in flight. It also shows when a webhook beats polling. If you only need one image or a single folder, start with the basic Python guide.
Bria wrote this guide. Any benchmark figure is from Bria's own benchmark. The async script is the author's composition from documented SDK methods (submit, poll, Image(...).as_bria_api_input, a semaphore and to_thread). The webhook receiver follows the example in the Bria docs with a dedupe set added. The pacing numbers are arithmetic from the published limits.
How do I remove image backgrounds in Python at scale?
Submit every image as an async job, pace the submits under your plan's limit and collect results with polling or a webhook. The Bria API processes all v2 requests asynchronously by default: a submit returns a request_id and a status_url, and the result follows later (async requests, checked 2026-12-02).
Client:
BriaAsyncClientis meant for "asyncio applications and high-concurrency pipelines" (Python SDK docs).Model: set
"model": "RMBG3". Bria's benchmark ranked RMBG 3.0 first of 6 models, with an average rank of 1.51 across 234 hard images (benchmark write-up).Install:
pip install bria-client, then exportBRIA_API_TOKEN. The package needs Python 3.10 or newer and is MIT licensed (bria-client on GitHub).
When does asyncio beat a plain loop for background removal?
Asyncio wins when most of the time per image is spent waiting, because one process can hold many jobs open at once. A sequential loop idles during every wait on every file, so the default async mode with a semaphore keeps many jobs in flight.
A loop with
client.run()holds one image at a time.Submit-then-poll in an async client overlaps the waits, so the limit becomes your plan's rate, not the latency.
The SDK page shows the same idea: submit everything first, then poll.
For fewer than about 20 images a plain loop is simpler and fast enough.
How many requests does one image use?
One image uses 1 submit request plus every status poll, so polling can triple your request count. The rate-limit page says status calls "count toward your rate limit" (rate limits and errors, checked 2026-12-02). The table converts the published limits into images per minute. It assumes 3 requests per image on the polling route and 1 on the webhook route.
Plan: Free; Limit per minute, per endpoint: 10; Images per minute, polling (3 requests each): about 3; Images per minute, webhook (1 request each): 10
Plan: Pay-as-you-go; Limit per minute, per endpoint: 60; Images per minute, polling (3 requests each): 20; Images per minute, webhook (1 request each): 60
Plan: Enterprise; Limit per minute, per endpoint: 1,000; Images per minute, polling (3 requests each): about 333; Images per minute, webhook (1 request each): 1,000
Source: Bria rate limits page for the limits, the per-image request counts are an assumption to measure on your own jobs. The docs do not say whether status calls share the submit endpoint's bucket, so the table plans for the worst case.
Time for 1,000 images on Pay-as-you-go: about 50 minutes by polling, about 17 minutes by webhook.
Cost for 1,000 images at $0.018: $18.
How do I write the async client?
Create one `BriaAsyncClient`, start a task per image and let a semaphore cap the jobs in flight. The asyncio.Semaphore class limits concurrent access (Python asyncio docs). The script below uses only methods that the SDK page documents: submit, poll and Image(...).as_bria_api_input.
import asyncio
import urllib.request
from pathlib import Path
from bria_client import BriaAsyncClient
from bria_client.toolkit import BriaException, Image
RATE_LIMIT_PER_MIN = 60 # Pay-as-you-go plan, per endpoint
REQUESTS_PER_IMAGE = 3 # 1 submit plus about 2 status polls, measure and adjust
SUBMIT_GAP = 60 * REQUESTS_PER_IMAGE / RATE_LIMIT_PER_MIN # seconds between submits
MAX_IN_FLIGHT = 8 # cap on jobs waiting for a result
async def cut_out(client, gate, path: Path, out_dir: Path):
async with gate:
job = await client.submit(
endpoint="image/edit/remove_background",
payload={"image": Image(str(path)).as_bria_api_input, "model": "RMBG3"},
raise_for_status=True,
)
done = await client.poll(job, interval=5, timeout=120)
target = out_dir / f"{path.stem}.png"
await asyncio.to_thread(urllib.request.urlretrieve, done.result.image_url, target)
async def main(folder: str, out: str):
out_dir = Path(out)
out_dir.mkdir(exist_ok=True)
gate = asyncio.Semaphore(MAX_IN_FLIGHT)
paths = sorted(Path(folder).glob("*.jpg"))
tasks = []
async with BriaAsyncClient() as client:
for path in paths:
tasks.append(asyncio.create_task(cut_out(client, gate, path, out_dir)))
await asyncio.sleep(SUBMIT_GAP) # pace submits under the rate limit
results = await asyncio.gather(*tasks, return_exceptions=True)
for path, result in zip(paths, results):
if isinstance(result, (BriaException, TimeoutError)):
print("failed:", path.name, result)
elif isinstance(result, Exception):
raise result
asyncio.run(main("photos", "cutouts"))submitdoes not raise on API errors such as 429, 415 or 422 unless you passraise_for_status=True.pollraises by default.asyncio.to_threadkeeps the blocking download off the event loop.return_exceptions=Truelets one failed image leave the rest running.The poll interval is 5 seconds. The docs suggest 1 to 2 seconds for image endpoints, so 5 trades a little latency for fewer requests.
Result URLs are temporary, so the script downloads each file as soon as the job completes.
How do I pace submits under the rate limit?
Wait `60 x requests per image / limit` seconds between submits, and cap in-flight jobs with a semaphore. For Pay-as-you-go the formula gives 60 x 3 / 60 = 3 seconds. The semaphore does not enforce the rate. It only stops a slow API from piling up hundreds of open jobs.
Free plan: 60 x 3 / 10 = 18 seconds between submits.
Enterprise at 1,000 per minute: about 0.18 seconds between submits.
Raise
intervalinpollif your measured polls per image are above 2. Lower it to shorten each job.Count real requests for one batch of 20 images and set
REQUESTS_PER_IMAGEto the observed average.
What happens on errors, timeouts and 429s?
Catch `BriaException` and `TimeoutError` per image, and retry only a failed submission, never a job that is still running. The async page states that submissions are not idempotent: retrying a POST creates a new job, and the SDKs never retry run or submit for this reason (async requests).
Status: 415; Meaning in the docs: Input type or color mode not supported; What to do: Convert to JPEG, PNG or WEBP
Status: 422; Meaning in the docs: Moderation failed, or an async-only option with
sync: true; What to do: Fix the input or the payload, do not retry blindlyStatus: 429; Meaning in the docs: Rate limit exceeded; What to do: Back off with jitter, honor
Retry-After, lower concurrencyStatus: 5xx; Meaning in the docs: Problem on Bria's side; What to do: Retry with backoff, check status.bria.ai if it persists
Source: Bria rate limits and errors page, checked 2026-12-02.
Status polls retry 429, 502, 503 and 504 by themselves, 3 attempts with exponential backoff.
Tune that with
BriaAsyncClient(retry=...), which takes anhttpx_retries.Retry.Write failed file names to a list so a second pass handles only those.
How do webhooks cut the request count?
Pass `webhook_url` to `submit` and Bria POSTs the result to your server, so each image costs 1 request and no polls. The documentation recommends webhooks for production pipelines, queues and serverless backends (webhooks). webhook_url is a keyword argument of submit, not part of the payload.
job = await client.submit(
endpoint="image/edit/remove_background",
payload={"image": Image(str(path)).as_bria_api_input, "model": "RMBG3"},
webhook_url="https://your-app.example.com/api/bria/webhook",
raise_for_status=True,
)Bria sends three headers:
Bria-Webhook-Id,Bria-Webhook-TimestampandBria-Webhook-Signature.Answer with any 2xx within 10 seconds. Bria retries up to 5 attempts over 45 minutes if you do not.
Use
Bria-Webhook-Idas a dedupe key, because duplicates are possible.
How do I receive and verify a webhook in Python?
Verify the signature with `verify_webhook_signature`, answer at once and do the work in a background task. The receiver below follows the FastAPI example in the Bria docs and uses FastAPI's `BackgroundTasks`.
import json
import os
from bria_client.toolkit import verify_webhook_signature
from fastapi import BackgroundTasks, FastAPI, Header, HTTPException, Request
app = FastAPI()
seen = set() # use Redis or a database in production
@app.post("/api/bria/webhook")
async def receive(
request: Request,
background: BackgroundTasks,
bria_webhook_id: str = Header(...),
bria_webhook_timestamp: str = Header(...),
bria_webhook_signature: str = Header(...),
):
body = await request.body()
if not verify_webhook_signature(
payload=body,
webhook_id=bria_webhook_id,
timestamp=bria_webhook_timestamp,
signature_header=bria_webhook_signature,
api_token=os.environ["BRIA_API_TOKEN"],
):
raise HTTPException(status_code=401, detail="Invalid webhook signature")
if bria_webhook_id not in seen:
seen.add(bria_webhook_id)
background.add_task(save, json.loads(body))
return {"ok": True}
async def save(data: dict):
if data["status"] == "COMPLETED":
... # download data["result"]["image_url"] now, it is temporary
elif data["status"] == "ERROR":
... # log data["error"]The signed message is
{webhook_id}.{timestamp}.{raw_body}, so verify the raw bytes before parsing JSON.Your server needs a public HTTPS address. A queue or serverless function works the same way.
How do I test the script before a big run?
Run 20 images, count the requests, and check the cutouts before you send thousands. A stub test confirms the control flow without spending credits. It does not replace a live run.
Replace
BriaAsyncClientwith a small fake class whosesubmitandpollare coroutines, and runmainon three tiny JPEG files.Then run 20 real images on the Free plan, where 100 free generations are included (checked 2026-12-02).
Log
request_idfor every job so a failure can be traced.Open ten cutouts on a dark and a light background and look at hair, fur and edges.
Set
SUBMIT_GAPfrom the measured requests per image, not from the assumption.
Which route should you choose?
Choose the paced asyncio script if you have hundreds to thousands of images, run it from one machine and can wait about 3 seconds per image on Pay-as-you-go.
Choose webhooks if your code runs as a service, you need to approach the plan limit and you can host a public endpoint.
Choose a plain `client.run()` loop if you have under about 20 images and want the shortest code.
Check the plan first if you need more than 60 requests per minute. Enterprise limits are customizable per organization, so ask Bria's sales team.





