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.
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...
