⚡ Async/Await = Scalable APIs
Web APIs need to scale. Async/Await best practices ensure your APIs handle high load efficiently.
📝 API Best Practices
// Async Controllers
[ApiController]
[Route("api/[controller]")]
public class OrdersController : ControllerBase
{
private readonly IOrderService _orderService;
public OrdersController(IOrderService orderService)
{
_orderService = orderService;
}
[HttpGet("{id}")]
public async Task> GetOrder(int id)
{
var order = await _orderService.GetOrderAsync(id);
if (order == null)
return NotFound();
return Ok(order);
}
[HttpPost]
public async Task> CreateOrder(OrderDto dto)
{
var order = await _orderService.CreateOrderAsync(dto);
return CreatedAtAction(nameof(GetOrder), new { id = order.Id }, order);
}
}
// Async Service Implementation
public class OrderService : IOrderService
{
private readonly IOrderRepository _orderRepo;
private readonly IEmailService _emailService;
public async Task GetOrderAsync(int id)
{
return await _orderRepo.GetOrderWithDetailsAsync(id);
}
public async Task CreateOrderAsync(OrderDto dto)
{
var order = new Order { /* ... */ };
await _orderRepo.AddAsync(order);
await _orderRepo.SaveAsync();
// Fire and forget (not recommended for critical operations)
_ = _emailService.SendConfirmationAsync(order);
return order;
}
}
🎯 Performance Patterns
// Parallel API Calls
[HttpGet("dashboard")]
public async Task> GetDashboard()
{
var usersTask = _userService.GetUsersAsync();
var ordersTask = _orderService.GetOrdersAsync();
var statsTask = _statsService.GetStatsAsync();
await Task.WhenAll(usersTask, ordersTask, statsTask);
return new DashboardData
{
Users = usersTask.Result,
Orders = ordersTask.Result,
Stats = statsTask.Result
};
}
// Proper Cancellation
public async Task>> SearchOrders(
[FromQuery] string query,
CancellationToken cancellationToken)
{
return Ok(await _orderService.SearchOrdersAsync(query, cancellationToken));
}
// Timeout Handling
public async Task> GetExternalData()
{
using var cts = new CancellationTokenSource(TimeSpan.FromSeconds(30));
try
{
return Ok(await _externalService.GetDataAsync(cts.Token));
}
catch (OperationCanceledException)
{
return StatusCode(408, "Request timed out");
}
}
// Rate Limiting
public async Task> CreateOrderWithLimit(OrderDto dto)
{
if (!await _rateLimiter.IsAllowedAsync(User.Identity.Name))
{
return StatusCode(429, "Too many requests");
}
return await CreateOrderAsync(dto);
}
💡 Web API Tips
- Use async all the way
- Implement proper cancellation
- Set appropriate timeouts
- Use parallel operations when possible
- Implement rate limiting
Async/await best practices are essential for building scalable web APIs. They ensure your APIs perform well under load.
