AlgoViz

CQRS

medium 30 min

CQRS 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

Our systemcommandUserCommand handlerreceivingWrite store0 eventsEvent brokeremptyProjectionidleRead storeno ordersQuery handleridle

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

Our systemUserCommand handleridleWrite store500 eventsEvent brokeremptyProjectionidleRead storeposition 500Query handleridle

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

    critical

    A crash between the two writes leaves the view wrong for ever.

    Wrong
    db.save(order)broker.publish(event)
    Right
    with db.transaction():    db.save(order)    db.save(outbox_row)# a relay publishes the outbox
  • Deciding from the read model

    critical

    It may be old, so two people can take the last item.

    Wrong
    if view.stock > 0: sell()
    Right
    item = load(item_id)item.sell()     # the aggregate checks
  • Projections that add blindly

    major

    A repeated event counts twice.

    Wrong
    view.count += 1
    Right
    if event.position > view.position:    view.count += 1    view.position = event.position
  • CQRS for everything

    major

    Simple parts become slow to change, with nothing gained.

    Wrong
    users, settings, tags = cqrs(), cqrs(), cqrs()
    Right
    orders = 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.