Database / CouchDB Interview Questions
How do you paginate results in CouchDB views using startkey, endkey, and skip/limit?
CouchDB views are sorted B-trees, so efficient pagination uses key-based cursoring rather than offset-based skipping. Two approaches exist: offset pagination (simpler but slow at large offsets) and key-based pagination (efficient at any depth).
# ── Approach 1: Offset-based (avoid for deep pages) ──
# Page 1
GET /db/_design/ddoc/_view/by_date?limit=10
# Page 2 (skip=10 forces a full scan of the first 10 rows — slow at scale)
GET /db/_design/ddoc/_view/by_date?limit=10&skip=10
# ── Approach 2: Key-based cursor (recommended for production) ──
# Page 1: fetch limit+1 to detect whether a next page exists
GET /db/_design/ddoc/_view/by_date?limit=11&descending=false
# From the response, take the last row's key and doc ID as the cursor:
# last key = "2024-03-15", last id = "order:0099"
# Page 2: start from the cursor using startkey + startkey_docid
GET /db/_design/ddoc/_view/by_date?startkey=%222024-03-15%22\
&startkey_docid=order%3A0099&limit=11
# Range query — all orders between two dates
GET /db/_design/ddoc/_view/by_date?startkey=%222024-01-01%22\
&endkey=%222024-03-31%22&include_docs=true
skip is implemented by scanning and discarding leading rows — O(n) in the skipped count. At page 500 with page size 20, skip=10000 forces CouchDB to read 10000 index entries before returning 20 results. For large datasets always use the key-cursor approach. The startkey_docid parameter resolves ties when multiple documents share the same emitted key, ensuring the cursor lands on the exact right row.
More Related questions...