Async Routes and Background Work

Learn what async and await mean in plain words, when an async route makes an API faster (waiting on other services) and when it doesn't (your SQLite queries), and how to do work after the response has gone. Then you'll build a movie night picker that asks two services at once.

Updated

async and await

  1. async and await in Plain Words (Journeyman): Most of a back end's time goes on waiting, so an async def function can pause at each await and let other work run, asyncio.gather waits for two things at once instead of one after the other, and time.sleep inside async def holds up everything else.
  2. Async Routes: When They Help, and When They Don't (Freelancer): An async def route that calls other services with httpx's AsyncClient can ask them all at once with asyncio.gather and give up after a timeout with a 503, while routes with blocking code such as sqlite3 stay plain def, because one blocking call inside async def holds up every request.

Background Work

  1. Work That Runs After the Response (Freelancer): FastAPI's BackgroundTasks runs a function after the answer has gone, so a caller never waits for a confirmation message or a log entry, 202 Accepted says slow work has been taken on, and a job queue such as Celery or RQ is what keeps work safe when it must survive a restart.

Exercise: Movie Night Picker

  1. Exercise: Movie Night Picker (Freelancer): Finish Movie Night Picker, an API that asks a showtimes service and a reviews service at the same time with httpx and asyncio.gather, answers 503 when either is slow or down, and saves the group's pick with a 201 before posting it to the group chat in a background task, checked by tests that never touch the network.