Introduction
In the previous lessons, we implemented authentication, authorization, centralized error handling, logging, and production preparation. This lesson focuses on making the application not only functional, but also secure, measurable, efficient, and maintainable. In real-world systems, security and performance are rarely solved by one configuration setting. Middleware ordering, endpoint policies, database queries, response contracts, and layer responsibilities must be evaluated together.
We will improve the product-listing endpoint in our Clean Architecture application. The goals are to avoid transferring unnecessary data, prevent unnecessary database queries, preserve asynchronous execution, limit abusive traffic, and provide predictable responses to API clients.
1. Essential API security protections
HTTPS and secure communication
Authentication data, access tokens, and business information must be transmitted over HTTPS. In production, disabling plain HTTP at the infrastructure level or configuring a secure reverse proxy can be preferable to redirecting every HTTP request. In development, UseHttpsRedirection is a practical option.
if (!app.Environment.IsDevelopment())
{
app.UseHsts();
}
app.UseHttpsRedirection();HSTS tells browsers to use HTTPS for subsequent requests. However, mobile clients and server-to-server integrations may not apply HSTS in the same way. Therefore, verify that the API is actually exposed through a secure port and that the hosting infrastructure does not permit insecure access.
Reducing abuse with rate limiting
Authentication alone does not prevent brute-force attempts, expensive searches, or automated request floods. ASP.NET Core rate-limiting middleware can limit login, search, reporting, and other costly endpoints.
using System.Threading.RateLimiting;
using Microsoft.AspNetCore.RateLimiting;
builder.Services.AddRateLimiter(options =>
{
options.AddFixedWindowLimiter("catalog", limiterOptions =>
{
limiterOptions.PermitLimit = 60;
limiterOptions.Window = TimeSpan.FromMinutes(1);
limiterOptions.QueueLimit = 0;
limiterOptions.AutoReplenishment = true;
});
options.OnRejected = async (context, cancellationToken) =>
{
context.HttpContext.Response.StatusCode = StatusCodes.Status429TooManyRequests;
await Results.Problem(
statusCode: StatusCodes.Status429TooManyRequests,
title: "Too many requests",
detail: "Please try again later.")
.ExecuteAsync(context.HttpContext);
};
});Enable the middleware in the request pipeline and apply the policy only to endpoints that need it:
app.UseRouting();
app.UseAuthentication();
app.UseAuthorization();
app.UseRateLimiter();
app.MapControllers();[EnableRateLimiting("catalog")]
[HttpGet]
public async TaskRate limits are operational settings, not universal truths. Choose them based on capacity measurements and client behavior. Before production deployment, load-test the policy and document the 429 response as part of the client contract.
Authorization and data access
The fact that an endpoint is available to authenticated users does not mean that every authenticated user may access every record. User, tenant, and role restrictions must be applied through the Application layer or appropriate domain and authorization rules. If a user may only see their own orders, removing that filter because the controller already knows the user is authenticated creates a security vulnerability.
var userId = _currentUser.UserId;
var orders = await _orderService.GetForUserAsync(userId, query, cancellationToken);Do not trust user ID, role, or tenant ID values supplied by the client. Obtain these values from the authentication context or server-side authorization policies.
2. Making EF Core queries efficient
Use projection instead of loading entities
List screens rarely need every entity property. Loading complete entities may select unnecessary columns, increase change-tracking overhead, and accidentally expose sensitive data in the response. Project directly to a DTO instead.
public sealed record ProductListItemDto(
Guid Id,
string Name,
decimal Price,
string CategoryName,
bool IsActive);public async Task<IReadOnlyList<ProductListItemDto>> GetActiveProductsAsync(
CancellationToken cancellationToken)
{
return await _dbContext.Products
.AsNoTracking()
.Where(product => product.IsActive)
.OrderBy(product => product.Name)
.Select(product => new ProductListItemDto(
product.Id,
product.Name,
product.Price,
product.Category.Name,
product.IsActive))
.ToListAsync(cancellationToken);
}This query selects only the fields required by the DTO. AsNoTracking removes change-tracking overhead in read-only scenarios. If the same entity must later be updated, do not apply no-tracking automatically; evaluate the tracking behavior deliberately.
Include and the N+1 query problem
Querying a category or stock record separately inside a loop creates the N+1 problem. The first query retrieves the product list, then another query runs for each record. This may look acceptable with test data but can cause serious delays as production data grows.
var products = await _dbContext.Products
.AsNoTracking()
.Select(product => new ProductListItemDto(
product.Id,
product.Name,
product.Price,
product.Category.Name,
product.IsActive))
.ToListAsync(cancellationToken);Projection allows the related category value to become part of the generated SQL query in a controlled way. Include is not always wrong, but when an API needs only a few fields, direct projection generally provides a clearer response-oriented query.
Pagination and limiting result sets
Do not allow an endpoint to return an unlimited number of records. Define a reasonable maximum page size in the Application query model.
public sealed record ProductQuery(int Page = 1, int PageSize = 20, string? Search = null);var page = query.Page < 1 ? 1 : query.Page;
var pageSize = Math.Clamp(query.PageSize, 1, 100);
var baseQuery = _dbContext.Products
.AsNoTracking()
.Where(product => product.IsActive);
if (!string.IsNullOrWhiteSpace(query.Search))
{
baseQuery = baseQuery.Where(product =>
product.Name.Contains(query.Search));
}
var totalCount = await baseQuery.CountAsync(cancellationToken);
var items = await baseQuery
.OrderBy(product => product.Name)
.Skip((page - 1) * pageSize)
.Take(pageSize)
.Select(product => new ProductListItemDto(
product.Id,
product.Name,
product.Price,
product.Category.Name,
product.IsActive))
.ToListAsync(cancellationToken);For very large tables and deep pages, consider keyset pagination instead of offset-based Skip and Take. In either approach, ordering must be deterministic and appropriate indexes should be reviewed.
3. Using asynchronous execution correctly
Database and network calls are I/O-bound operations. Synchronous APIs can occupy a thread while the operation waits. Therefore, preserve asynchronous execution from the controller through the Application layer and into Infrastructure.
public async Task<ActionResult<ProductListResponse>> GetProducts(
[FromQuery] ProductQuery query,
CancellationToken cancellationToken)
{
var response = await _productService
.GetProductsAsync(query, cancellationToken);
return Ok(response);
}A CancellationToken helps stop unnecessary database work when the client disconnects or a request timeout occurs. However, not every method should be made async artificially. For simple in-memory calculations, using Task.Run without a clear reason usually does not improve performance.
Avoid randomly mixing synchronous and asynchronous EF Core calls. Use APIs such as ToListAsync, FirstOrDefaultAsync, AnyAsync, CountAsync, and SaveChangesAsync where appropriate. Do not start two concurrent queries on the same DbContext instance; await operations sequentially.
4. Consistent responses
Clients can work reliably with an API only when success and error responses are predictable. Successful list responses should use the same structure for items and pagination metadata.
public sealed record PagedResult<T>(
IReadOnlyList<T> Items,
int Page,
int PageSize,
int TotalCount);Use HTTP status codes consistently: 200 for successful reads, 201 for newly created resources, 400 for invalid requests, 401 when authentication is missing, 403 when authorization fails, 404 when a resource cannot be found, and 500 for unexpected server errors.
Generate error responses using the Problem Details approach introduced in the previous lesson. In production, never expose stack traces, connection strings, SQL details, or internal exception messages to clients. Return a safe description and correlate the event with a trace or correlation ID in the logging system.
5. Code quality through a Clean Architecture lens
Do not break layer boundaries in the name of performance. Controllers should not use DbContext directly, Infrastructure details should not leak into the Domain layer, and DTO mapping should not be performed randomly in the Presentation layer. The Application layer should define the required data and business flow, while Infrastructure should contain the technical data-access implementation.
| Review area | Expected approach |
|---|---|
| Security | HTTPS, authorization policies, rate limiting, and sensitive-data controls |
| Query | Projection, AsNoTracking, bounded result sets, and suitable indexes |
| Asynchrony | End-to-end async execution with CancellationToken |
| Response | Correct status codes and consistent Problem Details |
| Architecture | Clear separation of Controller, Application, and Infrastructure responsibilities |
Common mistakes
- Applying the same rate limit to every endpoint without considering endpoint cost.
- Assuming authorization is unnecessary because authentication is enabled.
- Returning every entity property from a list query.
- Executing a new database query for every item inside a loop.
- Making only the controller asynchronous while using synchronous EF Core calls in the repository.
- Returning exception messages or stack traces to clients.
- Using raw SQL immediately instead of first inspecting the LINQ query and generated SQL.
- Trusting a client-provided
PageSizewithout enforcing an upper bound.
Practice exercise
Improve your product-listing endpoint with the following requirements:
- Apply a rate-limiting policy named
catalog. - Use
ProductListItemDtoprojection instead of returning entities. - Use
AsNoTrackingandToListAsyncfor the read query. - Validate page number and page size, limiting page size to 100.
- Pass the request
CancellationTokenthrough the Application and Infrastructure layers. - Verify that 404 and 429 responses use the Problem Details format.
- Add an integration test proving that the response does not contain sensitive data.
Conclusion
This lesson treated API security, performance, and code quality as one connected discipline. HTTPS and rate limiting reduce common attack surfaces, while authorization verifies that data belongs to the correct user. Projection, AsNoTracking, pagination, and asynchronous queries use database and application resources more efficiently. Consistent response contracts make client development easier. Finally, we applied all improvements without violating Clean Architecture boundaries. In the final lesson, we will review the complete project, create a production-oriented architecture checklist, and identify future improvement opportunities.
Sources
- https://learn.microsoft.com/en-us/aspnet/core/performance/rate-limit?view=aspnetcore-10.0
- https://learn.microsoft.com/en-us/ef/core/performance/efficient-querying
- https://learn.microsoft.com/en-us/aspnet/core/fundamentals/error-handling-api?view=aspnetcore-10.0
- https://learn.microsoft.com/en-us/aspnet/core/security/enforcing-ssl?view=aspnetcore-10.0