Cochise Ruhulessin
Cochise Ruhulessin

Reputation: 1101

CQRS/Event Sourcing: How to enforce data-integrity?

If I implement CQRS and Event Sourcing, how do I maintain the integrity and consistency of the data, assuming the final storage (read storage) of the data is in a RDBMS?

What if a an event is published but the RDBMS rejects the data derived from it, because of a check violation or missing FK reference?

Upvotes: 2

Views: 1418

Answers (2)

MikeSW
MikeSW

Reputation: 16368

CQRS implies at least 2 models: write and read. Both can be stored in the same db or in different dbs. With ES , you're using an event store which can be itself implemented on top of a rdbms (in .net there is NEventStore which afaik works with many databases rdbms or not).

You're saying you have the read model in a rdbms, that's great. Nothing needs to be enforced because it is the read model, nobody outside the model updater touches that. The app clients can ONLY query that model, never modify it. That's why you have 2 models in the first place so that the Domain would work with the 'write' model while the rest of the app works with the 'read' model.

Also, the RDBMS shouldn't really reject anything. An event handler should be idempotent so if, let's say, the handler inserts something with an id that should be unique, the second invocation should simply ignore any unique constraint violation. With CQRS you're using the RDBMS constraints to support idempotency, not to implement some business rule.

Also, think of the read model as the 'throw away model', that can be anytime changed or rebuilt.

Upvotes: 5

GraemeMiller
GraemeMiller

Reputation: 12263

Our read models are very simple. We don't have foriegn keys in them so that isn't possible. Why would you need foriegn keys? You may have foriegn key values but you don't need constraints as that is enforced by your domain model. You are really only reading and can rebuild all the read store if required.

Upvotes: 2

Related Questions