Stop Using OFFSET/LIMIT for Deep Pagination in Couchbase N1QL
Stop using OFFSET/LIMIT for deep pagination in Couchbase N1QL. For deep result sets, switch to keyset pagination using indexed fields for consistent, low-latency performance.
25 Apr 2026, 01:35 UTC

Deep Pagination in Couchbase: The Performance Trap
If your application uses OFFSET X LIMIT Y in Couchbase N1QL to fetch results for deep pagination (e.g., page 1000+), you are likely experiencing unpredictable latency spikes and unnecessary resource consumption. The useful takeaway is this: for deep sets, switch immediately to keyset pagination.
The Mechanics of OFFSET Inefficiency
Couchbase N1QL supports OFFSET and LIMIT for subset retrieval. However, OFFSET forces the query engine to scan and discard all rows preceding the requested offset before returning the desired batch. This means performance degrades linearly as the offset increases.
Keyset Pagination: Consistent Performance
Keyset pagination, also known as cursor-based pagination, avoids counting rows. Instead, it uses the value of the last item retrieved (the 'cursor') in a WHERE clause, combined with an ORDER BY clause, to fetch the next page. This maintains near-constant query time regardless of how deep the user navigates.
Worked Example: Switching from Offset to Keyset
Assume you are paginating user records ordered by a unique, indexed id. Instead of:
SELECT * FROM bucket WHERE type='user' ORDER BY id LIMIT 20 OFFSET 10000;Use keyset pagination, tracking the id from the 10000th record (e.g., last_id):
SELECT * FROM bucket WHERE type='user' AND id > $last_id ORDER BY id LIMIT 20;Run EXPLAIN on both queries in Couchbase Query Workbench. You should observe the OFFSET query performing a full scan up to the offset point, whereas the keyset query uses an index seek starting from $last_id.
Trade-off and Limitation
Keyset pagination requires the application to reliably store and pass the last value (the cursor). If the underlying data ordering (the field used in ORDER BY) is not stable—meaning new data can be inserted between pages in a way that changes the sequence—the cursor might skip or duplicate records. This is a data integrity constraint, not a query limitation.
Actionable Next Step
Identify the indexed field used for ordering in your deep queries. Modify the query to use WHERE indexed_field > $last_value instead of OFFSET. Verify correctness by ensuring the returned set is contiguous with the previous set using the application logic.
0 replies
A thoughtful contribution can make all the difference. Be the first to share one.