Lesson 5 of 9
Async/Await Best Practices for Backend
Async/await is the foundation of ASP.NET Core's scalability. The key insight: when a thread hits an `await` on an I/O operation it releases itself back to the thread pool, freeing it to handle another request while the I/O completes in the background. This is why a single ASP.NET Core server can handle thousands of concurrent requests with a small thread pool. Common pitfalls - deadlocks from `.Result`/`.Wait()`, unobserved exceptions from `async void`, missing CancellationToken propagation - cause hard-to-diagnose production issues.
Async Patterns & Common Pitfalls
using Microsoft.AspNetCore.Mvc;
// ━━ Golden rules of async in ASP.NET Core ━━
// 1. Async all the way - never block async code with .Result or .Wait()
// BAD: can deadlock in SynchronizationContext environments
var result = repository.GetProductAsync(id).Result; // NEVER do this
// GOOD: await end-to-end
var product = await repository.GetProductAsync(id);
// ━━ 2. Always pass CancellationToken ━━
// Client disconnects → token cancelled → DB query cancelled → saves resources
[HttpGet("{id}")]
public async Task<IActionResult> GetProduct(
string id,
[FromServices] IProductRepository repo,
CancellationToken cancellationToken) // ASP.NET Core injects request token automatically
{
var product = await repo.FindByIdAsync(id, cancellationToken);
return product is null ? NotFound() : Ok(product);
}
// ━━ 3. ValueTask for hot paths ━━
// Task always allocates. ValueTask avoids allocation when result is synchronous.
public ValueTask<Product?> GetCachedProduct(string id)
{
if (_cache.TryGetValue(id, out Product? cached))
return ValueTask.FromResult(cached); // no allocation - synchronous path
return new ValueTask<Product?>(FetchFromDatabaseAsync(id)); // allocates only on miss
}
// ━━ 4. Parallel async - don't await sequentially when independent ━━
// BAD: sequential - takes (A + B) ms
var productTask = await repo.GetProductAsync(id, ct);
var reviewTask = await reviewRepo.GetReviewsAsync(id, ct);
// GOOD: parallel - takes max(A, B) ms
var (product, reviews) = await (
repo.GetProductAsync(id, ct),
reviewRepo.GetReviewsAsync(id, ct)
).WhenAll();
// ━━ 5. ConfigureAwait - not needed in ASP.NET Core ━━
// ASP.NET Core has no SynchronizationContext - ConfigureAwait(false) is redundant
// but still recommended in library code
// ━━ 6. Avoid async void - use IHostedService for fire-and-forget ━━
// BAD: exceptions in async void are unobserved and crash the process
private async void SendEmailOnBackground() { } // NEVER
// GOOD: use Task.Run + structured logging, or better: a background queue
private readonly IBackgroundTaskQueue _queue;IAsyncEnumerable - Streaming Responses
// Stream data to client as it becomes available - perfect for large datasets
// Client gets first results immediately, not after entire dataset is loaded
[HttpGet("stream")]
public async IAsyncEnumerable<ProductDto> StreamProducts(
[FromServices] IProductRepository repo,
[System.Runtime.CompilerServices.EnumeratorCancellation] CancellationToken ct)
{
await foreach (var product in repo.StreamAllAsync(ct))
{
// Each product is flushed to client as it arrives from DB
yield return new ProductDto(product.Id, product.Name, product.Price);
}
}
// EF Core: AsAsyncEnumerable() for streaming from database
// await foreach (var product in dbContext.Products.AsAsyncEnumerable())
// ━━ Parallel.ForEachAsync (C# .NET 6+) - bounded parallel async ━━
// Process up to 4 items concurrently with cancellation support
await Parallel.ForEachAsync(
productIds,
new ParallelOptions { MaxDegreeOfParallelism = 4, CancellationToken = ct },
async (id, token) =>
{
var product = await repo.GetProductAsync(id, token);
await cache.SetAsync(id, product, token);
}
);
record ProductDto(string Id, string Name, decimal Price);
interface IProductRepository
{
Task<Product?> FindByIdAsync(string id, CancellationToken ct = default);
Task<Product?> GetProductAsync(string id, CancellationToken ct = default);
IAsyncEnumerable<Product> StreamAllAsync(CancellationToken ct = default);
}
record Product(string Id, string Name, decimal Price);
interface IBackgroundTaskQueue { }
interface IMemoryCache { bool TryGetValue(string key, out Product? value); }
interface IDistributedCache { Task SetAsync(string key, object? value, CancellationToken ct); }
Task<Product?> FetchFromDatabaseAsync(string id) => Task.FromResult<Product?>(null);
Microsoft.Extensions.Caching.Memory.IMemoryCache _cache = null!;Tip
Tip
Practice AsyncAwait Best Practices for Backend in small, isolated examples before integrating into larger projects. Breaking concepts into small experiments builds genuine understanding faster than reading alone.
.NET provides a unified platform for building various application types
Practice Task
Note
Practice Task - (1) Write a working example of AsyncAwait Best Practices for Backend from scratch without looking at notes. (2) Modify it to handle an edge case (empty input, null value, or error state). (3) Share your solution in the Priygop community for feedback.
Quick Quiz
Common Mistake
Warning
A common mistake with AsyncAwait Best Practices for Backend is skipping edge case testing - empty inputs, null values, and unexpected data types. Always validate boundary conditions to write robust, production-ready dotnet code.
Finished this lesson?