Performance and scale
This page is for the practitioner who runs the SDK in production: ingest pipelines, batch jobs, real-time triage workers. It covers the knobs for throughput, latency, and resilience under load.
The defaults are tuned for interactive use. Production workloads usually need at least retry tuning and a wall-clock deadline; throughput-bound workloads also need concurrency tuning and connection-pool sizing.
Headline knobs
| Concern | Knob | Default |
|---|---|---|
| Per-call SLA | SVIConfig(request_deadline_seconds=...) | unset (no cap) |
| Retry attempts | SVIClient(max_retries=...) | 3 |
| Backoff base | SVIClient(retry_backoff_seconds=...) (× 2^attempt) | 0.5 |
| Retryable statuses | SVIClient(retry_statuses=...) | 408, 429, 500, 502, 503, 504 |
| Slow-request log | SVIClient(log_slow_request_seconds=...) | unset |
| Connection pool (whole client) | SVIClient(limits=httpx2.Limits(...)) | httpx2 default (100 connections, 20 kept alive) |
| Timeout | SVIConfig(timeout=...) accepts float or httpx2.Timeout(...) | 30.0 s |
| Header and query redaction | SVIClient(log_http_redacted_headers=..., log_http_redacted_query_params=...) | safe defaults plus any caller adds |
Retry tuning
The default policy retries 3 times on idempotent methods with 0.5 s base backoff. That's fine for interactive use; production usually needs more attempts and a wall-clock cap.
import sasvi
client = sasvi.SVIClient(
auth=auth,
config=sasvi.SVIConfig(
base_url=base_url,
max_retries=6,
retry_backoff_seconds=0.5,
request_deadline_seconds=15.0,
),
)
| Tenant profile | Recommended max_retries | retry_backoff_seconds | request_deadline_seconds |
|---|---|---|---|
| Stable, low-latency | 2 | 0.25 | 5 |
| Default | 3 | 0.5 | 10 |
| Periodic 503s under load | 6 | 0.5 | 20 |
| Highly contested, write-heavy | 4 | 1.0 | 30 |
Token requests have their own fixed policy: a client-credentials or password
grant is resent up to two times when SAS Logon answers 408, 429 or 5xx, inside
the calling request's deadline, and then raises AuthServiceUnavailableError.
The request that needed the token is not retried on top of that. See
Authentication.
The retry loop computes next_sleep = retry_backoff_seconds * 2 ** attempt (with jitter).
max_retries=6 means 7 attempts and 6 sleeps of 0.5 s, 1 s, 2 s, 4 s, 8 s and 16 s:
31.5 s of backoff before jitter, and each sleep is scaled by 0.5x to 1.5x.
What the SDK resends, and what outcome_unknown means
A retry is safe when the first attempt provably did nothing. The loop sorts every failure into one of four classes:
| Class | What happened | outcome_unknown |
|---|---|---|
| Never left | Connect error, connect timeout, proxy error, pool timeout, token fetch failed | False |
| Uncertain | Read, write or protocol error after the request went out | True |
| Refused | HTTP 408 or 429: the server did not process the request | not raised |
| Server error | HTTP 5xx: the server may have applied the request before it failed | not raised |
A GET, HEAD or OPTIONS is resent in every class. POST and PATCH are never
resent. PUT and DELETE are in retry_methods by default, and what happens to
them depends on whether the request is guarded.
A request is guarded when it is not a GET, HEAD or OPTIONS and carries
If-Match, If-Unmodified-Since or If-None-Match. The SDK's document and
sheet writes are If-Match PUTs, so they are guarded. A custom request can opt
in with extensions={"sasvi_no_retry": True}, see
Custom endpoint requests.
| Request | Never left | Refused (408, 429) | Uncertain | 5xx |
|---|---|---|---|---|
| GET, HEAD, OPTIONS | resent | resent | resent | resent |
| PUT or DELETE, unguarded | resent | resent | resent | resent |
| PUT or DELETE, guarded | resent | resent | NetworkError(outcome_unknown=True) after 1 attempt | the 5xx comes back |
| POST, PATCH | not resent | not resent | not resent | not resent |
The guard exists because a resent conditional write lies. If the server applied the PUT and the response was lost, the retry carries the old ETag, and the server answers 412. The write succeeded and the caller sees a conflict.
When you catch NetworkError or DeadlineExceededError, read
exc.outcome_unknown before you resend a write. False means the request never
reached the server and resending is safe. True means the server may have
applied it: read the resource again and compare before you write a second time.
An unguarded DELETE is still resent. When the resend finds nothing, the first
attempt may be the reason. The SDK logs a WARNING and sets
response.extensions["sasvi_prior_attempt_outcome_unknown"] = True on a 404 that
follows an uncertain failure or a 5xx.
Bounded deadlines under high fanout
Set request_deadline_seconds to a value smaller than your worker's SLA. A slow
tenant then fails that one call instead of holding a worker for the full client
timeout, and the rest of the batch proceeds.
import sasvi
ingest_client = sasvi.SVIClient(
auth=auth,
config=sasvi.SVIConfig(base_url=base_url, max_retries=3, request_deadline_seconds=8.0),
)
The call raises DeadlineExceededError when the budget runs out; catch it
explicitly to record the failure and move on.
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.
Per-call opt-out
The retry policy is per-client. To opt one call out, build a second client:
no_retry = sasvi.SVIClient(base_url=base_url, auth=auth, max_retries=0)
result = no_retry.alerts.get(alert_id=alert_id)
Connection pool sizing
Every service of one SVIClient (the seven generated services and custom) sends
through one shared sync connection pool and one shared async pool. A request to Data
Hub reuses the connection a SAND search opened, so an operation that touches several
services pays one TLS handshake, not one per service.
The pools use the httpx2 defaults: 100 concurrent connections and 20 idle connections
kept alive, across all hosts. httpx2 has no per-host limit. limits= sets the cap for
the whole client, and each of the two pools is held to it:
import httpx2
import sasvi
client = sasvi.SVIClient(
base_url=base_url,
auth=auth,
limits=httpx2.Limits(max_connections=200, max_keepalive_connections=100),
)
Going much higher than 200 rarely helps, because Viya rate limits cut in first.
Track outcome=final:slow log lines to spot when you're saturated. When every
connection is busy, a request waits up to the pool phase of timeout and then
fails with NetworkError ("No connection was free"), which is safe to retry.
A limits entry in sync_httpx_args or async_httpx_args still works and sizes
that side's pool alone. Setting it there and on limits= as well raises
SVIConfigurationError, so there is one answer to which limit applies.
Each HTTPX client keeps a pool of its own, exactly as before the pools were shared,
when that side's *_httpx_args carry transport, mounts or proxy, or when a
proxy is set in the environment (HTTP_PROXY, HTTPS_PROXY, ALL_PROXY) and
trust_env is on. limits= then applies to each client separately, and the SDK
logs a WARNING saying so.
The pools belong to the client: closing client.custom or one service's HTTPX client
leaves them open, and client.close() / await client.close_async() closes them
after every client that uses them. The async pool's connections belong to the event
loop that first used them, so an async call on a second loop, through any service,
raises EventLoopChangedError. Create one SVIClient per event loop.
Construction cost
One SVIClient resolves verify_ssl into a single ssl.SSLContext and hands it
to all 16 HTTPX clients. Loading the CA bundle is the expensive part of building
a client, so construction takes about 2 ms instead of 39 ms. An OAuth provider
with the same verify_ssl reuses that context, and one with a different setting
builds one context for its own pair. A client built with your own transport,
verify, cert or trust_env=False in sync_httpx_args / async_httpx_args
keeps those and does not take the shared context. Pass a ready context as
verify_ssl=ssl.create_default_context(cafile=...) to share it across several
SVIClient instances.
Import cost
import sasvi loads two modules. Each public name (sasvi.SVIClient, sasvi.Alert, sasvi.errors) is
imported the first time you read it, and from sasvi import SVIClient works as before. Building a
client loads about 390 sasvi.* modules. The generated models and operation modules load when a
call first needs them, so a process that only searches never imports the alerts or workflow
models. Before this, import sasvi loaded 1,421 modules (0.7 s warm, 4.5 s cold).
The sasvi CLI imports a command module when that command runs. sasvi --help, sasvi --version
and shell completion load no command module and no generated code; sasvi version loads only its
own. sasvi --help takes about 0.2 s instead of 1.7 s. tests/test_import_budget.py holds these numbers as module counts.
Concurrency
Async + bounded fanout is the SDK's main scaling lever:
import asyncio
import sasvi
sem = asyncio.Semaphore(30)
async def hydrate(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:
return await asyncio.gather(*(hydrate(client, a) for a in alert_ids))
| Workload | Suggested Semaphore cap |
|---|---|
| Local dev or single test | 5–10 |
| Production read fanout | 20–50 (raise gradually; watch tenant CPU) |
| Write / disposition fanout | 5–10 (writes contend; smaller is safer) |
| Bulk endpoints | 1 (the bulk request is itself the batch) |
The full pattern lives in the async fanout recipe.
Batching
For high-volume document writes, use the bulk endpoint instead of per-document create:
from sasvi.documents import raise_on_errors
results = client.documents.bulk_upsert(batch_of_500) # each item carries "objectTypeName"
raise_on_errors(results) # optional fail-fast; rows expose .succeeded / .error
The bulk endpoint is at least an order of magnitude faster than 500 individual
creates, and each BulkOperationResult row gives you per-row error details for
the failures.
For very large jobs, submit an async job:
job = client.documents.submit_async_job(
parameters={"document_count": "10000"},
)
print(job.id, job.status)
# The status you get back is the one the submit call returned. There is no
# polling call to make: job status and cancel live on the VI job monitor and
# indexer services, which publish no OpenAPI specification, so the SDK wraps
# no endpoint for them. Watch the Jobs page in the VI admin UI.
Pagination
For large result sets prefer the iterator over bumping limit:
for hit in client.search.text("foo").iter(page_size=200):
process(hit)
iter and iter_async are lazy. The list_all methods on the services
(client.alerts.list_all(), client.admin.reference_lists.list_all(),
client.workflows.tasks.list_all()) are eager. Each pages to the end and
materializes the whole result set in memory, so reach for them only when you know
the collection is small.
client.alerts.list() sends two requests for each page: the Alerts API page, then one
Data Hub read of the documents of every alert on it. alerts.list_all() with the
default batch_size=100 therefore sends two requests per 100 alerts.
Cap the iteration when you only need a sample:
import itertools
sample = list(
itertools.islice(
client.search.types("alerts").iter(page_size=200),
1000,
)
)
Logging in production
Production logging should focus on outliers, not every request:
import sasvi
client = sasvi.SVIClient(
base_url=base_url,
auth=auth,
log_http=True,
log_http_level="INFO",
log_slow_request_seconds=2.0, # log a WARNING above 2 s
# headers, query, and bodies are off by default
)
Set log_slow_request_seconds=2.0 and grep your logs for outcome=final:slow. Resist
log_http_request_body=True and log_http_response_body=True in prod. They fill
disks and raise the risk of logging PII even with redaction configured.
See Logging and diagnostics for the full surface.
Caching
The SDK does not implement client-side caching. Some opportunities to add it in your app:
| Resource | Lifetime | Strategy |
|---|---|---|
| Entity type metadata | Hours | functools.lru_cache around client.admin.entity_types.get(name=...) |
| Reference list items | Minutes to hours | Cache the to_lookup(by="code") dict |
| Configuration bundle | Hours | Cache client.admin.config.export_bundle().to_dict() |
| Document snapshots | Seconds (volatile) | Don't cache; the upstream value moves |
| Alert lists | Seconds | Don't cache; the result is intrinsically time-sensitive |
Watch for ReferenceListConcurrentModificationError if you cache reference lists
across writes; refresh on conflict.
Profiling
For latency profiling at the Python level:
import cProfile
with cProfile.Profile() as pr:
for _ in range(100):
client.alerts.get(alert_id="...")
pr.dump_stats("alerts.prof")
# snakeviz alerts.prof
For SDK-internal profiling, enable HTTP wire logging and look at duration_ms
distributions per endpoint.
Memory
The SDK does not load full result sets into memory by default; iterators stream pages. The two operations that materialize a lot at once:
list_all(eager pagination). Bounded by tenant data volume.- The
BulkOperationResultlist returned frombulk_upsert. Proportional to the input batch.
For both, prefer the iterator / streaming alternative when input is unbounded.
Production checklist
| Done | Item |
|---|---|
SVIConfig(request_deadline_seconds=...) set | |
log_slow_request_seconds=... set for outlier monitoring | |
log_http=True only with log_http_level="INFO" and bodies off | |
httpx2.Limits set if running > 50 concurrent requests | |
| Async siblings used in hot paths | |
| Bulk endpoints used for write fanout | |
Iterators (iter, iter_async) used for large reads | |
| Caching layer in front of metadata reads (entity types, ref lists) | |
client.close_async() on shutdown (or async with scope) |
Go further
- Async deep dive. Patterns, pitfalls, debugging.
- api/generated/sasvi/config.md. The
SVIConfigreference, including theretry_policy/http_log_policysnapshot views. - Bulk operations guide. Bulk endpoints, async jobs.
- Logging and diagnostics. Every log knob.