How To Do Pagination in Postgres With Golang in 4 Common Ways - by Iman Tumorang - Easyread
How To Do Pagination in Postgres With Golang in 4 Common Ways - by Iman Tumorang - Easyread
Search Write
568 10
Membership
Free
Access the best member-only stories.
of the world.
Hi again everyone, it’s been a long time since I haven’t published any article.
There are a lot of things happening, like the pandemic and much more stuff.
This pandemic is affecting me mentally like this self-quarantine is
Membership
exhausting
Free and stressing me. I hope this Covid-19 pandemic will be ended
Access the best member-only stories.
before Christmas this year. 😭
Distraction-free reading. No ads. Support independent authors.
a better way, a vast experience than me, put your comments below
Try for yaa!!
$5/month
TBH, I never cared more details about this in my previous job because we all
had the same perspective, and we only like to have 10 engineers in my
previous company, so we could have the same perspective. But now I care
about this since we have a lot of engineers in my current job, and everyone
has a different perspective.
So, I’m just curious, what’s the better way to build pagination on Postgres on
top of the application, with my case, I’m using Golang for the application.
Sign
In thisup to discover
article, I’ll only human stories
cover those thatpaginations
two style deepen yourin 4 understanding
different
common ways that Backend engineer of the usually
world.does, or at least what I know so
far since I know how to code.
Membership
Do pagination with page number, pretty common; the user only sends
Free
the page number, and we handle it internally; I use offset at the database
Access the best member-only stories.
level.
Distraction-free reading. No ads. Support independent authors.
Do pagination with offset and limit, pretty common since the RDBMS
Organize your knowledge with lists and Listen to audio narrations.
features.
highlights.The user will directly send the offset number from the query
Read offline.
param.
Tell your story. Find your audience.
Join the Partner Program and earn for
Do pagination with a simple query with an your
autowriting.
incremental ID as the PK,
Sign up for
quite common forfree
auto incremental ID in the database. Which is the ID is
treated as the cursor. Try for $5/month
Do pagination with UUID as the PK combined with the created
timestamp, also known as the seek-pagination method or keyset
pagination method. And the combined key will be hashed into a cursor
string.
TL;DR
All the code used here has already been pushed to my Github repository,
github.com/bxcodec/go-postgres-pagination-example
SignConclusions
up to discover
can behuman stories
seen at the that
bottom deepen
of this your understanding
article
of the world.
Membership
Pagination On REST API
Free
Access the best member-only stories.
To give you some context, *in case you don’t know what pagination is used for.
Distraction-free
Pagination is used reading. No ads. your response, LOL.
to paginate Support independent
Well, I don’tauthors.
know how to
rephrase it better.
Organize your knowledge with lists and Listen to audio narrations.
highlights.
Read offline.
Tell your story. Find your audience.
I’ll create an example; let’s say I have this endpoint in REST API.
Join the Partner Program and earn for
your writing.
From a database perspective, querying all the records will takes time a lot. I
can imagine how long it will be if we have a million records and fetch all the
data. So, in that case, people introduce what they called pagination. It works
like pages on the books, that each page contains a bunch of words.
But for this endpoint, each page will contain a list of payment details, so we
can still fetch the payment faster but maybe it will truncated into multiple
pages until we can fetch all the payment records.
Membership
YouFree
may have seen this style in any endpoint, or maybe something like this
Access the best member-only stories.
as well.
Distraction-free reading. No ads. Support independent authors.
Have you seen pagination like those above? TBH, I never have seen any
pagination like those, not in public API if I remember correctly. But, I’ve ever
created pagination with that’s style, around 4 years ago, on my first job-test
after graduated.
First I’ll set the default limit, let’s say 10. Per page is 10 items.
Membership
And each page number will be multiplied to the default limit
Free
Access the best member-only stories.
Then I’ll use it as the offset to the database.
Distraction-free reading. No ads. Support independent authors.
Membership
Free
Access the best member-only stories.
But the benefit of using this method, the user feels like opening a book, they
will just need to pass the page number.
2. Pagination with Offset and Limit
Pagination with offset and limit is quite common to engineers. This comes
because of the feature of RDBMS that supports offset and limit for querying.
From the application level, there’s no extra logic, just passing the offset and
limit to the database, and let the database do the pagination.
Free
Access
And from database level, which is RDBMS, it will thelike
look best member-only
this below, stories.
Benchmark Result
Sign up to discover human stories that deepen your understanding
of the world.
Membership
Free
Access the best member-only stories.
GET /payments?limit=10
GET /payments?limit=10&cursor=last_id_from_previous_fetch
GET /payments?limit=10&cursor=last_id_from_previous_fetch
Sign up to discover human stories that deepen your understanding
... etc
of the world.
How it looks like in database query level
Membership
Free
SELECT Access the best member-only stories.
*
FROMDistraction-free reading. No ads. Support independent authors.
payments
WHERE
Organize your knowledge with lists and Listen to audio narrations.
Id > 10
highlights.
LIMIT 20 Read offline.
Tell your story. Find your audience.
Join the Partner Program and earn for
your writing.
Or for descending
Sign up for free
SELECT
*
FROM
payments
WHERE
Id < 100
ORDER BY Id DESC
LIMIT 20
Benchmark Result
Membership
Free
Access the best member-only stories.
The only drawback of this pagination method is, that when using the
auto-increment id, it will be problematic in the world of microservice
and distributed systems.
Like id with 20 can exist in Service Payment and Service User. It’s unique
in the same application context. It will be different if each ID uses UUID,
it’s “practically unique” (which means there’s a very small possibility of
duplicate generated UUID). So some people are trying to use UUID
instead of PK. Read more details about UUID and auto-increment keys
here
SignEasy
uptotoimplement, no need to do complex logic things in the server.
discover human stories that deepen your understanding
of that
The best way to do pagination the Iworld.
know so far performance-wise since
it’s using autoincrement ID.
Membership
Free
Access the best member-only stories.
4. Pagination with
Distraction-free UUID
reading. NoCombined
ads. with Created Timestamp
Support independent authors.
Organize
I’m not sure your
thisknowledge
is prettywith lists and
common, Listen
but I see that to audio
a few narrations.
articles do this kind
highlights.
of pagination. The context is that the table is not using
Read offline.auto incremental id,
Tell your story. Find your audience.
but it’s using the UUID instead. But then peopleJoin
wonder how
the Partner to do
Program and earn for
your writing.
pagination, adding a new column with auto incremental number is a wasting
resource. So Sign
for up for free what I do is, use the created timestamp of my rows
myself,
and combine it with the PK, which is the UUID. Try for $5/month
This is the database schema
Membership
Free
Access the best member-only stories.
I’ll use the UUID, which is my primary key and combine it with create
timestamp
And return that encoded string as a cursor for the next page, so the user
can use it to fetch the next page of their request.
Membership
Free
Access the best member-only stories.
Membership
Free
Access the best member-only stories.
Organize
And this your knowledge
is what it lookswith
likelists
inand Listen to audio narrations.
the REST endpoint.
highlights.
Read offline.
Tell your story. Find your audience.
Join the Partner Program and earn for
GET /payments?limit=10 your writing.
GET /payments?limit=10&cursor=base64_string_from_previous_result
GET Sign up for free
/payments?limit=10&cursor=base64_string_from_previous_result
... etc
Try for $5/month
But in the database, the query will look like this,
SELECT *
FROM payments
WHERE created_time <= '2020-05-16 03:15:06' // created timestamp
AND id < '2a1aa856-ad26-4760-9bd9-b2fe1c1ca5aa' // this is UUID
ORDER BY created_time DESC, id DESC
LIMIT 2
Benchmark Result
Membership
Free
Access the best member-only stories.
Membership
Free
Access the best member-only stories.
The performance is consistent from the beginning until querying the last
page of the data
Conclusions
Sign upafter
Alright, to discover
doing all human stories that
the benchmarks, deepen
I’ve come yourconclusions.
to some understanding
of the world.
1. Performances: Faster to Slower
From the benchmark results (using the Golang benchmark tool), the faster
one is using the autoincrement PK. See the chart below; the smaller, the
Membership
faster the chart for the average time needed for each operation in
Free
nanoseconds. This chart is might not be a goodAccess the best member-only
representation, stories.be
it should
betterDistraction-free
if I make itreading.
in 95th, 97th, etc percentile, Support
No ads. but I got this value
independent from the
authors.
benchmark
Organize result. So I assume
your knowledge this is already good
with lists and enough
Listen to for the
audio narrations.
highlights.
representation. Read offline.
Tell your story. Find your audience.
Join the Partner Program and earn for
your writing.
Membership
Free
Access the best member-only stories.
Organizewith
Pagination your knowledge with lists and
autoincrement Listen to audio
ID is faster, followed narrations.
by UUID/created time,
highlights.
and PageNumber and LimitOffset. And this is only with 100K rows of data.
Read offline.
Tell your story. Find your audience.
And it will grow bigger as the data grow as well. Sothewith
Join only
Partner 100K
Program anddata, even
earn for
your writing.
if it is still under 1 second, the differences are already quite high when using
Signcompared
autoincrement up for free to limit offset.
Try for $5/month
2. Development: Faster to Slower
Implementation difficulties from easy to hard
Using Offset, because we just only pass the offset and limit directly to the
database.
Using autoincrement ID
Code artifacts
For the code, I’ve pushed it to my GitHub repository, which can be found
here, https://github.com/bxcodec/go-postgres-pagination-example
Author Suggestion
Membership
As a software engineer and as the author of this article, I recommend using
Free
autoincrement ID when doing pagination, but Access
if yourthesystem or you stories.
best member-only don’t
want to use autoincrement ID as the PK, you may
Distraction-free reading. No ads.
consider using keyset
Support independent authors.
pagination; in my case using UUID + created_time timestamp.
Organize your knowledge with lists and Listen to audio narrations.
highlights.
Read offline.
Tell your story. Find your audience.
Join the Partner Program and earn for
your writing.
Organize
More from Imanyour knowledge
Tumorang andwith lists and
Easyread Listen to audio narrations.
highlights.
Read offline.
Tell your story. Find your audience.
Join the Partner Program and earn for
your writing.
Just Call Your Code Only Once !! Mount file to Kubernetes Pod
Sign upPattern
Singleton to discover
in Go human stories that deepen
Without yourtheunderstanding
Deleting Existing File
of the world.
What I learned about Kubernetes when trying
to mount config maps into a docker containe…
Membership
Free
Access the best member-only stories.
Sign
Lists up to discover human stories that deepen your understanding
of the world.
General Coding Knowledge Stories to Help You Grow as a
20 stories · 1235 saves Software Developer
19 stories · 1072 saves
Membership
Leadership Good Product Thinking
Free 50 stories · 336 saves 11 stories · 582 saves
Access the best member-only stories.
Membership
Free
Access the best member-only stories.
See more recommendations
Distraction-free reading. No ads. Support independent authors.