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.
1const databaseResponse = await this.database
2 .selectFrom('articles')
3 .selectAll()
4 .execute();It queries all rows from the articles 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.
1const databaseResponse = await this.database
2 .selectFrom('articles')
3 .orderBy('id')
4 .selectAll()
5 .execute();The first step in implementing pagination is to limit the number of rows in the result. To do that, we need the limit() function.
1const databaseResponse = await this.database
2 .selectFrom('articles')
3 .orderBy('id')
4 .limit(5)
5 .selectAll()
6 .execute();Thanks to the above, we now get only five elements instead of the whole contents of the articles 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 offset() function.
1const databaseResponse = await this.database
2 .selectFrom('articles')
3 .orderBy('id')
4 .limit(5)
5 .offset(5)
6 .selectAll()
7 .execute();Above, we omit the first five rows and get the five next rows in return thanks to combining the limit() and offset() 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 count() function.
1const { count } = await this.database
2 .selectFrom('articles')
3 .select((expressionBuilder) => {
4 return expressionBuilder.fn.countAll().as('count');
5 })
6 .executeTakeFirstOrThrow();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
1const databaseResponse = await this.database
2 .transaction()
3 .execute(async (transaction) => {
4 const articlesResponse = await transaction
5 .selectFrom('articles')
6 .orderBy('id')
7 .limit(5)
8 .offset(5)
9 .selectAll()
10 .execute();
11
12 const { count } = await transaction
13 .selectFrom('articles')
14 .select((expressionBuilder) => {
15 return expressionBuilder.fn.countAll().as('count');
16 })
17 .executeTakeFirstOrThrow();
18
19 return {
20 data: articlesResponse,
21 count,
22 };
23 });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.
1import { IsNumber, Min, IsOptional } from 'class-validator';
2import { Type } from 'class-transformer';
3
4export class PaginationParams {
5 @IsOptional()
6 @Type(() => Number)
7 @IsNumber()
8 @Min(0)
9 offset: number = 0;
10
11 @IsOptional()
12 @Type(() => Number)
13 @IsNumber()
14 @Min(1)
15 limit: number | null = null;
16}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.
1import {
2 Controller,
3 Get,
4 Query,
5 UseInterceptors,
6 ClassSerializerInterceptor,
7} from '@nestjs/common';
8import { ArticlesService } from './articles.service';
9import { GetArticlesByAuthorQuery } from './getArticlesByAuthorQuery';
10import { PaginationParams } from './dto/paginationParams.dto';
11
12@Controller('articles')
13@UseInterceptors(ClassSerializerInterceptor)
14export class ArticlesController {
15 constructor(private readonly articlesService: ArticlesService) {}
16
17 @Get()
18 getAll(
19 @Query() { authorId }: GetArticlesByAuthorQuery,
20 @Query() { offset, limit }: PaginationParams,
21 ) {
22 return this.articlesService.getAll(authorId, offset, limit);
23 }
24
25 // ...
26}The last step is to implement the offset and limit pagination in our repository.
1import { Database } from '../database/database';
2import { Article } from './article.model';
3import { Injectable } from '@nestjs/common';
4
5@Injectable()
6export class ArticlesRepository {
7 constructor(private readonly database: Database) {}
8
9 async getAll(offset: number, limit: number | null) {
10 const { data, count } = await this.database
11 .transaction()
12 .execute(async (transaction) => {
13 let articlesQuery = transaction
14 .selectFrom('articles')
15 .orderBy('id')
16 .offset(offset)
17 .selectAll();
18
19 if (limit !== null) {
20 articlesQuery = articlesQuery.limit(limit);
21 }
22
23 const articlesResponse = await articlesQuery.execute();
24
25 const { count } = await transaction
26 .selectFrom('articles')
27 .select((expressionBuilder) => {
28 return expressionBuilder.fn.countAll().as('count');
29 })
30 .executeTakeFirstOrThrow();
31
32 return {
33 data: articlesResponse,
34 count,
35 };
36 });
37
38 const items = data.map((articleData) => new Article(articleData));
39
40 return {
41 items,
42 count,
43 };
44 }
45
46 // ...
47}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:
- the user number one fetches the first page with articles,
- the user number two creates a new article that ends up on the first page,
- 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 where() function instead of the offset(). Let’s consider the following query:
1const databaseResponse = await this.database
2 .selectFrom('articles')
3 .orderBy('id')
4 .limit(5)
5 .selectAll()
6 .execute();In the above results, we can see that the last row has an ID of 5. We can use this information to query articles with an ID bigger than 5.
1const databaseResponse = await this.database
2 .selectFrom('articles')
3 .orderBy('id')
4 .where('id', '>', 5)
5 .limit(5)
6 .selectAll()
7 .execute();We should use the same column both for odering and for filtering with the where() 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 10. We can use that when calling the where() 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.
1import { IsNumber, Min, IsOptional } from 'class-validator';
2import { Type } from 'class-transformer';
3
4export class PaginationParams {
5 @IsOptional()
6 @Type(() => Number)
7 @IsNumber()
8 @Min(0)
9 offset: number = 0;
10
11 @IsOptional()
12 @Type(() => Number)
13 @IsNumber()
14 @Min(1)
15 limit: number | null = null;
16
17 @IsOptional()
18 @Type(() => Number)
19 @IsNumber()
20 @Min(0)
21 idsToSkip: number = 0;
22}We can now modify our repository and use the above parameter.
1import { Database } from '../database/database';
2import { Article } from './article.model';
3import { Injectable } from '@nestjs/common';
4
5@Injectable()
6export class ArticlesRepository {
7 constructor(private readonly database: Database) {}
8
9 async getAll(offset: number, limit: number | null, idsToSkip: number) {
10 const { data, count } = await this.database
11 .transaction()
12 .execute(async (transaction) => {
13 let articlesQuery = transaction
14 .selectFrom('articles')
15 .where('id', '>', idsToSkip)
16 .orderBy('id')
17 .offset(offset)
18 .selectAll();
19
20 if (limit !== null) {
21 articlesQuery = articlesQuery.limit(limit);
22 }
23
24 const articlesResponse = await articlesQuery.execute();
25
26 const { count } = await transaction
27 .selectFrom('articles')
28 .select((expressionBuilder) => {
29 return expressionBuilder.fn.countAll().as('count');
30 })
31 .executeTakeFirstOrThrow();
32
33 return {
34 data: articlesResponse,
35 count,
36 };
37 });
38
39 const items = data.map((articleData) => new Article(articleData));
40
41 return {
42 items,
43 count,
44 };
45 }
46
47 // ...
48}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.