Events, Commands and Queries
| Message type | Meaning | Example | Who knows the receiver? |
|---|---|---|---|
| Event | Something that happened (past tense, immutable) | OrderCreated, PaymentFailed | Producer does not care who listens |
| Command | Request to do something | ChargeCustomer | Sender targets one handler |
| Query | Request for data | GetOrder | Usually request-response, not Kafka |
Kafka fits best for events: many independent consumers can react without the producer knowing them. This loose coupling is the main benefit and the main risk (hidden dependencies), so document who consumes what.
Event Content Styles
| Style | Payload | Trade-off |
|---|---|---|
| Event notification | Only ids: {orderId: 1001} | Small, but consumers must call back the producer service for details (coupling, load) |
| Event-carried state transfer | All data consumers need: customer, items, totals | Consumers stay autonomous and can keep local copies. Events are bigger and schema design matters |
| Change event (CDC) | Before and after row | Exposes the internal table structure, so prefer an outbox with a designed contract |
Pattern 1: Transactional Outbox
Problem: the service must update its database and publish an event, but those are two systems. A crash between them loses the event or publishes an event for a rolled-back change.
Details and the Debezium router were in the CDC lesson. The outbox gives at-least-once publishing, so consumers must handle duplicates.
Pattern 2: Idempotent Consumer
Natural idempotency is even better: use upserts (INSERT ... ON CONFLICT UPDATE), set absolute values instead of increments, and use the order id as a unique key.
Pattern 3: Event Sourcing
Instead of storing the current state, store the sequence of events as the source of truth. The current state is computed by replaying events (with snapshots for speed).
| Benefits | Costs |
|---|---|
| Complete audit trail, temporal queries ('state at 10:00') | Learning curve and different thinking |
| Rebuild read models or fix bugs by replaying | Event schema versioning is hard (events are forever) |
| Natural fit for Kafka's log and compaction | Queries need read models (see CQRS). Deleting personal data (GDPR) needs special handling such as crypto-shredding |
Pattern 4: CQRS (Command Query Responsibility Segregation)
Separate the model that changes data (commands) from the models that read data (queries). Kafka carries events from the write side to one or more read models, each shaped for its queries.
Pattern 5: Saga (Distributed Transactions)
There is no single database transaction across services. A saga is a sequence of local transactions where each step publishes an event, and failures trigger compensating actions that undo earlier steps.
| Style | How | Pros | Cons |
|---|---|---|---|
| Choreography | Each service reacts to events and emits the next one | Simple, decoupled, no central point | Flow is spread over services, hard to see and debug as steps grow |
| Orchestration | A saga coordinator service sends commands and tracks state | Clear flow, central place for timeouts and compensation | Orchestrator is an extra component, risk of becoming a god service |
- Every step needs an idempotent handler and a defined compensation
- Add timeouts: if no
PaymentCompletedarrives in 15 minutes, cancel the order - Include a correlation id (order id) in every event for tracing
- Choose choreography for 2 to 4 steps, orchestration for long, branching processes
Topic Design Guidelines
| Topic | Guideline |
|---|---|
| Naming | <domain>.<entity>.<event>.<version> such as shop.orders.created.v1, lowercase, consistent separators |
| Granularity | One topic per event type, or per entity with all its events (when order across event types for the same key matters) |
| Keys | Entity id (order id, customer id) so all events for the entity stay ordered in one partition |
| Partitions | Plan for future throughput and consumer count. Increasing later changes key-to-partition mapping |
| Retention | Match the consumers' needs (days for events, compact for latest-state topics, long or infinite for event sourcing) |
| Ownership | Each topic has an owner team, a documented schema and an access policy |
Versioning Events
- Prefer compatible changes (add optional fields with defaults) within a version
- For breaking changes, publish to a new topic version (
v2), run both for a migration period, then retirev1 - Include
eventId,eventType,eventTime,schemaVersion,correlationIdin a standard envelope or in headers
Anti-Patterns
| Anti-pattern | Problem | Better |
|---|---|---|
| Kafka as a request-response RPC for everything | Latency, complexity, hidden coupling | Use HTTP/gRPC for queries and immediate answers |
| Dual write (DB then Kafka in code) | Lost or phantom events | Outbox or CDC |
| One giant 'god event' with every field | Coupling and constant schema changes | Focused events with a clear contract |
| Consumers reading another service's database tables via CDC | Internal schema becomes public API | Publish designed events (outbox) |
| Ignoring duplicates and ordering | Corrupt state | Idempotent handlers, keys per entity |
| Everything in one topic | No isolation, hard permissions | Separate topics by event type and ownership |
Conclusion
Use Kafka for events, publish them reliably with the outbox pattern, make consumers idempotent, build read models with CQRS, coordinate multi-service workflows with sagas (choreography or orchestration), and keep topics, keys and schemas well designed and versioned.

