Database / CouchDB Interview Questions
What is the CouchDB _changes feed and how do you use it for real-time event streaming?
The _changes feed is CouchDB's built-in event stream. It reports every document change (create, update, delete) in a database as a sequence of events, each with a sequence number (seq), document ID (id), list of changed revisions (changes), and optionally the full document body. It is the mechanism that powers replication and can also drive event-driven application architectures.
# One-shot: get all changes since the beginning
curl "http://admin:pass@localhost:5984/mydb/_changes"
# Long-polling: block until at least one change arrives
curl "http://admin:pass@localhost:5984/mydb/_changes?feed=longpoll&since=now"
# Continuous streaming feed (server-sent events style)
curl "http://admin:pass@localhost:5984/mydb/_changes?feed=continuous&since=now&heartbeat=5000"
# Include full document body in each change event
curl "http://admin:pass@localhost:5984/mydb/_changes?feed=continuous&include_docs=true&since=now"
# Resume from a checkpoint (since= is the last seq you processed)
curl "http://admin:pass@localhost:5984/mydb/_changes?feed=continuous&since=45-g1AAAA..."
# Filter by Mango selector (2.x+)
curl -X POST "http://admin:pass@localhost:5984/mydb/_changes?feed=continuous&since=now" \
-H "Content-Type: application/json" \
-d '{"selector":{"type":"order","status":"pending"}}'
Each event looks like:
{"seq":"46-g1AAAA...","id":"order:001","changes":[{"rev":"3-abc"}]}
The seq value is your cursor: always persist the last-processed seq to your consumer state store so you can resume without reprocessing. The continuous feed sends a newline heartbeat at regular intervals to keep HTTP connections alive through proxies. Eventsource (feed=eventsource) wraps changes in the Server-Sent Events format for direct browser consumption.
More Related questions...