Trung BìnhSystem Design iconSystem Design

CQRS Pattern là gì? Khi nào nên áp dụng và những thách thức gì khi implement? (What is the CQRS Pattern? When should it be applied and what are the challenges?)

CQRS (Command Query Responsibility Segregation) là pattern tách biệt hoàn toàn model đọc (Query) và model ghi (Command) – thay vì một model dùng cho cả CRUD. Command side xử lý mutations và thường dùng domain model phức tạp; Query side tối ưu cho read và có thể dùng denormalized view riêng.

Lợi ích: Read model có thể scale độc lập với Write model; Query side có thể dùng database khác (Elasticsearch cho search, Redis cho cache); mỗi side được tối ưu riêng. Thường kết hợp với Event Sourcing: mỗi Command tạo ra Events, Events cập nhật Read Model (eventual consistency). Phù hợp khi: read/write ratio không cân bằng, domain logic phức tạp, cần nhiều dạng read views khác nhau. Thách thức: eventual consistency giữa write và read side; operational complexity tăng; debugging khó hơn; không phù hợp cho CRUD đơn giản. Ví dụ thực tế: e-commerce – order placement (Command) và order listing dashboard (Query) dùng store riêng biệt.

Xem toàn bộ System Design cùng filter theo level & chủ đề con.

Mở danh sách System Design