Programming and async
CoreWrite clean, typed, concurrent services that hold up under real traffic.
Concepts
Structured concurrencyRun tasks as a group that starts and cancels together, so nothing leaks.
Structured concurrency is a programming paradigm that ties the lifetime of concurrent tasks to a lexical scope. Tasks spawned inside a scope cannot outlive it: when the block exits, every child task is cancelled and awaited before execution moves on. This prevents the class of bugs where a background task continues running after the code that started it has already returned, leaking resources or causing subtle state corruption.
In Python the pattern is most fully realized in Trio's nurseries and in asyncio's TaskGroup, added in Python 3.11. The guarantee matters especially in AI services where a single request may fan out into dozens of tool calls and retrieval steps: if the request is cancelled, every sub-task is cancelled with it rather than silently orphaned.
Sources
BackpressureKeep fast producers from drowning slow consumers under load.
Backpressure is the mechanism by which a slow consumer signals to a fast producer to slow down, rather than letting a queue grow unboundedly until memory is exhausted or messages are dropped. In an AI service, a common failure is a high-throughput ingest path that enqueues work far faster than the model or the downstream API can drain it. Without backpressure, the queue balloons, latency climbs, and the system eventually crashes or starts dropping requests silently.
Implementing backpressure usually means setting a bounded queue and blocking or rejecting new work when it is full, rather than accepting everything and hoping for the best. asyncio queues accept a maxsize argument for exactly this purpose.
Sources
Technologies
asyncioPython's event loop for concurrent I/O without threads.
asyncio is Python's built-in event loop and coroutine framework, introduced in Python 3.4 and stable since 3.7. It runs I/O-bound tasks concurrently on a single thread by suspending a coroutine at each await point and resuming another that is ready, without the overhead or complexity of threads. In AI services, nearly everything is I/O-bound: model API calls, database queries, embedding lookups, and tool calls all spend most of their time waiting for a network response rather than computing.
asyncio's native primitives (TaskGroup, Queue, timeout, gather) are the right building blocks for the concurrency layer of an AI backend. The key discipline is to keep CPU-bound work out of the event loop: any heavy computation should run in a thread pool via loop.run_in_executor.
Sources
PydanticTyped models that validate data at the boundary.
Pydantic is a Python data validation library built on type annotations. You declare the shape of data as a Python class, and Pydantic enforces that shape at runtime, raising a structured error if any field is wrong rather than letting malformed data propagate silently into business logic. It is the de-facto standard for validating data at service boundaries in Python: API request bodies, environment configuration, and crucially, model outputs that need to conform to a typed schema before your code acts on them.
Sources
In production
The discipline that separates a shipped system from a demo.
Deadline every callNo external call without a timeout; a hung dependency must never hang the whole system.
Every call to an external system, whether a model API, a database, or a third-party tool, must be wrapped in a timeout. Without one, a hung dependency can hold a connection open indefinitely, exhausting the thread pool or event loop and taking down the whole service. The timeout should be set at the point of the call, not assumed from a framework default, and its value should reflect the SLA you are trying to meet.
In asyncio, asyncio.timeout() and asyncio.wait_for() are the right primitives. The discipline is to wire a timeout before the first deploy, not after the first outage.
Sources
Degrade gracefullyDecide the fallback before the dependency fails, not in the middle of an incident.
Deciding the fallback behavior before a dependency fails is far easier than deciding it in the middle of an incident. Graceful degradation means your service keeps returning something useful, a cached result, a simplified response, or an honest error message, rather than crashing or hanging when a downstream system is unavailable. For AI services this often means falling back to a simpler model, returning a cached embedding, or surfacing a clear 'feature temporarily unavailable' message instead of a blank failure.
Sources