Async deep dive
This page is for the practitioner who is past "what's the async method called" and
wants the right pattern for their workload. The SDK exposes *_async siblings on
every major method; this page is about using them well.
Quick orientation
import asyncio
import sasvi
async def main() -> None:
async with sasvi.SVIClient(base_url="https://viya.example.com", auth=auth) as client:
await client.verify_connection_async()
# Read paths
alert = await client.alerts.get_async(alert_id="alert-1")
doc = await client.documents.get_async(entity_type_name="alerts", document_id="alert-1")
tasks = await client.workflows.tasks.list_async(limit=20)
# Write paths
instance = await client.workflows.start_async(
workflow_name="triage",
document_ref=doc,
)
await alert.update_fields_async(queue_id="manual-review")
await alert.disposition_async(
disposition_id="...",
resolution_code="PRODUCTIVE",
)
# Search fluent builder
page = await client.search.text("invoice").summary_async(limit=50)
total = await client.search.text("invoice").count_async()
asyncio.run(main())
Conventions
The SDK uses one async naming convention everywhere, the _async suffix:
| Surface | Convention | Example |
|---|---|---|
| Service methods | _async suffix | client.alerts.list_async(...) |
| Bound-object methods | _async suffix | alert.refresh_async(), task.complete_async() |
Search fluent builder terminals | _async suffix | search.count_async(), search.summary_async() |
| Context managers | Python convention | async with, close_async() |
Every async method carries the _async suffix, so there is a single rule to
learn and it matches the rest of the Python async ecosystem (httpx2, asyncpg,
aiohttp).
Surfaces that are intentionally sync-only
Every public method that sends a request has an _async twin, with these exceptions:
- insight-cell editing (
insight.cells.*on a sheet fromdocument.insights.get(...)) and theInsightCell.*_from_documentsbuilders when given boundDocumenthandles; - workspace node, relationship and layout editing (
workspace.nodes.*,workspace.relationships.*andworkspace.layout.*on a workspace fromdocument.workspaces.get(...)); - local reads that send nothing:
client.admin.entity_types.hydrate,client.admin.config.load_bundleandload_archive.
Each editing call is one locked whole-document write, built from many small builder methods.
Run one from async code with asyncio.to_thread, for example
await asyncio.to_thread(cells.add_table, ...).
The table below lists each public method that does I/O and is sync-only, on the objects an
_async call returns. A test renders it from a hand-kept list of those objects, so a listed
object cannot drift from the code, and a new return type must be added to the list
(tests/test_async_inventory.py). An empty table means every one of those objects has a full set
of twins.
| Object | Sync-only methods |
|---|
A few async twins read a cache that the first call fills: a disposition option's
request_async, requirements_async and its option helpers make one GET and answer later calls
from the cached request, and ReferenceListRecord.item_async, to_lookup_async and
validate_values_async read the list once when the record has not loaded its items.
The admin managers under client.admin follow the same rule. Where a manager has a sync
method that sends a request, it has the _async twin too. Check with dir() if you are unsure.
When to use async
| Scenario | Use sync? | Use async? |
|---|---|---|
| One-off script, notebook (no async cells) | ✅ | Possible but unnecessary |
| Notebook with async cells (Jupyter, IPython) | Works; blocks the event loop briefly | ✅ |
| FastAPI / Starlette handler | ❌ blocks the worker | ✅ |
asyncio-based ingest worker | ❌ | ✅ |
| Single API call with no concurrency | ✅ | OK but no win |
| Fan-out over many ids (search hydration, ingest) | Possible but slow | ✅ massive throughput win |
| Mixed I/O + CPU pipeline | Bridges fine | ✅ keeps event loop free for I/O |
The sync surface remains the default for scripts, notebooks (outside async cells),
and one-off operations. Mixing sync and async on the same SVIClient instance is
supported, because the generated client manages an internal pair of httpx2.Client
and httpx2.AsyncClient.
Sync vs native-async vs thread-bridged async
Patterns
Bounded concurrency
import asyncio
import sasvi
sem = asyncio.Semaphore(20)
async def fetch_one(client, alert_id):
async with sem:
return await client.alerts.get_async(alert_id=alert_id)
async def main():
async with sasvi.SVIClient.from_env() as client:
results = await asyncio.gather(
*(fetch_one(client, aid) for aid in alert_ids),
return_exceptions=True,
)
return results
asyncio.Semaphore caps the number of outstanding requests at any one time.
return_exceptions=True lets one failure surface without canceling the whole batch.
See the async fanout recipe.
Streaming generator
async def stream_hits():
async for hit in client.search.text("foo").iter_async(page_size=200):
yield hit
iter_async is a real async generator. async for cancellation propagates to the
in-flight page request, so closing the consumer also stops the producer.
Per-call deadline as SLA
client = sasvi.SVIClient(
auth=auth,
config=sasvi.SVIConfig(
base_url=base_url,
max_retries=3,
request_deadline_seconds=8.0,
),
)
When the budget runs out the call raises DeadlineExceededError, a
TransientError subclass.
Async is a hard wall-clock cap: the attempt is cancelled when the budget runs
out, whatever phase it is in. Sync cannot cancel a blocking wait. It caps every
connect, pool, write and read wait at the budget left when the attempt starts,
reads the body chunk by chunk and checks the clock between chunks, and starts
no retry after the deadline. A body that keeps trickling bytes stops at the
first chunk that arrives after the deadline, so the read overshoots by at most
one read wait. Waits in different phases are capped one by one, so a call that
stalls in several phases in turn can still run longer than the budget. A
per-call timeout= cannot extend the budget. See Performance guide for retry-policy tuning.
Cooperative cancellation
import asyncio
async def with_timeout(coro, seconds):
try:
return await asyncio.wait_for(coro, timeout=seconds)
except asyncio.TimeoutError:
return None
results = await asyncio.gather(
*(with_timeout(client.alerts.get_async(alert_id=a), seconds=2.0) for a in alert_ids)
)
asyncio.wait_for cancels the underlying task on timeout. For a natively async
method the SDK propagates that cancellation through httpx2's async client, and
the connection is returned to the pool.
The handful of methods listed under Thread-bridged async is not free run their sync implementation on a worker thread. Python cannot cancel a running thread, so cancelling the coroutine abandons the result, not the work: the request has been sent and will complete.
Cancelling UsernamePasswordTokenProvider.get_token_async or
AuthorizationCodeTokenProvider.get_token_async leaves a token acquisition
running, and the authorization-code flow may have a browser window open.
Cancelling AttachmentsManager.download_to_async during its file write lets
that write finish; each step is shielded, so no half-written file is left.
A write is different from a read even when it is natively async: once a create, update or disposition has been sent, cancelling the task leaves its outcome unknown. Read the record back before retrying, because creates are not idempotent.
Long-running poll with asyncio.sleep
AlertingEvent.alert_async polls for the final alert and uses asyncio.sleep
internally:
events = await client.alerts.ingest_async(layout="flat", body=payload)
alert = await events[0].alert_async(timeout=30.0, poll_interval=0.5)
The event loop stays free between polls; one task can do this without blocking the worker.
Pitfalls
Blocking sync calls inside async def
# WRONG. alerts.get() is sync; this blocks the event loop.
async def handler(client, alert_id):
return client.alerts.get(alert_id=alert_id)
# RIGHT. Use the async sibling.
async def handler(client, alert_id):
return await client.alerts.get_async(alert_id=alert_id)
Forgetting async with
# WRONG. The async client is never closed; connections leak.
client = sasvi.SVIClient.from_env()
result = await client.alerts.get_async(alert_id="...")
# RIGHT. The async context manager closes both sync and async clients.
async with sasvi.SVIClient.from_env() as client:
result = await client.alerts.get_async(alert_id="...")
One client per event loop
The async transports hold connections that belong to the event loop they were
first used on. Each asyncio.run() call starts a new loop, so a client reused
across two of them cannot send. The second call raises EventLoopChangedError
before anything leaves the process.
client = sasvi.SVIClient.from_env()
# WRONG. The second asyncio.run() is a second event loop.
asyncio.run(client.alerts.get_async(alert_id="a-1"))
asyncio.run(client.alerts.get_async(alert_id="a-2")) # EventLoopChangedError
# RIGHT. One loop, one client, every call inside it.
async def main() -> None:
async with sasvi.SVIClient.from_env() as client:
await client.alerts.get_async(alert_id="a-1")
await client.alerts.get_async(alert_id="a-2")
asyncio.run(main())
The sync methods of the same client are not bound to a loop.
Using a client after it is closed
A request through a closed client raises ClientClosedError. That includes a
Document or another handle kept from the client: it sends through the client
that produced it. Both errors are SVIError subclasses, so except SVIError
catches them. Neither is a TransientError. Build a new client and fetch the
object again.
Thread-bridged async is not free
Two public async methods still run sync code on a worker thread:
AuthorizationCodeTokenProvider.get_token_async,UsernamePasswordTokenProvider.get_token_async. The token request runs inside the provider's single-flight lock and its sync retry rules, so sixteen concurrent callers still make one request.AttachmentsManager.download_to_async, for its local file writes only (create, write, fsync and rename). The HTTP read is native async.
Each call uses a worker thread, and a bridged call cannot be cancelled once it has started.
Every other _async method awaits the generated client on the event loop.
Mixing sync and async on the same object
A bound Document carries a DocumentRuntime that holds both a sync and async
HTTP client. Calling doc.refresh() then await doc.refresh_async() on the same
object works, but interleaving sync mutations with parallel async reads on the same
object can race the snapshot. Use a fresh handle per concurrent task.
Debugging async code
Enable asyncio debug mode
import asyncio
asyncio.run(main(), debug=True)
Or via env var: PYTHONASYNCIODEBUG=1. This warns about slow callbacks (>100 ms)
and unawaited coroutines.
SDK wire logging
client = sasvi.SVIClient.from_env(
log_level="DEBUG",
log_http=True,
log_http_level="DEBUG",
log_slow_request_seconds=1.0,
)
Slow requests log at WARNING with outcome=final:slow, which is the easiest way to
spot a single bad request in a 100-call fanout.
CLI --debug flag
sasvi <cmd> --debug prints the full Python traceback on any classified error,
including from async paths. Use it during development.
aiomonitor for production
In production async workers, mount aiomonitor (third-party) to inspect running
tasks live without restarting the process.
Async + transactions
The SDK does not provide a transaction wrapper. Every call is its own request. Composite operations that must succeed or fail together are the caller's job:
async def route_atomically(client, alert_id, queue_id):
alert = await client.alerts.get_async(alert_id=alert_id)
try:
await alert.update_fields_async(queue_id=queue_id)
await alert.comments.create_async(text="Routed.")
except Exception:
# Best-effort compensating action.
await alert.update_fields_async(queue_id=alert.queue_id)
raise
For workflows that actually need transactional semantics, build them on top of the Workflows service.
Go further
- Async fanout recipe. The canonical bounded-concurrency pattern.
- Performance guide. Concurrency tuning, connection pooling.
- Errors reference. Typed exceptions surface on both sync and async paths.
- Troubleshooting.
TransientError, deadlocks.