From PostgreSQL to ElasticSearch: The Power of CQRS in Real Projects
Why separating reads and writes can lead to simpler, faster systems
I recently watched some videos by Golo Roden from the native web GmbH on his YouTube channel, and they sparked some thoughts around CQRS and Event Sourcing.
Let’s take a practical example: implementing a marketplace where users can search for bicycles.
In such a system, you usually have two very different concerns—writing data (like creating or updating listings) and reading data (like searching for bikes based on filters). That’s where the CQRS (Command Query Responsibility Segregation) pattern comes into play.
The idea is simple but powerful: split your application into two parts. The write side handles commands—data changes—and writes to a relational database like PostgreSQL. PostgreSQL offers strong consistency, referential integrity, and powerful features like constraints and transactions. It’s the ideal choice for managing critical business data with precision.
On the read side, you want to provide a smooth and fast experience when users are searching for bikes. This is where ElasticSearch enters the picture.
The data is denormalized and synced from PostgreSQL into ElasticSearch. Denormalized means it's tailored for fast access: no complex joins, no foreign key lookups, just flat and queryable data.
The biggest advantage? Your queries become much simpler. You get automatic indexing, which is a huge time saver. Need full-text search across multiple fields? Done. Want to aggregate results by location, brand, or price range? ElasticSearch handles that effortlessly. These are things that would require non-trivial SQL and manual index tuning in PostgreSQL.
So with CQRS and ElasticSearch, you decouple complex domain logic from high-performance querying. You get strong guarantees on the write side and fast, flexible queries on the read side.
And now you: Have you used CQRS with ElasticSearch in your projects?