Async, await, and cancellation
Let I/O wait without occupying a request thread.
The idea
An asynchronous database call allows the server to use a thread for other work while it waits. It does not make a slow SQL query fast. Propagate a CancellationToken from the request through the application boundary so abandoned work can stop at cooperative cancellation points.
Follow the flow
Make it concrete
This excerpt isolates the concept. Connect it to the booking API as you work through the exercise.
app.MapGet("/bookings/{id:guid}", async (
Guid id, IBookingStore store, CancellationToken ct) =>
{
var booking = await store.FindAsync(id, ct);
return booking is null
? Results.NotFound()
: Results.Ok(booking);
});Decisions that matter
- Await asynchronous I/O end to end; blocking on Result or Wait can exhaust request threads.
- Cancellation is cooperative and does not imply that a committed write was undone.
- Set operation deadlines and distinguish cancellation from application failures.
Your turn
A client cancels while the store is waiting on PostgreSQL. Where should the token travel, and why is Task.Run around the query unnecessary?
Reveal a worked answer
Pass the request token into the application operation and database API. Asynchronous I/O already yields while waiting; Task.Run adds scheduling overhead without improving the query. Test cancellation with a controlled fake that observes the token.