Thursday, November 27, 2025

How to Sync Databases with CQRS ?

 But when we separate read and write databases in 2 different database, the main consideration is sync these two database in a proper way.

So we should sync these 2 databases and keep sync always.

This can be solve by using Event-Driven Architecture. According to Event Driven Architecture, when something update in write database, it will publish an update event with using message broker systems and this will consume by the read database and sync data according to latest changes.

But this solution creates a consistency issue, because since we have implemented async communication with message brokers, the data would not be reflected immediately.

Press enter or click to view image in full size

This will operates the principle of “eventual consistency”. The read database eventually synchronizes with the write database, and it can be take some time to update read database in the async process. We discuss eventual consistency in the next sections.

So if we come back to our read and write databases in CQRS pattern, When starting your design, you can take read database from replicas of write database. By this way we can use different read-only replicas with applying Materialized view pattern can significantly increase query performance.

Also when we separated read and write databases, it means we can scale them independently. That means if our application is read-incentive, I mean if it much more query that write, than we can scale only reading databases very fast.

CQRS comes with separating commands and query databases. So this required to sync both 2 databases with offering event-driven architectures. And with Event-driven architectures there are some new patterns and practices should be consider when applying CQRS.

Event Sourcing pattern is the first pattern we should consider to use with CQRS. Mostly CQRS is using with “Event Sourcing pattern” in Event-Driven Architectures. So after we have learned the CQRS we should learn “Event Sourcing pattern”, because CQRS and “Event Sourcing pattern” is the best practice to use both of them.

Design the Architecture — CQRS, Event Sourcing, Eventual Consistency, Materialized View















No comments:

Post a Comment