← Back to SQL, page 23

sql-0454 · Hard senior

What is CQRS, and when would a team keep separate read models in SQL?

Command Query Responsibility Segregation separates the model that handles writes (normalised, enforcing rules) from models optimised for reads (denormalised tables or views shaped for specific screens). Read models are updated from the write side, often asynchronously via events, so they may lag. It helps when read and write needs differ greatly, and adds complexity otherwise.

Full answer

Example: an order system writes to normalised orders, order_lines and payments. A dashboard needs 'orders with customer name, item count, paid amount and last status change', filtered and sorted many ways.

Read model:

text
order_summaries(order_id PK, customer_name, item_count, total_minor, paid_minor,
                status, last_change_at)   -- indexed for the dashboard's filters

Updated by:

  • triggers or the same transaction (synchronous, simpler, consistent), or
  • events from an outbox consumed by a projector (asynchronous, scales out, eventually consistent).

When it pays off: very different read and write volumes, many specialised screens, or reads served from a different store (search engine, cache). When it does not: simple CRUD apps, where a view or a few indexes on the normalised tables are enough.

Rebuilding a read model from the source data (or event log) must be possible, since projections can have bugs.

Key points

  • Separate write and read models
  • Read models are denormalised for screens
  • Updates can be synchronous or event-driven
  • Asynchronous read models lag
  • Must be rebuildable

Common mistakes

  • Applying CQRS to simple CRUD
  • Read models that cannot be rebuilt

Follow-ups

  • How does CQRS relate to materialized views?
  • How would you handle read-your-writes with an async read model?

Tips

  • State when it is not worth it