Event Streaming with MongoDB
Join the DZone community and get the full member experience.Join For Free
mongodb is a really great “nosql” database, with a very wide range of applications. in one project that we are developing at softwaremill , we used it as a replicated event storage, from which we stream the events to other components.
the basic idea is pretty simple (see also martin fowler’s article on event sourcing ). our system generates a series of events. these events are persisted in the event storage. other components in the system follow the stream of events and do “something” with them; for example they can get aggregated and written into a reporting database (this, on the other hand, resembles cqrs ). such an approach has many advantages:
- reading and writing of the events is decoupled (asynchronous)
- any following-component may die and then “catch up”, given that it wasn’t dead for too long
- there may be multiple followers. the followers may read the data from slave replicas, for better scalability
- bursts of event activity have a reduced impact on event sinks; at worst, the reports will get generated slower
the key component here is of course a fast and reliable event storage. the three key features of mongodb that we used to implement one are:
- capped collections and tailable cursors
- fast collection appends
- replica sets
as the base, we are using a capped collection , which by definition is size-constrained. if writing a new event would cause the collection to exceed the size limit, the oldest events are overwritten. this gives us something similar to a circular buffer for events. (plus we are also quite safe from out-of-disk-space errors.)
until version 2.2, capped collection didn’t have an _id field by default (and hence no index). however, as we wanted the events to be written reliably across the replica set, both the _id field and an index on it are mandatory.
writing events is a simple mongo insert operation; inserts can also be done in batches. depending on how tolerant we are of event loss, we may use various mongo write concerns (e.g. waiting for a write confirmation from a single-node or from multiple nodes).
all of the events are immutable. apart from nicer, thread-safe java code, this is a necessity for event streaming; if the events were mutable, how would the event sink know what was updated? also, this has good mongo performance implications. as the data is never changed, the documents that are written to disk never shrink or expand, so there is no need to move blocks on disk. in fact, in a capped collection, mongo doesn’t allow to grow a document that was once written.
reading the event stream is a little bit more complex. first of all, there may be multiple readers, each with a different level of advancement in the stream. secondly, if there are no events in the stream, we would like the reader to wait until some events are available, and avoid active polling. finally, we would like to process the events in batches, to improve performance.
tailable cursors solve these problems. to create such a cursor we have to provide a starting point – an id of an event, from which we’ll start reading; if an id is not provided, the cursor will return events from the oldest one available. thus each reader must store the last event that it has read and processed.
more importantly, tailable cursors can optionally block for some amount of time if no new data is available, solving the active polling problem.
(by the way, the oplog collection that mongo uses to replicate data across a replica set, is also a capped collection. slave mongo instances tail this collection, streaming the “events”, which are database operations, and applying them locally in order.)
reading events in java
when using the mongo java driver , there are a few “catches”. first of all you need to initialise the cursor. to do that, we need to provide (1) the last event id, if present; (2) an order in which we want to read the events (here: natural, that is the insertion order); and (3) two crucial cursor options, that we want the cursor to be tailable, and that we want to block if there’s no new data:
dbobject query = lastreceivedeventid.ispresent() ? basicdbobjectbuilder.start("_id", basicdbobjectbuilder .start("$gte", lastreceivedeventid.get()).get()) .get() : null; dbobject sortby = basicdbobjectbuilder.start("$natural", 1).get(); dbcollection collection = ... // must be a capped collection dbcursor cursor = collection .find(query) .sort(sortby) .addoption(bytes.queryoption_tailable) .addoption(bytes.queryoption_awaitdata);
you may wonder why we used
. that is needed here because of the way mongo objectids are generated. with a simple
we may miss some events that have been generated in the same second as the
event, but after it. this also means that our java code must take care of this fact and discard the first event that was received.
the cursor’s class extends the basic java
interface, so it’s fairly easy to use. so now we can take care of batching. when iterating over a cursor, the driver receives the data from the mongo server in batches; so we may simply call
, as with any other iterator, to receive subsequent elements, and only some calls will actually cause network communication with the server.
in the mongo java driver the call that is actually potentially blocking is
. if we want to process the events in batches, we need to (a) read the elements as long as they are available, and (b) have some way of knowing before getting blocked that there are no more events, and that we can process the events already batched. and as
can block, we can’t do this directly.
that’s why we introduced an intermediate queue (
). in a separate thread, events read from the cursor are put on the queue as they come. if there are no events, the thread will block on
. the blocking queue has an optional size limit, so if it’s full, putting an element will block as well until space is available. in the event-consumer thread, we first try to read a single element from the queue, in a blocking fashion (using
, so here we wait until any event is available). then we try to drain the whole content of the queue to a temporary collection (using
, building the batch, and potentially getting 0 elements, but we always have the first one).
an important thing to mention is that if the collection is empty, mongo won’t block, so we have to fall back to active polling. we also have to take care of the fact that the cursor may die during this wait; to check this we should verify that
cursor.getcursorid() != 0
, where 0 is an id of a “dead cursor”. in such a case we simply need to re-instantiate the cursor.
to sum up, we got a very fast event sourcing/streaming solution. it is “self regulating”, in the sense that if there’s a peak of event activity, they will be read by the event sinks with a delay, in large batches. if the event activity is low, they will be processed quickly in small batches.
we’re also using the same mongo instance for other purposes; having a single db system to cluster and maintain both for regular data and events is certainly great from an ops point of view.
Published at DZone with permission of Adam Warski, DZone MVB. See the original article here.
Opinions expressed by DZone contributors are their own.