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.
Invest now in Acorns!!! 🚀
Join Acorns and get your $5 bonus!
Acorns is a micro-investing app that automatically invests your "spare change" from daily purchases into diversified, expert-built portfolios of ETFs. It is designed for beginners, allowing you to start investing with as little as $5. The service automates saving and investing. Disclosure: I may receive a referral bonus.
Invest now!!! Get Free equity stock (US, UK only)!
Use Robinhood app to invest in stocks. It is safe and secure. Use the Referral link to claim your free stock when you sign up!.
The Robinhood app makes it easy to trade stocks, crypto and more.
Webull! Receive free stock by signing up using the link: Webull signup.
More Related questions...
