Chapter 20. Change Notifications
Say you are building a message service with CouchDB. Each user has an inbox database and other users send messages by dropping them into the inbox database. When users want to read all messages received, they can just open their inbox databases and see all messages.
So far, so simple, but now you’ve got your users hitting the Refresh button all the time once they’ve looked at their messages to see if there are new messages. This is commonly referred to as polling. A lot of users are generating a lot of requests that, most of the time, don’t show anything new, just the list of all the messages they already know about.
Wouldn’t it be nice to ask CouchDB to give you notice when a new
message arrives? The _changes database API does just
that.
The scenario just described can be seen as the cache
invalidation problem; that is, when do I know that what I am
displaying right now is no longer an apt representation of the underlying
data store? Any sort of cache invalidation, not only
backend/frontend-related, can be built using
_changes.
_changes is also designed and suited to extract an
activity stream from a database, whether for simple display or, equally
important, to act on a new document (or a document change) when it
occurs.
The beauty of systems that use the changes API is that they are decoupled. A program that is interested only in latest updates doesn’t need to know about programs that create new documents and vice versa.
Here’s what a changes item looks ...