Skip to content

Concurrency and lifecycle

A controller can use the same Http.client("catalog") builder for several operations. Each awaited send has its own deadline and response. When an Orionis runtime is active, compatible calls on the same event loop reuse connections. Configure the catalog integration before trying these examples.

Where the code runsWho owns the resources?
HTTP controller or middleware under ASGI with lifespanOrionis opens the runtime during application startup and closes it on shutdown. The first actual network send initializes the pool. Each incoming request can use the same worker’s pool.
RSGI application under GranianOrionis binds the pool to the worker’s event loop using RSGI startup and shutdown hooks.
Reactor commandThe CLI runtime manages resources for the command. Resolve the manager by injection or use the facade during the command. Await any child tasks before returning.
Standalone script, background program you start yourselfCall await app.boot() and pair it with await app.aclose() in a finally on the same event loop.
Direct HTTP dispatch without a running server lifespanAn unowned send can use a temporary transport that closes after that operation. Run with the normal application lifecycle when connection reuse matters.

A pool belongs to one application, process and event loop. Separate server workers have separate pools and limits. Keep builders tied to the application currently handling the work. The integration examples show how to inject the manager into application code.

Save this as read_product.py beside your project’s reactor and run python read_product.py in the project environment. Use the profile of a real catalog you control that returns {"data":{"name":"Notebook"}}, or replace the network call with a fake for a local rehearsal. The script prints the product name.

import asyncio
from bootstrap.app import app
from orionis.http.client import IHttpManager
async def main() -> None:
await app.boot()
try:
http = await app.make(IHttpManager)
result = await http.client("catalog").get("/products/42")
print(result.throw().json("data.name"))
finally:
await app.aclose()
if __name__ == "__main__":
asyncio.run(main())

For example, fetch distinct product IDs four at a time. The following service is called after application startup. Each batch finishes before the next batch starts, so a list of thousands of IDs creates at most four request tasks at once. With the sample payload above, await product_names(http, [42]) returns {42: "Notebook"}.

import asyncio
from itertools import batched
from orionis.http.client import IHttpManager
async def product_names(http: IHttpManager, ids: list[int]) -> dict[int, str]:
catalog = http.client("catalog").acceptJson().connectTimeout(1).deadline(4)
names = {}
for batch in batched(ids, 4):
async with asyncio.TaskGroup() as group:
tasks = {
key: group.create_task(catalog.get(f"/products/{key}"))
for key in batch
}
for key, task in tasks.items():
names[key] = task.result().throw().json("data.name")
return names

The builder is immutable. Per-request credentials or options should be applied on a derived builder. TaskGroup waits for its tasks; if one task raises a transport error, it cancels unfinished siblings and raises an exception group. In this example HTTP error statuses are inspected after the batch completes. If you need independent per-item outcomes, catch the specific expected failures inside each worker and return a result for that ID.

SettingMeaning under load
max_in_flight (32 by default)Maximum admitted operations on one application event loop, shared across profiles.
max_pending (64)Further sends wait in arrival order until an active slot is free. Once the waiting queue is full a new send raises HttpCapacityException. A value of 0 rejects immediately when all active slots are busy.
max_connections (32)Physical connection budget on that loop. An admitted operation can still wait for a pooled connection.
max_keepalive_connections (16), keepalive_expiry (5 s)How many idle connections HTTPX can retain and how long they may remain idle.

Start by limiting the number of tasks created by your caller. Raising the queue length lets more callers wait; it does not create more connections. Your total potential load also depends on how many worker processes you deploy.

Distinguish a slow response from a busy client

Section titled “Distinguish a slow response from a busy client”

The time limits are measured in seconds. Every send makes one attempt. With the default profile, catalog.timeout(2).connectTimeout(1).deadline(4) allows up to one second for connection setup and up to four seconds for the entire send. timeout(2) applies to each I/O phase within its configured ceiling. connectTimeout() and deadline() reject values above their corresponding profile ceilings.

HttpTimeoutException.phaseTime being measuredUseful next check
connectOpening a connection (default 5 s).Check reachability of the configured host and port.
writeInactivity while writing request data (5 s).Inspect payload size and whether the upstream is receiving it.
readInactivity while reading response data (5 s).Check whether the upstream stops producing data between chunks.
poolWaiting for HTTPX to allocate a connection (2 s).Compare concurrent sends with max_connections.
deadlineTotal operation budget (15 s), including admission wait, preparation, I/O and reading the complete response.A request can hit this limit before opening a connection or while data is still arriving. Review queueing and the service’s total latency.

A full waiting queue raises HttpCapacityException immediately. Cancellation initiated by the caller propagates as asyncio.CancelledError. Let it propagate after cleanup. On final shutdown Orionis stops admitting work for that pool, wakes waiters and gives active sends a five-second grace period before cancelling unfinished I/O. A task holding an expired runtime owner receives HttpClosedException when it tries another send.

Enable INFO for the Python logger orionis.http.client to see one record per attempt reaching the response reader. A typical message looks like the following.

HTTP client=catalog method=GET result=response status=200 duration=0.012345 attempt=1

The record contains the profile name, method, outcome (response, error or cancelled), status when available and elapsed seconds in the transport/reader. A received 503 has outcome response. Use the exception type and phase or category to diagnose failures. URLs, query parameters, headers and bodies are omitted. For caller-observed latency, measure around the awaited send; an attempt log excludes time queued before it.

  • TLS and proxies. The HTTPX transport uses HTTPS, verifies the server certificate and uses HTTP/1.1. It sets trust_env=False for its TLS context and transport. The public Orionis configuration has no option to select a proxy, provide a client certificate for mutual TLS, disable certificate verification or enable HTTP/2.
  • Compression and size. Orionis sets Accept-Encoding: identity itself. On a response with a body it accepts absent Content-Encoding or identity; for example, Content-Encoding: gzip raises HttpDecodeException during the awaited send. Downloads are buffered within the response budget. For a large export, use an upstream paginated or bounded endpoint. This version offers neither streaming downloads nor multipart uploads.
  • Redirects, cookies and attempts. Each send issues one attempt. The application receives a 3xx and its Location header directly. Received Set-Cookie values remain available as headers; the client does not keep a cookie jar or retry calls automatically. Requests · Responses and errors