Introduction
Listing endpoints may look simple with a small dataset, but returning every record at once creates serious performance problems as the data grows. Excessive memory usage, longer response times, increased network traffic, and more client-side processing are common consequences. A professional API divides list results into controlled portions so clients retrieve only the records they need.
In this lesson, we will add offset-based pagination to the Product and Order listing endpoints. Requests will use the page and pageSize query-string parameters, while responses will include page, pageSize, totalCount, totalPages, hasNext, and hasPrevious. We will also enforce default and maximum page sizes, ensure that queries execute in the database, and examine why stable ordering is essential.
1. Designing the pagination contract
The API should first have a predictable contract that client applications can understand. For example, the following request asks for up to 20 products from the second page:
GET /api/products?page=2&pageSize=20
We can define these rules for the request parameters:
- page starts at 1. If it is omitted, the default is 1.
- If pageSize is omitted, the default is 20.
- pageSize is limited to a maximum of 100.
- Invalid or negative values can be normalized to safe defaults or rejected with a consistent validation response.
- Results must always use deterministic and stable ordering.
Instead of returning only an array, wrapping the array with metadata helps clients make navigation decisions:
{ "items": [ { "id": 21, "name": "Keyboard", "price": 49.90 } ], "metadata": { "page": 2, "pageSize": 20, "totalCount": 145, "totalPages": 8, "hasNext": true, "hasPrevious": true } }
totalCount represents the total number of records matching the filters, while totalPages represents the number of pages. The hasNext and hasPrevious fields prevent clients from having to calculate navigation state themselves.
2. Query and metadata models
Instead of handling query-string values directly in a controller, define a request model. This improves readability and gives us a natural place to add filtering and sorting parameters in future lessons.
public sealed class PaginationQuery { private const int DefaultPageSize = 20; private const int MaxPageSize = 100; public int Page { get; init; } = 1; public int PageSize { get; init; } = DefaultPageSize; public int SafePage => Page < 1 ? 1 : Page; public int SafePageSize => PageSize < 1 ? DefaultPageSize : Math.Min(PageSize, MaxPageSize); public int Skip => (SafePage - 1) * SafePageSize; }
SafePage and SafePageSize are calculated properties. This keeps controllers and services from repeating the same validation logic. If the API requires a stricter contract, values such as page=0 or pageSize=1000 can instead produce a 400 Bad Request. The important point is to apply the same behavior consistently across all list endpoints.
public sealed record PageMetadata( int Page, int PageSize, int TotalCount, int TotalPages, bool HasNext, bool HasPrevious); public sealed record PagedResult<T>( IReadOnlyList<T> Items, PageMetadata Metadata);
Using record types makes it clear that these objects are data-transfer models. They can be placed in the Application layer so Product and Order services share the same pagination contract.
3. Calculating metadata
The basic metadata calculation is:
var totalPages = totalCount == 0 ? 0 : (int)Math.Ceiling(totalCount / (double)pageSize); var metadata = new PageMetadata( page, pageSize, totalCount, totalPages, page < totalPages, page > 1 && totalPages > 0);
Using totalPages=0 for an empty result set is a reasonable choice. In that case, both hasNext and hasPrevious are false. Another design may use totalPages=1 for an empty collection, but the selected behavior must be documented clearly.
There are two common approaches when a client requests a page that does not exist, such as page=999. The first returns 200 OK with an empty items array. The second returns 404 or 400. For list APIs, the first approach is often easier to consume because the client does not need a special error flow for an empty page.
4. Efficient querying for the Product endpoint
The Product service should build the base query, calculate the total count, and apply pagination. Ordering, projection, and pagination should remain on IQueryable so Entity Framework Core can translate them into database operations.
public async Task<PagedResult<ProductListItem>> GetProductsAsync( PaginationQuery pagination, CancellationToken cancellationToken) { var page = pagination.SafePage; var pageSize = pagination.SafePageSize; var query = _dbContext.Products .AsNoTracking() .OrderBy(product => product.Id); var totalCount = await query.CountAsync(cancellationToken); var items = await query .Skip((page - 1) * pageSize) .Take(pageSize) .Select(product => new ProductListItem { Id = product.Id, Name = product.Name, Price = product.Price }) .ToListAsync(cancellationToken); return PagedResultFactory.Create(items, page, pageSize, totalCount); }
AsNoTracking reduces change-tracking overhead for read-only list endpoints. The Select projection requests only the fields needed by the client instead of loading every entity column and navigation property. CountAsync, Skip, and Take execute in the database. Loading all rows with ToListAsync and applying Skip afterward is a major mistake.
A shared PagedResultFactory prevents duplicate metadata logic in the Product and Order services:
public static class PagedResultFactory { public static PagedResult<T> Create<T>( IReadOnlyList<T> items, int page, int pageSize, int totalCount) { var totalPages = totalCount == 0 ? 0 : (int)Math.Ceiling(totalCount / (double)pageSize); var metadata = new PageMetadata( page, pageSize, totalCount, totalPages, page < totalPages, page > 1 && totalPages > 0); return new PagedResult<T>(items, metadata); } }
5. The Order listing endpoint
Order lists often need more than raw entity fields. A dedicated summary DTO can expose values such as the customer name, order date, status, and total amount without exposing the complete entity graph.
[HttpGet("orders")] public async Task<ActionResult<PagedResult<OrderListItem>>> GetOrders( [FromQuery] PaginationQuery pagination, CancellationToken cancellationToken) { var result = await _orderService .GetOrdersAsync(pagination, cancellationToken); return Ok(result); }var query = _dbContext.Orders .AsNoTracking() .OrderByDescending(order => order.CreatedAt) .ThenByDescending(order => order.Id); var totalCount = await query.CountAsync(cancellationToken); var items = await query .Skip((page - 1) * pageSize) .Take(pageSize) .Select(order => new OrderListItem { Id = order.Id, CreatedAt = order.CreatedAt, Status = order.Status, TotalAmount = order.TotalAmount }) .ToListAsync(cancellationToken);
CreatedAt may not be unique. Two orders can have the same timestamp, and the database does not necessarily guarantee the same relative order between queries. Therefore, ThenByDescending(order => order.Id) adds a unique secondary ordering key. Stable ordering reduces the risk of records disappearing or appearing twice as clients move between pages.
6. Offset pagination and performance
Skip and Take are practical when clients need to jump directly to a specific page. However, as the page number increases, the database may still need to process many rows before reaching the requested offset. This can become expensive for very large datasets.
We use offset pagination in this lesson because random page access is part of the requirement. For very large or frequently changing tables where forward and backward navigation is sufficient, keyset pagination may be a better option. With keyset pagination, the client sends the last ordering key instead of a page number. For example, the API can request products with an Id greater than the last returned value:
var items = await _dbContext.Products .AsNoTracking() .Where(product => product.Id > lastProductId) .OrderBy(product => product.Id) .Take(pageSize) .Select(product => new ProductListItem { ... }) .ToListAsync(cancellationToken);
Keyset pagination does not naturally provide a total page count. Therefore, if totalCount and totalPages are required by the product contract, offset pagination is usually more appropriate.
7. Common mistakes
- Omitting OrderBy: Relational databases do not guarantee a default row order. Define explicit and unique ordering before applying pagination.
- Allowing unlimited page sizes: A client could send pageSize=1000000 and overload the API. Always enforce default and maximum values.
- Returning entities directly: Internal fields, navigation properties, and database details may leak into the public contract. Use list DTOs.
- Paginating after loading into memory: Apply Skip and Take before calling ToListAsync.
- Counting a paginated query: Call CountAsync before applying Skip and Take.
- Ignoring count and item inconsistencies: Records may be inserted or deleted between the two queries. Metadata is not necessarily an immutable snapshot; evaluate transactions or snapshot strategies for critical reporting scenarios.
8. Short practice exercise
Complete the following exercise:
- Create the PaginationQuery, PageMetadata, and PagedResult<T> types.
- Add page and pageSize parameters to GET /api/products.
- Set the default page size to 20 and the maximum page size to 100.
- Use AsNoTracking, stable OrderBy, CountAsync, Skip, Take, and projection in the Product query.
- Apply the same design to the Order listing endpoint and order by CreatedAt followed by Id.
- Test an empty table, the first page, the last page, the maximum page size, and a request beyond the available pages.
Conclusion
Pagination is not merely about splitting a result set. It requires coordinated design of the client experience, API contract, and database behavior. In this lesson, we created a shared pagination model for Product and Order endpoints, defined metadata fields, enforced default and maximum page sizes, and ensured that queries execute in the database.
In the next stage, you can combine pagination with filtering and sorting to create more flexible listing endpoints. Always consider stable ordering, bounded result sets, DTO projection, and suitable indexes together. This allows the API to remain predictable not only during development, but also under real production workloads.