API with NestJS #125. Offset and keyset pagination with Kysely

NestJS SQL

This entry is part 125 of 180 in the API with NestJS

So far, when working with Kysely, we fetched all rows from our tables. However, this might not be the best solution when it comes to performance. A common approach is to query the data in parts and present the users with separate pages or infinite scrolling. We implement pagination in this article with NestJS, PostgreSQL, and Kysely to achieve that. While doing that, we compare various solutions and point out their pros and cons.

Offset and limit

First, let’s look at the result of a simple SELECT query.

It queries all rows from the table.

The crucial thing about the above results is that the order of the returned records is not guaranteed. However, when implementing pagination, we need the order to be predictable. Therefore, we have to sort the results.

The first step in implementing pagination is to limit the number of rows in the result. To do that, we need the function.

Thanks to the above, we now get only five elements instead of the whole contents of the table. By doing that, we get the first page of the results.

To get to the second page, we must skip a certain number of rows. To achieve that, we need the function.

Above, we omit the first five rows and get the five next rows in return thanks to combining the and functions. In this case, it gives us the rows with IDs from 6 to 10. It is crucial to maintain a steady order of rows when traversing through various pages of data to avoid skipping some rows or showing some of them more than once.

Counting the number of rows

It is a common feature to present the number of data pages to the user. For example, if we have a hundred rows and show ten per page, we have ten data pages.

To determine that, we need to know the number of rows in the table. To do that, we need the function.

It is crucial to count the rows in the database in the same transaction as the query that gets the data. This way, we ensure the consistency of our results.

If you want to know more about transactions with Kysely, check out API with NestJS #123. SQL transactions with Kysely

Offset pagination with NestJS

When implementing the offset pagination with a REST API, we expect the users to provide the offset and limit as query parameters. Let’s create a designated class to handle that.

paginationParams.ts

To read more about validation in NestJS, read API with NestJS #4. Error handling and data validation

We can now use the above class in our controller to validate the offset and limit parameters.

articles.controller.ts

The last step is to implement the offset and limit pagination in our repository.

articles.repository.ts

Thanks to the above approach, we get a full working offset-based pagination.

Advantages

The offset-based pagination is a very common approach that is straightforward to implement. When using it, the user can easily skip multiple data pages at once. It also makes it easy to change the columns we use when sorting. Therefore, it is a good enough solution in many cases.

Disadvantages

Unfortunately, the offset-based pagination has significant disadvantages. The most important one is that the database must compute all rows skipped through the offset. This can hurt our performance:

  • the database sorts all rows according to the specified order,
  • then, it drops the number of rows defined in the offset.

Aside from that, we can experience issues with a lack of consistency:

  1. the user number one fetches the first page with articles,
  2. the user number two creates a new article that ends up on the first page,
  3. the user number one fetches the second page.

The above situation causes user number one to miss the new article added to the first page. They also see the last element from the first page again on the second page.

Keyset pagination

An alternative approach to pagination involves filtering the data with the function instead of the . Let’s consider the following query:

In the above results, we can see that the last row has an ID of . We can use this information to query articles with an ID bigger than .

We should use the same column both for odering and for filtering with the function.

To get the next chunk of results, we need to look at the results and notice that the id of the last row is . We can use that when calling the function.

This exposes the most significant disadvantage of the keyset pagination, unfortunately. To get the next data page, we need to know the ID of the last element of the previous page. Because of that, we can’t traverse more than one page at once.

Keyset pagination with NestJS

To implement the keyset pagination with NestJS, we need to start by accepting an additional query parameter.

paginationParams.ts

We can now modify our repository and use the above parameter.

articles.repository.ts

Advantages

With the keyset pagination, we can experience a significant performance improvement over the offset-based pagination, especially when dealing with large data sets. Additionally, it solves the data inconsistency problem we can sometimes experience with offset pagination. When the user adds or removes rows, it does not cause elements to be skipped or duplicated when fetching the pages.

Disadvantages

The most significant disadvantage of the keyset pagination is that the users must know the id of the row they want to start with. Fortunately, we could solve this problem by mixing the keyset pagination with the offset-based approach.

Also, the column used for filtering should have an index for an additional performance boost. Thankfully, PostgreSQL creates an index for every primary key, so keyset pagination should perform well when using IDs.

Additionally, ordering the results by text columns might not be straightforward when using natural sorting. If you want to read more, look at this question on StackOverflow.

Summary

In this article, we’ve gone through two different pagination solutions we can use with Kysely and PostgreSQL. Considering their pros and cons, we can see that each solution is valid for some use cases. While the keyset pagination is more restrictive, it provides a performance boost. Thankfully, we can mix different approaches to pagination. Combining the keyset and offset pagination can cover a wide variety of cases and provide us with the advantages of both solutions.

Series Navigation<< API with NestJS #124. Handling SQL constraints with KyselyAPI with NestJS #126. Improving the database performance with indexes and Kysely >>
Subscribe
Notify of
guest
1 Comment
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Esteban
Esteban
1 year ago

Amazing set of articles! I already shared this with my colleges!