Database / CouchDB Interview Questions
What is the _rev field in CouchDB and why is it required for updates and deletes?
The _rev field is CouchDB's revision token — a unique identifier for a specific version of a document. Its format is {generation}-{hash} where generation is a monotonically increasing integer (starting at 1) and hash is an MD5 of the document body. Example: "1-967a00dff5e02add41819138abb3284d". After one update it becomes something like "2-7051cbe5c8faecd085a3fa619e6e6337".
Why it is mandatory for updates and deletes: The _rev is the MVCC optimistic-lock token. CouchDB compares the supplied _rev against what the storage engine holds. A match means the write is based on the current state — the operation proceeds and a new revision is assigned. A mismatch means another writer updated the document since you read it — CouchDB returns HTTP 409 Conflict, preventing silent data loss.
# Read — always capture the returned _rev
curl http://localhost:5984/db/doc1
# {"_id":"doc1","_rev":"1-abc","name":"Alice"}
# Update: supply the exact current _rev in the body
curl -X PUT http://localhost:5984/db/doc1 \
-H "Content-Type: application/json" \
-d '{"_rev":"1-abc","name":"Alice Smith"}'
# Response: {"ok":true,"rev":"2-def"}
# Delete: supply _rev as a query parameter
curl -X DELETE "http://localhost:5984/db/doc1?rev=2-def"
# Writes a tombstone: {"_id":"doc1","_rev":"3-xyz","_deleted":true}
Deleting a document does not remove it physically. CouchDB writes a tombstone — a minimal document with _deleted: true at the next revision — so the deletion event replicates correctly to other nodes. Tombstones are only removed by the _purge API, which bypasses the replication system and should be used with care.
More Related questions...