Introduction
The first version of a product-listing API often returns every product. This may appear acceptable with a small development database, but as the number of products grows, query time, JSON response size, serialization cost, and application memory usage increase quickly. If the client only displays the first few products, loading thousands of rows from the database is unnecessary resource consumption.
In this lesson, we will transform the product-listing API into a more controlled design. We will handle page number, page size, category, price range, search text, and sorting parameters. We will then build a query that selects only the required records and return a DTO containing the total count and page metadata.
The implementation will use offset pagination with Skip and Take. This approach supports jumping to an arbitrary page, making it practical for administration panels and traditional paging interfaces. However, high offset values may require the database to process many preceding rows. At the end of the lesson, we will examine the limits of offset pagination and when keyset pagination should be considered.
1. Why pagination improves performance
Pagination divides a result set into smaller portions instead of loading everything at once. Returning 25 products per request instead of all 100,000 products reduces several costs:
- Fewer rows are transferred from the database to the application.
- EF Core creates fewer entity or DTO instances.
- JSON serialization and network transfer take less time.
- The client has less data to parse.
- Per-request memory usage becomes more predictable.
Pagination does not automatically make a query fast. Filters must work well with indexes, ordering must be deterministic, and projection should select only the required properties. The AsNoTracking and projection techniques from earlier lessons are also important here.
2. Designing the paging contract
Let us define the query parameters in a dedicated model. Defaults prevent missing or invalid parameters from making the API unnecessarily expensive.
public sealed class ProductQueryParameters
{
public int Page { get; init; } = 1;
public int PageSize { get; init; } = 25;
public int? CategoryId { get; init; }
public decimal? MinPrice { get; init; }
public decimal? MaxPrice { get; init; }
public string? Search { get; init; }
public string SortBy { get; init; } = "name";
public bool Desc { get; init; }
}An example request could be /api/products?page=2&pageSize=20&categoryId=3&minPrice=100&search=keyboard&sortBy=price&desc=true. ASP.NET Core can bind this model from query-string values when it is declared as a controller action parameter.
Page and page size should be constrained before they are used. page=0 is invalid, while an extremely large pageSize allows a client to request more data than the endpoint should return in one response.
public sealed class ProductQueryParameters
{
private const int MaxPageSize = 100;
public int Page { get; init; } = 1;
public int PageSize { get; init; } = 25;
public int EffectivePage => Page < 1 ? 1 : Page;
public int EffectivePageSize =>
PageSize < 1 ? 25 : Math.Min(PageSize, MaxPageSize);
public int? CategoryId { get; init; }
public decimal? MinPrice { get; init; }
public decimal? MaxPrice { get; init; }
public string? Search { get; init; }
public string SortBy { get; init; } = "name";
public bool Desc { get; init; }
}In production applications, this validation can also be implemented in a validation layer or combined with the behavior of [ApiController]. The important point is to define the limits in one place and apply them consistently across endpoints.
3. Result DTO and page metadata
Returning only the product list forces the client to calculate or request the total count separately. Instead, let us create a response DTO that carries the items, total count, and page information together.
public sealed record ProductListItemDto(
int Id,
string Name,
decimal Price,
string CategoryName);
public sealed record PagedResult<T>
(
IReadOnlyList<T> Items,
int Page,
int PageSize,
int TotalCount,
int TotalPages
)
{
public bool HasPreviousPage => Page > 1;
public bool HasNextPage => Page < TotalPages;
}Be careful with integer division when calculating TotalPages. For 101 records and a page size of 25, the result must be five pages.
var totalPages = (int)Math.Ceiling(
totalCount / (double)pageSize);Total count is useful to clients, but it can be an expensive query. With complex filters, the cost of CountAsync should be measured separately. For infinite-scroll scenarios, omitting the total count and returning only a HasMore value may be more efficient.
4. Building the filtering and sorting query
Now build the query step by step. Applying filters to IQueryable does not immediately send a request to the database. Query construction continues until a terminal operation such as CountAsync or ToListAsync is called.
[HttpGet]
public async Task<ActionResult<PagedResult<ProductListItemDto>>> GetProducts(
[FromQuery] ProductQueryParameters parameters,
CancellationToken cancellationToken)
{
var page = parameters.EffectivePage;
var pageSize = parameters.EffectivePageSize;
IQueryable<Product> query = _db.Products
.AsNoTracking()
.Where(p => p.IsActive);
if (parameters.CategoryId.HasValue)
{
query = query.Where(p =>
p.CategoryId == parameters.CategoryId.Value);
}
if (parameters.MinPrice.HasValue)
{
query = query.Where(p =>
p.Price >= parameters.MinPrice.Value);
}
if (parameters.MaxPrice.HasValue)
{
query = query.Where(p =>
p.Price <= parameters.MaxPrice.Value);
}
if (!string.IsNullOrWhiteSpace(parameters.Search))
{
var search = parameters.Search.Trim();
query = query.Where(p =>
p.Name.Contains(search));
}
query = parameters.SortBy.ToLowerInvariant() switch
{
"price" => parameters.Desc
? query.OrderByDescending(p => p.Price).ThenBy(p => p.Id)
: query.OrderBy(p => p.Price).ThenBy(p => p.Id),
"created" => parameters.Desc
? query.OrderByDescending(p => p.CreatedAt).ThenBy(p => p.Id)
: query.OrderBy(p => p.CreatedAt).ThenBy(p => p.Id),
_ => parameters.Desc
? query.OrderByDescending(p => p.Name).ThenBy(p => p.Id)
: query.OrderBy(p => p.Name).ThenBy(p => p.Id)
};
var totalCount = await query.CountAsync(cancellationToken);
var items = await query
.Skip((page - 1) * pageSize)
.Take(pageSize)
.Select(p => new ProductListItemDto(
p.Id,
p.Name,
p.Price,
p.Category.Name))
.ToListAsync(cancellationToken);
var totalPages = (int)Math.Ceiling(totalCount / (double)pageSize);
return Ok(new PagedResult<ProductListItemDto>(
items,
page,
pageSize,
totalCount,
totalPages));
}The client-provided sort field is not inserted directly into a SQL expression. Instead, a switch maps it to a known set of properties. This is safer and prevents unsupported fields from entering the query accidentally.
Adding ThenBy(p => p.Id) is especially important. If the query is ordered only by price or name, records with equal values may have an unstable order. A unique secondary ordering reduces the chance of records being repeated or skipped between pages.
5. Limits of Skip and Take
With offset pagination, the second page skips the records from the first page. On SQL Server, this approach is generally translated into OFFSET and FETCH. As the page number grows, the database may need to process and discard more rows. For example, jumping to page 10,000 may require evaluating a large number of preceding rows.
Offset pagination also becomes less predictable when the data changes while a user moves between pages. Inserting a new product or deleting an existing one can cause the next page to overlap with the previous page or skip records.
Offset pagination is appropriate when:
- Users need to jump directly to a specific page.
- The result set and offset values are reasonably sized.
- The application uses a traditional paging interface, such as an administration panel.
Keyset pagination may be a better option for very large result sets where users only move forward or backward. For example, the API can return the last product’s Id, and the next request can use Where(p => p.Id > lastId). This makes jumping directly to page 500 difficult, but finding the next indexed records can be more efficient.
6. Measuring query time, response size, and memory
After implementing pagination, measuring only HTTP response time is not enough. At least three comparisons should be made:
| Measurement | Cost being examined |
|---|---|
| Query duration | Database filtering, sorting, and paging cost |
| Response size | JSON serialization and network transfer |
| Memory usage | Holding and processing results in the application |
For comparison, test the endpoint without pagination, then with pageSize=25, pageSize=100, and a high page number. Use the same data set, filters, and ordering for each test. Measurements made against a development database containing a few hundred rows may not represent production behavior with millions of rows.
Inspect the SQL generated by EF Core through logging or database query tools. Use the execution plan to determine whether filter and ordering columns align with appropriate indexes. Also remember that CountAsync and the paged ToListAsync normally produce two separate SQL queries.
7. Common mistakes
- Leaving page size unlimited: A client could request 1,000,000 records. Always define a maximum.
- Using Skip without ordering: Pages are not reliable without deterministic ordering.
- Concatenating dynamic sort input: Map user input to explicitly allowed properties instead of turning it into SQL text.
- Making CountAsync mandatory in every scenario: Infinite-scroll endpoints may not need a total count.
- Applying filters after ToListAsync: This filters in memory and moves the large result set into the application first.
- Returning entities: Use projection for list endpoints so unnecessary columns and relationships are not transferred.
- Ignoring search index behavior: The cost of
Containsdepends on the database, collation, and search pattern.
8. Short practice exercise
Extend the existing product endpoint with the following requirements:
- Add
Page,PageSize,Search,CategoryId,MinPrice, andMaxPriceparameters. - Limit
PageSizeto a maximum of 50. - Support ascending and descending ordering by name, price, and creation date.
- Return only
Id,Name,Price, and category name through a DTO. - Include total count, total pages, current page, and next-page information in the response.
- Compare the paged and unpaged endpoints using test data containing at least 10,000 products.
- Inspect the execution plan and identify suitable indexes for the filters and ordering columns.
Conclusion
In this lesson, we designed a product-listing API that can manage large result sets in a controlled and measurable way. We grouped query-string parameters in a model, pushed filters to the database, explicitly mapped supported sort fields, and selected only the required data through projection. We also created a reusable response model containing total count and page metadata.
Skip and Take are useful when random page access is required, but their cost can increase with high offsets and frequently changing data. For large-scale forward and backward navigation, keyset pagination should be considered. Finally, validate the optimization not only by checking that the code works, but by measuring query duration, response size, memory usage, and execution plans.
Sources
- https://learn.microsoft.com/en-us/ef/core/querying/pagination
- https://learn.microsoft.com/en-us/ef/core/performance/efficient-querying
- https://learn.microsoft.com/en-us/aspnet/core/mvc/models/model-binding?view=aspnetcore-10.0
- https://learn.microsoft.com/en-us/aspnet/core/web-api/action-return-types?view=aspnetcore-7.0