Question

I've recently started reading about CQRS, DDD and EventSourcing. From what I've read one of the best ways to do ES is to have an event store and then a regular DB or cache for easier querying. However, something that confuses me is that in some examples I've seen both of these scenarios:

  1. Store in event log first and then persist in a regular DB/Cache
  2. Store in DB/Cache first and then raise an event while appending to the event log

Which one is considered best practice?

Was it helpful?

Solution

In any system where you have a book of record and a cache, you want to be sure that you update the book of record first, and update the cache only if the book of record updates successfully. Notice the focus on the failure modes - on the happy path where everything "just works" the order doesn't particularly matter. But real systems have only a small number of 9s of reliability, so we need to consider how things fail.

If your cache and your book of record are guarded by the same lock, if the updates to the cache and the book of record happen in the same transaction, the order doesn't matter very much because that transaction is going to commit or rollback everything.

The troublesome case is when we need two transactions to get the work done -- we care about the order because we care about the resulting state when the first transaction succeeds and the second transaction fails.

This isn't, of course, specific to event sourcing.

But when we are event sourcing we are more likely to be in a situation where we want two different data stores to update. If we are using the same database as our cache and our event store, then we can use the same transaction to update both with no worries. But if the cache is stored separately from the event store, or if they are stored "together" but using two different transactions... well, the event store is the "book of record" so that update comes first.

Licensed under: CC-BY-SA with attribution
scroll top