Ryan Mitchell·
CQRS event-sourcing design where the aggregate enforces no-overdraft before any event is emitted
Designs Command Query Responsibility Segregation with event sourcing patterns including event store selection, projection design, and snapshot strategies.
CQRS & Event Sourcing Architecture
You are a Domain-Driven Design expert who has implemented CQRS and Event Sourcing in large-scale financial and gaming systems. Design a CQRS + Event Sourcing architecture.
**Domain**: {{domain}} (banking, e-commerce order management, gaming, inventory, collaborative editing)
**Aggregate Roots**: {{aggregate_roots}} (the main business entities that maintain invariants)
**Query Patterns**: {{query_patterns}} (the read-side queries: complex filters, reports, real-time views, search)
**Scale Requirements**: {{scale_requirements}} (write throughput, read throughput, latency requirements for both sides)
Design the complete architecture:
1. **CQRS Architecture Overview** - Command side vs Query side separation, deployment topology, communication patterns between sides
2. **Command Side Design** - Command handlers, aggregate roots, domain invariants, validation rules, business logic encapsulation
3. **Event Design** - Domain events as source of truth, event schema (JSON/Avro), event versioning strategy, event metadata (correlationId, causationId, timestamp)
4. **Event Store Selection** - EventStoreDB, Kafka as event store, PostgreSQL with event sourcing, Axon Server comparison and selection
5. **Aggregate Reconstruction** - Loading events by aggregate ID, applying events to rebuild state, snapshot strategy to optimize load times
6. **Snapshot Strategy** - Snapshot every N events, snapshot versioning, snapshot storage, snapshot + incremental event loading
7. **Projection Design** - Read model projections: one per query type, projection handlers, eventual consistency window, projection rebuilding
8. **Projection Storage** - Dedicated read databases per projection (MongoDB, Elasticsearch, PostgreSQL views), denormalized for query efficiency
9. **Consistency Model** - Strong consistency for commands (aggregate invariant protection), eventual consistency for queries, consistency window SLAs
10. **Process Manager / Saga** - Long-running business processes coordinated via events, timeout handling, compensating transactions
11. **Event Replay Strategy** - Full replay for bug fixes, selective replay, replay in parallel, zero-downtime projection rebuilding
12. **Testing Strategy** - Aggregate unit tests (given/when/then), projection tests, integration tests with event store, snapshot verification
13. **Anti-Patterns Warning** - Common CQRS/ES mistakes, when NOT to use event sourcing, complexity vs benefit analysis
Include actual event definitions, command handlers pseudocode, and projection rebuild procedure. Show the event flow with sequence numbers.
Ergebnisse
CQRS + Event Sourcing for a **banking account** domain. The `Account` aggregate protects the no-overdraft invariant on the write side; read models are projected for fast queries.
**Events are the source of truth:**
```json
{ "type": "MoneyWithdrawn", "aggregateId": "acc_812", "sequence": 47,
"data": { "amountCents": 5000, "balanceAfter": 12000 },
"meta": { "correlationId": "c-9k", "causationId": "cmd-44", "at": 1717250000 } }
```
**Command handler — invariant enforced before any event is emitted:**
```
handle(Withdraw cmd):
account = rehydrate(loadEvents(cmd.accountId)) # replay events → current state
if account.balance < cmd.amount:
reject InsufficientFunds # invariant protected on write side
emit MoneyWithdrawn(amount, account.balance - cmd.amount)
```
**Aggregate reconstruction** loads from the latest snapshot + events since, so a long-lived account doesn't replay thousands of rows:
```
state = snapshot ?? emptyAccount
for e in eventsSince(snapshot.sequence): state = apply(state, e)
```
**Snapshots** every 100 events. **Projections** are independent read models — a `balance_view` (Postgres) for fast lookups and an Elasticsearch `transaction_search` for statements — each rebuilt by replaying the event log, which makes a projection bug a non-event (just replay). **Consistency:** strong on the command side (invariants), eventual on queries with a documented sub-second window. **Anti-pattern warning:** don't event-source CRUD-shaped entities with no invariants and no audit need — the complexity isn't worth it. Aggregate tests are pure given/when/then over events.
Modell: Claude Opus 4
38 Likes15 SavesScore: 20
3 Kommentare
Ahmed Hassan·
Sending this system design one to my whole team.
Marco Rossi·
Okay the test coverage on this is chef-tier.
Emily Chen·
Stealing this for the next code review.