Database / CouchDB Interview Questions
What are CouchDB update handlers and how do they differ from direct PUT operations?
Update handlers are server-side JavaScript functions stored in a design document under the updates key. They allow you to perform document transformations atomically on the server without a client round-trip — the client sends a POST request, and the update handler reads the current document, applies business logic, and returns the modified document in a single operation.
// In _design/handlers:
{
"updates": {
"increment_stock": "function(doc, req) {
if (!doc) { doc = { _id: req.id, stock: 0, type: 'item' }; }
var body = JSON.parse(req.body);
doc.stock = (doc.stock || 0) + (body.amount || 1);
doc.last_updated = new Date().toISOString();
return [doc, toJSON({ ok: true, new_stock: doc.stock })];
}"
}
}
# Call the update handler
curl -X POST \
"http://admin:pass@localhost:5984/mydb/_design/handlers/_update/increment_stock/item:001" \
-H "Content-Type: application/json" \
-d '{"amount": 5}'
# {"ok":true,"new_stock":155}
Differences from a direct PUT:
- No client round-trip — the client does not need to first GET the document to read the current
_revand current field values; the handler receives both and returns the updated document. - Atomic transformation — the read, compute, and write happen within a single server-side operation, reducing MVCC conflict probability for frequently-updated counters or timestamps.
- Custom response body — the handler can return any JSON in the response, not just the standard
{"ok":true,"rev":...}. - When not to use them — update handlers are deprecated in CouchDB 3.x (along with list and show functions). The same logic implemented in your application using a read-modify-write loop is more maintainable and testable.
More Related questions...