Database / CouchDB Interview Questions
What are view indexes in CouchDB and how are they built and updated, including stale options?
A view index in CouchDB is a persistent B-tree file on disk that stores all the key-value pairs emitted by a view's map function across all documents in the database. It is stored separately from the main database file (with a .view extension in the views/ directory). The index is sorted by emitted key, enabling efficient range queries.
Build and update lifecycle:
- First query — if the index does not exist, CouchDB processes every document through the map function and builds the index from scratch. This can be slow for large databases.
- Subsequent queries — CouchDB checks the database's update sequence number. Documents changed since the last index update are re-run through the map function incrementally. The index reflects all committed documents before returning results.
- Design document change — any modification to the design document invalidates the entire index; full rebuild required.
The stale query parameter (CouchDB 1.x) or update parameter (2.x+) controls this behavior:
# Default: wait for index to be fully up to date before returning
GET /db/_design/ddoc/_view/my_view
# Return stale (potentially outdated) results immediately; trigger index update in background
GET /db/_design/ddoc/_view/my_view?stale=update_after # 1.x style
GET /db/_design/ddoc/_view/my_view?update=lazy # 2.x+ style
# Return whatever is in the index right now, do not update
GET /db/_design/ddoc/_view/my_view?stale=ok # 1.x
GET /db/_design/ddoc/_view/my_view?update=false # 2.x+
Using stale=update_after is a common pattern for dashboard queries where slightly stale data is acceptable and you want to avoid blocking the user while the index refreshes.
More Related questions...