CQRS
medium 30 minCQRS means Command Query Responsibility Segregation.
See it run
Follow a command to the write store, an event to the read store, and a query back to the user.
Operations
Command
CreateOrder changes the write side, then the view follows.
Step 1 of 6
User submits a command
CreateOrder
CreateOrder: user U001, items A and B, total 150.
Step 1: User submits a command
def handle(cmd): validate(cmd) order = load(cmd.order_id) events = order.create(cmd.items) store.append(cmd.order_id, order.version, events) # a relay publishes the stored events- Joins at read
- None
- View is
- A moment behind
- One model
- joins on each read
The user gets an answer as soon as the events are saved.
In the real world
The same cqrs doing real jobs. Pick one and step through it.
Writes go on, and the views get old.
Step 1 of 4
Normal
No lag
The view is less than a second behind.
Step 1: Normal
Common mistakes
The bugs interviewers watch for, with the fix beside each.
Dual writes
criticalA crash between the two writes leaves the view wrong for ever.
Wrongdb.save(order)broker.publish(event)Rightwith db.transaction(): db.save(order) db.save(outbox_row)# a relay publishes the outboxDeciding from the read model
criticalIt may be old, so two people can take the last item.
Wrongif view.stock > 0: sell()Rightitem = load(item_id)item.sell() # the aggregate checksProjections that add blindly
majorA repeated event counts twice.
Wrongview.count += 1Rightif event.position > view.position: view.count += 1 view.position = event.positionCQRS for everything
majorSimple parts become slow to change, with nothing gained.
Wrongusers, settings, tags = cqrs(), cqrs(), cqrs()Rightorders = cqrs() # the part that hurtssettings = one_model()
Interview tips
How to explain it
- One model to change, another to ask.
- Events in between.
- Views are a moment behind.
Memory trick: CQRS
- Commands change state.
- Queries question data.
- Responsibility: one role each.
- Segregation: split models.
Use it when
- Many reads with joins.
- Views over several services.
- Search.
Skip it when
- Simple forms.
- A small team.
- Everyone must see each write at once.