CQRS (Command Query Responsibility Segregation) tách biệt model cho write (Command) và read (Query).
Kafka là event bus lý tưởng để kết nối hai side:
- Command side: nhận command (CreateOrder), validate, update write model (DB), publish event (OrderCreated) lên Kafka;
- Event consumer: subscribe Kafka topic, xử lý event để update read model (search index, cache, materialized view phù hợp cho query);
- Query side: đọc từ read model đã được optimize (Elasticsearch cho full-text search, Redis cho low-latency lookup, PostgreSQL view cho reports)
Lợi ích: write và read model có thể scale độc lập; read model optimize cho access pattern cụ thể; dễ add thêm read model mới mà không ảnh hưởng write side. Nhược điểm: eventual consistency — sau khi write, read model chưa update ngay (thường < 100ms nhưng phải communicate với user).
Cần careful UX: sau khi user tạo order, show optimistic UI thay vì đọc lại từ DB ngay.
CQRS (Command Query Responsibility Segregation) separates the write model (Command) from the read model (Query).
Kafka is an ideal event bus connecting the two sides:
- Command side: receives a command (CreateOrder), validates it, updates the write model (DB), and publishes an event (OrderCreated) to Kafka;
- Event consumer: subscribes to the Kafka topic and processes events to update read models (search index, cache, or a materialized view optimized for queries);
- Query side: reads from the optimized read model (Elasticsearch for full-text search, Redis for low-latency lookups, a PostgreSQL view for reports)
Benefits: write and read models can scale independently; read models are optimized for specific access patterns; new read models can be added without impacting the write side. Drawbacks: eventual consistency — after a write, the read model is not updated immediately (usually < 100ms, but must be communicated to users).
Careful UX is required: after a user creates an order, show an optimistic UI rather than immediately re-querying the DB.