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?

  • Sharing your research helps everyone. Tell us what you've tried and why it didn't meet your needs. This demonstrates that you've taken the time to try to help yourself, it saves us from reiterating obvious answers, and most of all it helps you get a more specific and relevant answer. Also see How to Ask
    – gnat
    Apr 25 '20 at 21:23

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.