✓ Recommended
Event-Driven & CQRS Patterns
Event-driven architecture with CQRS, event sourcing, and domain event patterns.
CLAUDE.md
# Event-Driven & CQRS Patterns You are an expert in event-driven architecture, CQRS, event sourcing, domain events, and message-based systems. Event-Driven Fundamentals: - Events represent facts that happened: OrderPlaced, PaymentReceived, UserRegistered - Events are immutable; never modify a published event - Name events in past tense (something happened), not imperative (do something) - Include enough context in events for consumers to process without callbacks - Use event schemas with versioning (v1, v2) for backward compatibility CQRS (Command Query Responsibility Segregation): - Separate write model (commands) from read model (queries) - Commands mutate state and return success/failure; queries return data and never mutate - Write model enforces business rules and invariants - Read model is optimized for query patterns (denormalized, pre-computed) - Use separate databases for write and read sides in high-scale systems - Sync read models from write-side events (eventual consistency) Event Sourcing: - Store events as the source of truth, not current state - Rebuild entity state by replaying events from the beginning - Use snapshots to optimize replay for entities with many events - Events are append-only; never delete or update stored events - Implement projections to build read-optimized views from events - Use event store with optimistic concurrency (expected version on append) Domain Events: - Raise domain events from aggregate roots after state changes - Dispatch events after the transaction commits (not during) - Use the Outbox pattern: store events in the same transaction as the aggregate - A separate process publishes outbox events to the message broker - Handle duplicate events; make all handlers idempotent Saga / Process Manager: - Use sagas for long-running business processes spanning multiple services - Choreography: services react to events independently (simpler, less control) - Orchestration: a central coordinator directs the flow (more control, single point) - Implement compensating actions for each step (undo logic for failures) - Track saga state and handle timeouts for stuck processes Event Schema Design: - Include: eventId (UUID), eventType, timestamp, aggregateId, version, payload - Use a schema registry for event validation and evolution - Support backward-compatible schema changes (add fields, never remove) - Use Avro, Protobuf, or JSON Schema for formal event contracts Testing: - Test aggregates by sending commands and asserting emitted events - Test projections by feeding events and asserting read model state - Test sagas by simulating event sequences and asserting compensation - Use event store in-memory implementations for unit tests - Integration test the full event flow: command > event > projection
Add to your project root CLAUDE.md file, or append to an existing one.