| Cookies :👈 | 👉:EF Core Performance Optimization |
ASP.NET Core Web API Best Practices: Building Production-Ready APIs |
ASP.NET Core Web API Best Practices: Building Production-Ready APIs
Table of Contents
- Introduction: Why Production API Design Matters
- Architecture: Layered Architecture and Separation of Concerns
- Request Pipeline: Middleware and Endpoint Execution
- Dependency Injection: Service Lifetimes and Composition
- Validation: FluentValidation or Built-in Validation
- Error Handling: Global Exception Handling and ProblemDetails
- Security: JWT, OAuth2 and Authorization Policies
- Performance: Caching, Pagination, Async and Database Optimization
- Resilience: Retry, Timeout and Circuit Breaker
- Observability: Logging, Metrics and Distributed Tracing
- Testing: Unit and Integration Testing
- Deployment: Docker and Cloud Deployment
- Common Mistakes: Anti-Patterns and Production Lessons
- Conclusion
1. Introduction: Why Production API Design Matters
What is a Production-Ready API?
A production-ready API is an API designed to operate reliably, securely, efficiently and consistently in a real-world environment where multiple users, applications and services depend on it. Developing an API that works on a developer's machine is relatively easy. However, developing an API that handles thousands of requests, protects sensitive information, recovers from failures and maintains good performance requires proper engineering practices.Why does production API design matter?
Consider an e-commerce application with the following APIs:- GET /api/products - Retrieve products.
- GET /api/orders - Retrieve customer orders.
- POST /api/orders - Create a new order.
- POST /api/payments - Process payments.
- Database overload due to inefficient queries.
- Memory consumption due to unnecessary object creation.
- Security vulnerabilities due to missing authorization.
- Duplicate orders due to retrying requests incorrectly.
- Application crashes due to unhandled exceptions.
- Difficulty identifying production issues due to insufficient logging.
Characteristics of a production-ready API
| Characteristic | Meaning |
|---|---|
| Scalability | Handles increasing users and requests. |
| Security | Protects APIs and sensitive information. |
| Performance | Responds quickly and efficiently. |
| Reliability | Works consistently and handles failures. |
| Maintainability | Easy to understand, modify and extend. |
| Observability | Helps identify and troubleshoot problems. |
| Testability | Supports automated testing. |
2. Architecture: Layered Architecture and Separation of Concerns
What is Layered Architecture?
Layered architecture organizes an application into different layers, where each layer has a specific responsibility. Instead of placing database queries, business logic, validation and HTTP handling inside a single controller, responsibilities are separated.Typical ASP.NET Core Web API architecture
1. Presentation Layer
Responsible for handling HTTP requests and responses. Typical responsibilities:- Accept HTTP requests.
- Read route parameters and request bodies.
- Call application services.
- Return appropriate HTTP status codes.
[ApiController]
[Route("api/products")]
public class ProductsController : ControllerBase
{
private readonly IProductService _productService;
public ProductsController(IProductService productService)
{
_productService = productService;
}
[HttpGet("{id:int}")]
public async Task GetById(
int id,
CancellationToken cancellationToken)
{
var product = await _productService.GetByIdAsync(
id, cancellationToken);
if (product == null)
return NotFound();
return Ok(product);
}
}
The controller should not contain complex business logic or direct database operations.
2. Application Layer
Contains application-specific business workflows and use cases. Responsibilities:- Coordinate business operations.
- Call domain services and repositories.
- Manage transactions when required.
- Coordinate external service calls.
public interface IProductService
{
Task<ProductDto?> GetByIdAsync(
int id,
CancellationToken cancellationToken);
}
public class ProductService : IProductService
{
private readonly IProductRepository _repository;
public ProductService(IProductRepository repository)
{
_repository = repository;
}
public async Task<ProductDto?> GetByIdAsync(
int id,
CancellationToken cancellationToken)
{
var product = await _repository.GetByIdAsync(
id, cancellationToken);
if (product == null)
return null;
return new ProductDto
{
Id = product.Id,
Name = product.Name,
Price = product.Price
};
}
}
3. Domain Layer
Contains core business concepts and business rules. Examples:- Entities.
- Value Objects.
- Domain Services.
- Domain Events.
- Business Invariants.
public class Product
{
public int Id { get; private set; }
public string Name { get; private set; }
public decimal Price { get; private set; }
public void UpdatePrice(decimal price)
{
if (price <= 0)
throw new ArgumentException(
"Price must be greater than zero.");
Price = price;
}
}
The domain layer should not depend on ASP.NET Core, EF Core or HTTP-specific classes.
4. Infrastructure Layer
Contains implementation details for external dependencies. Examples:- Entity Framework Core.
- SQL Server and PostgreSQL.
- Redis caching.
- Email providers.
- External REST APIs.
- Message brokers.
public class ProductRepository : IProductRepository
{
private readonly AppDbContext _context;
public ProductRepository(AppDbContext context)
{
_context = context;
}
public async Task<Product?> GetByIdAsync(
int id,
CancellationToken cancellationToken)
{
return await _context.Products
.AsNoTracking()
.FirstOrDefaultAsync(
p => p.Id == id,
cancellationToken);
}
}
Dependency direction
A common approach is to make outer layers depend on inner layers through abstractions.
Important: In Clean Architecture, the Domain layer should remain independent. Infrastructure implements interfaces required by the inner layers.
Best practices
- Keep controllers thin.
- Keep business rules outside controllers.
- Use interfaces where abstraction provides a real benefit.
- Keep database implementation details in Infrastructure.
- Avoid unnecessary layers and excessive abstractions.
- Use DTOs instead of exposing EF Core entities directly.
3. Request Pipeline: Middleware and Endpoint Execution
What is the ASP.NET Core request pipeline?
The request pipeline is a sequence of middleware components through which an HTTP request passes before reaching the selected endpoint. Each middleware can:
- Inspect the incoming request.
- Modify the request or response.
- Call the next middleware.
- Terminate the request without calling the next middleware.
Request pipeline execution
The exact ordering depends on the middleware and application requirements.
What is middleware?
Middleware is a component that participates in processing HTTP requests and responses. Example: Custom logging middleware.public class RequestLoggingMiddleware
{
private readonly RequestDelegate _next;
private readonly ILogger<RequestLoggingMiddleware> _logger;
public RequestLoggingMiddleware(
RequestDelegate next,
ILogger<RequestLoggingMiddleware> logger)
{
_next = next;
_logger = logger;
}
public async Task InvokeAsync(HttpContext context)
{
_logger.LogInformation(
"Request: {Method} {Path}",
context.Request.Method,
context.Request.Path);
await _next(context);
_logger.LogInformation(
"Response Status: {StatusCode}",
context.Response.StatusCode);
}
}
Register the middleware:
app.UseMiddleware<RequestLoggingMiddleware>();
Configure the pipeline in Program.cs
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddControllers();
builder.Services.AddAuthentication();
builder.Services.AddAuthorization();
var app = builder.Build();
app.UseExceptionHandler();
app.UseHttpsRedirection();
app.UseRouting();
app.UseCors("DefaultPolicy");
app.UseAuthentication();
app.UseAuthorization();
app.MapControllers();
app.Run();
The above is a simplified example. Authentication, CORS and exception handling must be configured with their respective options.
Authentication vs Authorization
| Authentication | Authorization |
|---|---|
| Identifies who the user is. | Determines what the user can access. |
| Validates credentials or tokens. | Checks permissions and policies. |
| Example: Valid JWT token. | Example: User has Admin role. |
- Register exception handling early in the pipeline.
- Place authentication before authorization.
- Configure CORS before endpoints execute.
- Avoid unnecessary middleware.
- Use built-in middleware wherever possible.
- Do not log passwords, access tokens or sensitive request bodies.
4. Dependency Injection: Service Lifetimes and Composition
What is Dependency Injection?
Dependency Injection (DI) is a design pattern in which an object receives its dependencies from an external container rather than creating them directly. Without DI:public class OrderService
{
private readonly OrderRepository _repository;
public OrderService()
{
_repository = new OrderRepository();
}
}
Problems:
- OrderService is tightly coupled to OrderRepository.
- Replacing the repository is difficult.
- Unit testing becomes harder.
- Mocking dependencies becomes difficult.
public class OrderService
{
private readonly IOrderRepository _repository;
public OrderService(IOrderRepository repository)
{
_repository = repository;
}
}
Register dependencies:
builder.Services.AddScoped<IOrderRepository,
OrderRepository>();
builder.Services.AddScoped<IOrderService,
OrderService>();
Three service lifetimes
ASP.NET Core provides three main dependency injection lifetimes.1. Transient
A new instance is created every time the service is requested from the container.builder.Services.AddTransient<IEmailService,
EmailService>();
Use cases:
- Lightweight stateless services.
- Small utility services.
- Services without shared state.
2. Scoped
One instance is created per DI scope. In a typical ASP.NET Core Web API request, one scope is created per request.builder.Services.AddScoped<IOrderService,
OrderService>();
Use cases:
- Business services.
- Repository implementations.
- Entity Framework Core DbContext.
builder.Services.AddDbContext<AppDbContext>(
options =>
options.UseSqlServer(
builder.Configuration.GetConnectionString(
"DefaultConnection")));
DbContext is registered as scoped by default.
3. Singleton
Only one instance is created for the lifetime of the application container.builder.Services.AddSingleton<ICacheService,
CacheService>();
Use cases:
- Thread-safe shared services.
- Application-wide configuration services.
- In-memory caches with appropriate concurrency handling.
Comparison
| Lifetime | Instance Creation | Typical Usage |
|---|---|---|
| Transient | Every resolution | Stateless utility services |
| Scoped | Once per scope | DbContext and business services |
| Singleton | Once per container | Thread-safe shared services |
Important production mistake: Captive dependency
A singleton service should not directly capture a scoped dependency. Incorrect:builder.Services.AddScoped<AppDbContext>();
builder.Services.AddSingleton<OrderService>();
If OrderService depends on AppDbContext, this creates a lifetime mismatch.
Correct:
builder.Services.AddScoped<OrderService>();
If a background singleton needs scoped services, use IServiceScopeFactory to create and dispose an appropriate scope.
Best practices:
- Use scoped lifetime for DbContext.
- Use singleton only for thread-safe services.
- Avoid service locator patterns.
- Do not store request-specific data in singleton services.
- Enable dependency validation during development.
5. Validation: FluentValidation or Built-in Validation
What is request validation?
Validation ensures incoming API data satisfies the required rules before business operations are performed. Example request:{
"name": "",
"price": -100
}
This request should not be accepted because:
- Name is empty.
- Price is negative.
Option 1: Built-in validation using Data Annotations
ASP.NET Core supports validation attributes. Example DTO:public class CreateProductRequest
{
[Required]
[StringLength(100, MinimumLength = 3)]
public string Name { get; set; }
[Range(0.01, 100000)]
public decimal Price { get; set; }
[Required]
public string Category { get; set; }
}
Controller:
[ApiController]
[Route("api/products")]
public class ProductsController : ControllerBase
{
[HttpPost]
public IActionResult Create(
CreateProductRequest request)
{
return Ok("Product created");
}
}
With [ApiController], invalid model state automatically produces an HTTP 400 response by default.
Option 2: FluentValidation
FluentValidation is a library that allows validation rules to be defined separately from DTO classes. Install the package:dotnet add package FluentValidation
Create a validator:
public class CreateProductValidator
: AbstractValidator<CreateProductRequest>
{
public CreateProductValidator()
{
RuleFor(x => x.Name)
.NotEmpty()
.MinimumLength(3)
.MaximumLength(100);
RuleFor(x => x.Price)
.GreaterThan(0);
RuleFor(x => x.Category)
.NotEmpty();
}
}
Register validators:
builder.Services.AddValidatorsFromAssemblyContaining<
CreateProductValidator>();
You must also configure how validators are executed. For example, invoke them explicitly in an application service or use a compatible validation pipeline.
Built-in Validation vs FluentValidation
| Feature | Data Annotations | FluentValidation |
|---|---|---|
| Setup | Built into .NET | External package |
| Simple validation | Excellent | Excellent |
| Complex rules | Limited | Flexible |
| Conditional validation | Less convenient | Built-in support |
| Separate validator classes | No | Yes |
Production best practices
- Validate all incoming client data.
- Validate business rules in the appropriate application or domain layer.
- Never trust client-side validation alone.
- Return meaningful validation messages.
- Do not perform database queries unnecessarily during basic field validation.
- Do not expose internal exception details in validation responses.
6. Error Handling: Global Exception Handling and ProblemDetails
Why is centralized error handling important?
Consider an application containing 50 API endpoints. If every controller implements its own try-catch blocks, error handling becomes repetitive and inconsistent. Instead, implement centralized exception handling.Traditional approach
[HttpGet("{id}")]
public async Task<IActionResult> Get(int id)
{
try
{
var product = await _service.GetByIdAsync(id);
return Ok(product);
}
catch (Exception ex)
{
return StatusCode(500, ex.Message);
}
}
Problems:
- Repeated code across controllers.
- Inconsistent error responses.
- Risk of exposing internal exception messages.
- More difficult maintenance.
Global exception handling
ASP.NET Core provides built-in exception handling middleware. Create a custom exception handler:public class GlobalExceptionHandler
: IExceptionHandler
{
private readonly ILogger<GlobalExceptionHandler> _logger;
public GlobalExceptionHandler(
ILogger<GlobalExceptionHandler> logger)
{
_logger = logger;
}
public async ValueTask<bool> TryHandleAsync(
HttpContext context,
Exception exception,
CancellationToken cancellationToken)
{
_logger.LogError(
exception,
"An unexpected error occurred.");
var problem = new ProblemDetails
{
Status = StatusCodes.Status500InternalServerError,
Title = "An unexpected error occurred.",
Detail = "Please try again later.",
Instance = context.Request.Path
};
context.Response.StatusCode =
problem.Status.Value;
await context.Response.WriteAsJsonAsync(
problem,
cancellationToken);
return true;
}
}
Register it:
builder.Services.AddExceptionHandler<
GlobalExceptionHandler>();
builder.Services.AddProblemDetails();
var app = builder.Build();
app.UseExceptionHandler();
What is ProblemDetails?
ProblemDetails is a standardized format for communicating API errors. It follows the RFC 9457 standard. Example response:{
"type": "about:blank",
"title": "An unexpected error occurred.",
"status": 500,
"detail": "Please try again later.",
"instance": "/api/products/10"
}
Common HTTP status codes
| Status Code | Meaning | When to use |
|---|---|---|
| 200 | OK | Successful GET request. |
| 201 | Created | Resource successfully created. |
| 204 | No Content | Successful operation without response body. |
| 400 | Bad Request | Invalid request data. |
| 401 | Unauthorized | Missing or invalid authentication. |
| 403 | Forbidden | Authenticated user lacks permission. |
| 404 | Not Found | Resource does not exist. |
| 409 | Conflict | Resource state conflict. |
| 429 | Too Many Requests | Rate limit exceeded. |
| 500 | Internal Server Error | Unexpected server failure. |
| 503 | Service Unavailable | Service temporarily unavailable. |
Production best practices
- Use global exception handling.
- Return consistent ProblemDetails responses.
- Log exceptions with appropriate severity.
- Never expose stack traces in production.
- Use custom exceptions for meaningful application errors.
- Do not use exceptions for normal business control flow.
- Include a correlation or trace identifier when useful.
7. Security: JWT, OAuth2 and Authorization Policies
Security is one of the most important aspects of a production-ready API. An API may contain sensitive information such as customer details, payment information and business data.
1. JWT Authentication
JWT stands for JSON Web Token. It is a compact token format commonly used to transmit claims between a client and an API. Typical authentication flow:
Example API request:
GET /api/orders
Authorization: Bearer eyJhbGciOi...
JWT structure
A JWT generally contains three parts:Header.Payload.Signature
- Header: Identifies the token type and signing algorithm.
- Payload: Contains claims such as user ID, roles and expiration.
- Signature: Helps verify token integrity and authenticity.
JWT configuration in ASP.NET Core
Install:dotnet add package Microsoft.AspNetCore.Authentication.JwtBearer
Configure authentication:
builder.Services
.AddAuthentication("Bearer")
.AddJwtBearer("Bearer", options =>
{
options.Authority =
builder.Configuration["Authentication:Authority"];
options.Audience =
builder.Configuration["Authentication:Audience"];
options.RequireHttpsMetadata = true;
});
builder.Services.AddAuthorization();
This example assumes an external identity provider that publishes OpenID Connect discovery metadata and signing keys.
Protect an API endpoint
[Authorize]
[HttpGet("orders")]
public IActionResult GetOrders()
{
return Ok("Authorized orders");
}
Only authenticated users with valid credentials can access this endpoint.
2. OAuth 2.0
OAuth 2.0 is an authorization framework that allows applications to obtain limited access to protected resources. For example:- A mobile application accesses an API on behalf of a user.
- A background service accesses another service using client credentials.
- An application accesses a third-party API using granted permissions.
- Authorization Code with PKCE: Commonly used for mobile and browser-based public clients.
- Client Credentials: Used for service-to-service authentication.
3. Authorization Policies
Authorization policies define what an authenticated user is allowed to do. Example:builder.Services.AddAuthorization(options =>
{
options.AddPolicy("AdminOnly", policy =>
policy.RequireRole("Admin"));
options.AddPolicy("CanManageOrders", policy =>
policy.RequireClaim(
"permission",
"orders.manage"));
});
Apply the policy:
[Authorize(Policy = "AdminOnly")]
[HttpDelete("{id}")]
public IActionResult DeleteOrder(int id)
{
return NoContent();
}
Authentication vs OAuth2 vs Authorization
| Concept | Purpose |
|---|---|
| Authentication | Establishes user or client identity. |
| JWT | Token format used to carry claims. |
| OAuth 2.0 | Framework for delegated authorization. |
| OpenID Connect | Identity and authentication layer built on OAuth 2.0. |
| Authorization Policy | Determines what an identity can access. |
Other important API security practices
- Use HTTPS everywhere.
- Validate token issuer, audience, signature and expiration.
- Use short-lived access tokens and secure refresh-token handling.
- Apply role-based or policy-based authorization.
- Implement rate limiting.
- Validate and sanitize untrusted input where appropriate.
- Store secrets in secure configuration providers or a secret manager.
- Use least-privilege database permissions.
- Configure CORS with specific trusted origins.
- Never store passwords in plain text.
8. Performance: Caching, Pagination, Async and Database Optimization
Performance is critical when APIs serve many concurrent users.
1. Caching
Caching stores frequently accessed data so that the application does not need to repeatedly perform expensive operations. Example: Suppose 1,000 users request the same product category. Without caching:
ASP.NET Core supports in-memory caching. Example:
builder.Services.AddMemoryCache();
Usage:
public class ProductService
{
private readonly IMemoryCache _cache;
private readonly AppDbContext _context;
public ProductService(
IMemoryCache cache,
AppDbContext context)
{
_cache = cache;
_context = context;
}
public async Task<Product?> GetProductAsync(
int id,
CancellationToken cancellationToken)
{
return await _cache.GetOrCreateAsync(
$"product-{id}",
async entry =>
{
entry.AbsoluteExpirationRelativeToNow =
TimeSpan.FromMinutes(5);
return await _context.Products
.AsNoTracking()
.FirstOrDefaultAsync(
p => p.Id == id,
cancellationToken);
});
}
}
For multiple application instances, use a distributed cache such as Redis rather than relying only on local in-memory caching.
2. Pagination
Never return millions of database records in one API response. Instead, return data in smaller pages. Example:GET /api/products?pageNumber=1&pageSize=20
Implementation:
[HttpGet]
public async Task<IActionResult> GetProducts(
int pageNumber = 1,
int pageSize = 20)
{
pageNumber = Math.Max(1, pageNumber);
pageSize = Math.Clamp(pageSize, 1, 100);
var products = await _context.Products
.AsNoTracking()
.OrderBy(p => p.Id)
.Skip((pageNumber - 1) * pageSize)
.Take(pageSize)
.ToListAsync();
return Ok(products);
}
For large datasets, consider keyset pagination instead of large Skip operations.
Example:
GET /api/products?afterId=100
Keyset pagination retrieves records after a known key and is often more efficient for large sequential datasets.
3. Asynchronous Programming
Use async/await for I/O-bound operations such as:- Database queries.
- HTTP requests.
- File operations.
- Message broker communication.
// Avoid blocking calls
var product = _context.Products
.FirstOrDefault(p => p.Id == id);
// Prefer asynchronous I/O
var product = await _context.Products
.FirstOrDefaultAsync(p => p.Id == id);
Important: Async does not automatically make a database query faster. It improves thread utilization while waiting for I/O.
Avoid using Task.Run simply to wrap synchronous database calls.
4. Database Optimization
Common optimization techniques:- Use AsNoTracking for read-only EF Core queries.
- Create indexes on frequently filtered and joined columns.
- Select only required columns using Select().
- Avoid N+1 query problems.
- Use pagination.
- Avoid unnecessary Include() operations.
- Use compiled queries only when profiling shows a benefit.
- Review actual SQL execution plans.
- Use connection pooling and appropriate database limits.
var products = await _context.Products
.AsNoTracking()
.Select(p => new ProductDto
{
Id = p.Id,
Name = p.Name,
Price = p.Price
})
.ToListAsync();
This avoids loading unnecessary entity columns.
5. Response compression
Compression reduces the amount of data transferred over the network. Example:builder.Services.AddResponseCompression();
var app = builder.Build();
app.UseResponseCompression();
Compression is particularly useful for larger JSON responses, subject to CPU and security considerations.
Performance best practices
- Measure before optimizing.
- Use caching for frequently accessed data.
- Implement pagination on collection endpoints.
- Use asynchronous I/O.
- Optimize database queries and indexes.
- Avoid returning unnecessary fields.
- Use response compression where appropriate.
- Monitor response time, throughput and database latency.
9. Resilience: Retry, Timeout and Circuit Breaker
What is resilience?
Resilience is the ability of an application to continue operating or recover gracefully when dependencies fail. Consider an API that communicates with three external services:
What happens if the Payment Service becomes unavailable? Without resilience mechanisms, requests may wait too long, fail repeatedly or consume application resources. Three important resilience patterns are:
1. Retry Pattern
Retry means attempting an operation again when a temporary failure occurs. Example:
Use cases:
- Temporary network failures.
- Transient database connectivity problems.
- Temporary service unavailability.
builder.Services
.AddHttpClient<IPaymentClient, PaymentClient>()
.AddStandardResilienceHandler();
The standard resilience handler provides configured resilience strategies, including retry, timeout and circuit breaker behavior. Do not blindly retry every operation. Retrying a payment POST operation without idempotency protection can result in duplicate payments.
2. Timeout Pattern
A timeout defines the maximum amount of time an operation is allowed to take. Example:
builder.Services
.AddHttpClient<IPaymentClient, PaymentClient>(
client =>
{
client.Timeout = TimeSpan.FromSeconds(10);
});
If the external service does not respond within the configured period, the operation is cancelled.
Timeouts prevent requests from waiting indefinitely.
3. Circuit Breaker Pattern
Circuit breaker prevents repeated requests to a dependency that is continuously failing. It has three states:- Closed: Requests are allowed normally.
- Open: Requests are blocked temporarily.
- Half-Open: A limited number of requests are allowed to check whether the service has recovered.
Comparison
| Pattern | Purpose | Benefit |
|---|---|---|
| Retry | Try again after temporary failure. | Recovers from transient errors. |
| Timeout | Stop operations taking too long. | Prevents indefinite waiting. |
| Circuit Breaker | Temporarily stop calling failing services. | Prevents cascading failures. |
Production best practices
- Use exponential backoff with jitter for appropriate retries.
- Retry only transient failures.
- Use idempotency keys for operations that may be retried.
- Configure sensible timeouts.
- Use circuit breakers for unstable remote dependencies.
- Respect cancellation tokens.
- Monitor retry counts and circuit-breaker state changes.
- Avoid unlimited retries.
10. Observability: Logging, Metrics and Distributed Tracing
What is observability?
Observability is the ability to understand the internal behavior of an application by examining its outputs. In production, an API may work for most users but fail for a particular request. Observability helps answer:- Why did the API request fail?
- Which database query was slow?
- Which external service caused the delay?
- How many requests are failing?
- Which API endpoint consumes the most resources?
1. Logging
Logging records events occurring inside an application. Example:public class OrderService
{
private readonly ILogger<OrderService> _logger;
public OrderService(
ILogger<OrderService> logger)
{
_logger = logger;
}
public void CreateOrder()
{
_logger.LogInformation(
"Order creation started.");
try
{
// Business operation
}
catch (Exception ex)
{
_logger.LogError(
ex,
"Order creation failed.");
throw;
}
}
}
Common logging levels:
| Level | Purpose |
|---|---|
| Trace | Very detailed diagnostic information. |
| Debug | Information useful during debugging. |
| Information | Normal application events. |
| Warning | Unexpected but recoverable situations. |
| Error | Operation failed. |
| Critical | Serious application failure. |
_logger.LogInformation(
"Order {OrderId} created for Customer {CustomerId}",
orderId,
customerId);
This makes logs easier to search and analyze.
2. Metrics
Metrics are numerical measurements collected over time. Important API metrics:- Request count.
- Request duration.
- Error rate.
- Requests per second.
- CPU utilization.
- Memory consumption.
- Database connection usage.
- External dependency latency.
builder.Services.AddOpenTelemetry()
.WithMetrics(metrics =>
{
metrics
.AddAspNetCoreInstrumentation()
.AddHttpClientInstrumentation()
.AddRuntimeInstrumentation();
});
These metrics can be exported to a monitoring backend.
3. Distributed Tracing
Distributed tracing tracks a request as it travels across multiple services. Example:
A trace contains multiple spans.
- Trace: Represents the complete end-to-end operation.
- Span: Represents one operation within the trace.
Trace ID: abc123
Span 1: API Gateway 20 ms
Span 2: Order API 50 ms
Span 3: Inventory API 100 ms
Span 4: Payment API 800 ms
Span 5: Database 30 ms
In this example, Payment API is the main source of latency.
OpenTelemetry is a widely used framework for collecting traces, metrics and logs.
Example tracing configuration:
builder.Services.AddOpenTelemetry()
.WithTracing(tracing =>
{
tracing
.AddAspNetCoreInstrumentation()
.AddHttpClientInstrumentation()
.AddSource("MyApplication")
.AddOtlpExporter();
});
Configure the OpenTelemetry exporter package and endpoint for your observability backend.
Logging vs Metrics vs Tracing
| Type | Answers | Example |
|---|---|---|
| Logging | What happened? | Payment failed. |
| Metrics | How much or how often? | 5% payment failure rate. |
| Tracing | Where did the request spend time? | Payment API took 800 ms. |
Production best practices
- Use structured logging.
- Use correlation IDs or trace IDs.
- Collect application and infrastructure metrics.
- Use distributed tracing for microservices.
- Monitor API latency and error rates.
- Avoid logging sensitive data.
- Configure alerts for important production failures.
- Use centralized log storage.
11. Testing: Unit and Integration Testing
Why is API testing important?
Testing ensures that the API behaves as expected and that changes do not introduce unexpected problems. Two important testing types are unit testing and integration testing.1. Unit Testing
Unit testing verifies a small unit of code independently. For example, test an OrderService without connecting to an actual database. Example:public class OrderServiceTests
{
[Fact]
public async Task GetOrderAsync_ReturnsOrder()
{
var mock = new Mock<IOrderRepository>();
mock.Setup(x => x.GetByIdAsync(1))
.ReturnsAsync(new Order
{
Id = 1
});
var service = new OrderService(mock.Object);
var result = await service.GetByIdAsync(1);
Assert.NotNull(result);
Assert.Equal(1, result.Id);
}
}
Common tools:
- xUnit.
- NUnit.
- MSTest.
- Moq or NSubstitute.
2. Integration Testing
Integration testing verifies whether multiple components work together correctly. For an ASP.NET Core Web API, integration testing can verify:- HTTP routing.
- Middleware execution.
- Authentication and authorization.
- Model validation.
- Database interaction.
- HTTP status codes and response formats.
public class ProductApiTests
: IClassFixture<WebApplicationFactory<Program>>
{
private readonly HttpClient _client;
public ProductApiTests(
WebApplicationFactory<Program> factory)
{
_client = factory.CreateClient();
}
[Fact]
public async Task GetProducts_ReturnsSuccess()
{
var response = await _client.GetAsync(
"/api/products");
response.EnsureSuccessStatusCode();
}
}
For meaningful database integration tests, use an isolated test database or a suitable database container. Do not assume EF Core's in-memory provider behaves exactly like a relational database.
Unit Testing vs Integration Testing
| Feature | Unit Testing | Integration Testing |
|---|---|---|
| Scope | Individual unit | Multiple components |
| Database | Usually mocked | Can use real test database |
| Speed | Fast | Usually slower |
| Purpose | Verify individual logic | Verify component interaction |
3. Load and Performance Testing
Load testing verifies how an API behaves under expected and high traffic. Useful tools:- k6.
- Apache JMeter.
- Azure Load Testing.
- Requests per second.
- Average response time.
- p95 and p99 response time.
- Error rate.
- CPU and memory usage.
- Test success and failure scenarios.
- Test validation and authorization.
- Test database integration.
- Test concurrency and load.
- Run automated tests in CI/CD pipelines.
12. Deployment: Docker and Cloud Deployment
What is Docker?
Docker is a containerization platform that packages an application and its dependencies into a container image. It helps ensure that an application behaves consistently across development, testing and production environments.Traditional deployment vs Docker deployment
Create a Dockerfile
# Build stage
FROM mcr.microsoft.com/dotnet/sdk:10.0 AS build
WORKDIR /src
COPY . .
RUN dotnet restore
RUN dotnet publish -c Release -o /app/publish
# Runtime stage
FROM mcr.microsoft.com/dotnet/aspnet:10.0
WORKDIR /app
COPY --from=build /app/publish .
ENTRYPOINT ["dotnet", "MyApi.dll"]
The example uses .NET 10.0. Match the SDK and runtime images to the target framework of your application.
Build the image:
docker build -t myapi .
Run the container:
docker run -p 8080:8080 myapi
Cloud deployment options
Common deployment platforms include:| Platform | Purpose |
|---|---|
| Azure App Service | Managed hosting for web applications and APIs. |
| Azure Container Apps | Managed hosting for containerized applications. |
| Azure Kubernetes Service | Managed Kubernetes for container orchestration. |
| AWS ECS | Container orchestration on AWS. |
| AWS EKS | Managed Kubernetes on AWS. |
| Google Cloud Run | Managed container execution. |
CI/CD pipeline
CI/CD automates building, testing and deploying applications.
Common tools:
- GitHub Actions.
- Azure DevOps Pipelines.
- Jenkins.
Production deployment best practices
- Use multi-stage Docker builds.
- Run containers as non-root users where possible.
- Keep secrets outside Docker images.
- Use environment-specific configuration.
- Implement health checks.
- Use readiness and liveness probes where supported.
- Enable HTTPS.
- Use automated CI/CD pipelines.
- Support graceful shutdown.
- Use backward-compatible database migrations.
- Maintain rollback procedures.
13. Common Mistakes: Anti-Patterns and Production Lessons
Even well-developed APIs can face production problems due to architectural and implementation mistakes.
1. Fat Controllers
Bad practice:[HttpPost]
public IActionResult CreateOrder(Order order)
{
// Validation
// Business logic
// Database queries
// Payment processing
// Email sending
// Logging
}
Problem: Controllers become difficult to maintain and test.
Better approach: Keep controllers responsible for HTTP handling and delegate application workflows to services or use cases.
2. Returning Database Entities Directly
Bad practice:return Ok(await _context.Products.ToListAsync());
Problems:
- Exposes internal database structure.
- May expose sensitive fields.
- Can create serialization problems with navigation properties.
- Couples API contracts to database entities.
3. Missing Pagination
Bad practice:var products = await _context.Products.ToListAsync();
Problem: Large datasets consume excessive memory and database resources.
Better approach: Implement pagination and enforce maximum page sizes.
4. Blocking Asynchronous Operations
Bad practice:var result = service.GetDataAsync().Result;
Problem: Blocking threads can reduce throughput and may contribute to deadlocks in certain synchronization contexts.
Better approach:
var result = await service.GetDataAsync();
5. Incorrect Dependency Injection Lifetimes
Bad practice: Injecting a scoped DbContext into a singleton service. Problem: Lifetime mismatch and potentially incorrect shared state. Better approach: Use appropriate scoped lifetimes or create scopes for background operations.6. Exposing Internal Exceptions
Bad practice:return StatusCode(500, exception.ToString());
Problem: Exposes internal implementation details.
Better approach: Use centralized exception handling and safe ProblemDetails responses.
7. No Authentication or Authorization
Problem: Sensitive endpoints may be accessed by unauthorized users. Better approach: Apply authentication and explicit authorization policies to protected endpoints.8. Overusing Caching
Problem: Users may receive outdated information, or one user's private data may be served to another user if cache keys are poorly designed. Better approach: Define cache expiration, invalidation and isolation strategies.9. Retrying Every Failed Request
Problem: Repeated retries can increase dependency load and create duplicate operations. Better approach: Retry only appropriate transient failures and use idempotency protection for operations that need it.10. Missing Observability
Problem: Production issues become difficult to diagnose. Better approach: Implement structured logging, metrics and distributed tracing.11. No API Versioning Strategy
Problem: Changes to API contracts may break existing client applications. Better approach: Introduce a versioning strategy for APIs with independently evolving consumers. Example:GET /api/v1/products
GET /api/v2/products
12. Incorrect HTTP Status Codes
Problem: Clients cannot reliably understand the result of an operation. Better approach: Return meaningful status codes such as 200, 201, 400, 401, 403, 404, 409 and 500.13. No Rate Limiting
Problem: A single client may generate excessive traffic and consume application resources. Better approach: Configure rate limiting based on user identity, API key or other suitable client identifiers.14. Putting Secrets in Source Code
Bad practice:string connectionString =
"Server=...;Password=MyPassword";
Problem: Secrets may leak through source control and build artifacts.
Better approach: Use secure configuration providers, environment-specific secrets and managed identity where available.
15. Ignoring Cancellation Tokens
Problem: Expensive operations may continue even after the client disconnects or the request is cancelled. Better approach:[HttpGet("{id}")]
public async Task<IActionResult> Get(
int id,
CancellationToken cancellationToken)
{
var product = await _context.Products
.FirstOrDefaultAsync(
p => p.Id == id,
cancellationToken);
return product == null
? NotFound()
: Ok(product);
}
Production API checklist
- Use layered architecture where complexity justifies it.
- Keep controllers thin.
- Use dependency injection correctly.
- Validate all incoming requests.
- Implement global exception handling.
- Return standardized ProblemDetails responses.
- Secure APIs with authentication and authorization.
- Implement pagination and caching where appropriate.
- Use asynchronous I/O.
- Optimize database queries.
- Configure retries, timeouts and circuit breakers.
- Implement structured logging and tracing.
- Write unit and integration tests.
- Automate deployment using CI/CD.
- Monitor application health and performance.
14. Conclusion
Building a production-ready ASP.NET Core Web API requires more than implementing controllers and database operations. A well-designed API should follow sound architectural principles, use dependency injection correctly, validate incoming requests, handle exceptions consistently and protect resources through authentication and authorization. It should also provide good performance through caching, pagination, asynchronous programming and database optimization. Resilience mechanisms such as retry, timeout and circuit breaker help applications handle temporary failures. Observability through logging, metrics and distributed tracing makes production troubleshooting easier. Finally, automated testing, Docker-based deployment, CI/CD pipelines and continuous monitoring help maintain application quality throughout its lifecycle. Final principle: A production-ready API should be secure, scalable, maintainable, observable, testable and resilient. These qualities should be considered from the beginning of development rather than added after production problems occur.| Cookies :👈 | 👉:EF Core Performance Optimization |