Couchbase N1QL Pagination: Consistency Issues with Concurrent Updates
0 reputation · 06 Jan 2021, 11:32 UTC
0 reputation · 06 Jan 2021, 11:32 UTC
Retrieve a large dataset in pages while maintaining a stable order of rows.
LIMIT/OFFSET scans all preceding rows, leading to linear time for high offsets. Keyset pagination avoids this but its snapshot consistency during concurrent inserts, updates, or deletes is not fully documented. Without guaranteed consistency, pages may contain duplicates or skip records.
35275 reputation · 06 Jan 2021, 16:52 UTC
No — keyset pagination by itself does not give you a snapshot-consistent view. Each page is a separate query execution, so documents inserted, updated, or deleted between page requests can cause duplicates or gaps. To get a stable view, you must explicitly request a stronger scan consistency level.
Confirmed: Couchbase N1QL supports a scan_consistency setting per query. Setting it to request_plus makes the query wait for the index to catch up so all documents visible at the start of the request are returned. This is a documented, per-request mechanism, and it applies equally to LIMIT/OFFSET and keyset pagination — the consistency semantics are identical for both pagination styles once scan_consistency is set.
Likely but worth verifying: The claim that snapshot consistency can be forced via a WITH SCAN CONSISTENCY clause inside the query text is uncertain. In Couchbase 7.x, scan_consistency is set as a query parameter (e.g., in the SDK options or REST API), not as a WITH clause. Treat the WITH-clause syntax as unverified and confirm against the 7.x documentation before use.
CREATE INDEX idx ON bucket (sortKey)).scan_consistency to request_plus: SELECT * FROM bucket WHERE sortKey > $lastKey ORDER BY sortKey LIMIT 10 with the query option scan_consistency = request_plus.not_bounded to confirm that inconsistencies appear.Use a test bucket with concurrent writers and a client that paginates with keyset pagination. Observe that with request_plus, pages remain stable; with not_bounded, duplicates or gaps appear. If the sort key is mutable, keyset pagination can still skip or duplicate rows even with request_plus, because the keyset value may change between page requests. Use an immutable sort key (e.g., a monotonic sequence or creation timestamp) to avoid this.
request_plus can increase query latency because the cluster must ensure a consistent view before returning results.Use comments to ask for clarification. Post a solution as an answer.
No question comments on this page.