Lab 07: CQRS Patterns

Time: 60 minutes | Level: Architect | Docker: golang:1.22-alpine

Overview

CQRS (Command Query Responsibility Segregation) in Go: Command/Query interfaces, handler registry, CommandBus with middleware chain (logging/validation/retry), QueryBus, in-process event bus, and saga orchestrator.


Step 1: Command and Query Interfaces

package cqrs

import "context"

// Command: intent to change state
// Naming: verb + noun (CreateUser, PlaceOrder, CancelOrder)
type Command interface {
	CommandName() string
}

// Query: request for data, no side effects
// Naming: noun phrase (GetUser, ListOrders, SearchProducts)
type Query interface {
	QueryName() string
}

// Handler types
type CommandHandler func(ctx context.Context, cmd Command) error
type QueryHandler  func(ctx context.Context, query Query) (interface{}, error)

// Middleware: wraps a handler
type CommandMiddleware func(next CommandHandler) CommandHandler
type QueryMiddleware  func(next QueryHandler) QueryHandler

Step 2: CommandBus with Middleware Chain


Step 3: Three Middleware Handlers


Step 4: QueryBus


Step 5: Domain Commands and Queries


Step 6: In-Process Event Bus


Step 7: Saga Orchestrator


Step 8: Capstone — CommandBus with 3 Middleware

📸 Verified Output:


Summary

Component
Interface
Role

Command

CommandName() string

Mutates state

Query

QueryName() string

Reads state

CommandBus

Middleware chain

Route + wrap commands

QueryBus

Middleware chain

Route + cache queries

Middleware

func(next) Handler

Cross-cutting concerns

EventBus

Subscribe/Publish

Async cross-aggregate

Saga

Compensating transactions

Distributed rollback

Last updated