This post was originally published in Portuguese on my blog: Chamadas concorrentes com asyncio, timeout e degradação graciosa.
You know that screen that needs data from three different services? Customer profile, recent orders, recommendations. The most common way to write it is to call one after the other with await, and the result is that the screen takes the sum of all the calls. Worse: when the recommendations service chokes, the whole screen chokes with it, even though nobody cares that much about recommendations.
In this post I show a small aggregator that solves both problems: it calls everything at the same time with asyncio.TaskGroup, puts a timeout on each call, and decides what is required and what can be left out.
The core idea
The business rule is simple. The customer profile is required: without it there's no dashboard. Orders and recommendations are optional: if they take too long or return an error, the dashboard goes out without them, and the response says which sections were left out, in the degraded field. The front end decides what to show instead.
TaskGroup fits this well because of its default behavior: if one task raises an exception, its siblings are cancelled. For the required call that's exactly what I want. For the optional ones it's the opposite, so they catch their own error and return a result instead of raising.
Firing the three calls
The build method creates the three tasks inside the group. When the async with block ends, they have all finished, and then it's just a matter of calling result(). If something escapes the group, it arrives as an ExceptionGroup, and I translate it into the two domain exceptions, CustomerNotFound and ProfileUnavailable.
async def build(self, customer_id: int) -> Dashboard: try: async with asyncio.TaskGroup() as group: profile = group.create_task(self._fetch_profile(customer_id)) orders = group.create_task(self._fetch_optional(f"/customers/{customer_id}/orders")) recommendations = group.create_task( self._fetch_optional(f"/customers/{customer_id}/recommendations") ) except ExceptionGroup as errors: if errors.subgroup(CustomerNotFound) is not None: raise CustomerNotFound(customer_id) from None raise ProfileUnavailable(customer_id) from errors I used a regular except ExceptionGroup with subgroup because I need to look at what came inside the group before deciding which domain exception to raise: if there's a CustomerNotFound in there, the response is a 404, and anything else becomes a 502. The from None in the first case avoids dragging the whole group into the traceback of an error that is expected.
Timeout and concurrency limit
Every call goes through _fetch. The asyncio.Semaphore limits how many requests are in flight at the same time (useful when the same aggregator serves a lot of people and you don't want to drown the service behind it), and asyncio.timeout cuts the wait. Note that the timeout sits inside the semaphore: time spent waiting in the queue doesn't count against the call.
async def _fetch(self, path: str) -> Any: async with self._limit: async with asyncio.timeout(self._timeout): response = await self._client.get(f"{self._base_url}{path}") response.raise_for_status() return response.json() When asyncio.timeout expires it raises TimeoutError, the same built-in Python type, so there's no special exception to import.
Degrading instead of failing
The optional call swallows the expected errors, a timeout or any httpx.HTTPError, and returns a Section with error="unavailable". Since it never raises, the TaskGroup doesn't cancel anyone because of it.
async def _fetch_optional(self, path: str) -> Section: try: return Section(data=await self._fetch(path)) except (TimeoutError, httpx.HTTPError): return Section(error="unavailable") Testing without a network
In the tests I swap the upstream for an httpx.MockTransport with an async handler, so I can simulate slowness with asyncio.sleep without starting anything. The test below makes recommendations slow, with a 0.1 second timeout, and checks that the dashboard comes out without them.
async def test_slow_optional_call_degrades_instead_of_failing(): upstream = FakeUpstream(delays={"recommendations": 1.0}) aggregator, client = make_aggregator(upstream, timeout=0.1) async with client: dashboard = await aggregator.build(1) assert dashboard.recommendations.error == "unavailable" assert dashboard.recommendations.data is None assert dashboard.orders.data is not None assert dashboard.degraded == ["recommendations"] There's also a test that measures the maximum number of simultaneous calls in the handler: with three calls released the peak is 3, and with max_concurrency=1 the peak is 1. Stopwatch-based concurrency tests are fragile, so this counter is more reliable than comparing times (the timing test exists, but with a generous margin). Each test creates its own aggregator, so there's no shared state between them.
How to run it with Docker
The docker-compose.yml starts two services: upstream, which simulates the dependencies with configurable delays, and app, which is the aggregator. Recommendations take 2 seconds on purpose, longer than the 0.5 second timeout, so the very first call already shows the degradation.
docker compose up --build curl localhost:8000/customers/1/dashboard curl localhost:8000/customers/99/dashboard docker compose run --rm tests The first response comes back with "degraded": ["recommendations"] in about half a second, instead of the 2 seconds the slow call would take. The second returns a 404. Play with RECOMMENDATIONS_DELAY and UPSTREAM_TIMEOUT in the compose file and watch the result change.
Wrapping up
The pattern is small, but it solves a problem that shows up in almost every API that aggregates data: separating what is essential from what is decoration, and not letting the decoration take down the response. The full code, with tests, Dockerfile and compose, is at programero-python/2026-11-concurrent-calls-asyncio-taskgroup.
