Event-Driven Architecture Patterns with Kafka: Event Sourcing, CQRS, Saga and Outbox

Apache Kafka 20 min min read Updated: Nov 17, 2026 Advanced
Event-Driven Architecture Patterns with Kafka: Event Sourcing, CQRS, Saga and Outbox
Advanced Topic 1 of 2

Events, Commands and Queries

Message typeMeaningExampleWho knows the receiver?
EventSomething that happened (past tense, immutable)OrderCreated, PaymentFailedProducer does not care who listens
CommandRequest to do somethingChargeCustomerSender targets one handler
QueryRequest for dataGetOrderUsually 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

StylePayloadTrade-off
Event notificationOnly ids: {orderId: 1001}Small, but consumers must call back the producer service for details (coupling, load)
Event-carried state transferAll data consumers need: customer, items, totalsConsumers stay autonomous and can keep local copies. Events are bigger and schema design matters
Change event (CDC)Before and after rowExposes 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.

text 1. One DB transaction: INSERT order + INSERT outbox row (atomic) 2. Debezium (or a poller) reads the outbox table 3. Publishes to Kafka topic, then the row can be removed Result: an event is published if and only if the business change was committed.

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

sql CREATE TABLE processed_events ( event_id VARCHAR(64) PRIMARY KEY, processed_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP );
java @Transactional public void handle(OrderCreated event, String eventId) { if (processedEventsRepository.existsById(eventId)) return; // already done, skip inventoryService.reserve(event); // business change processedEventsRepository.save(new ProcessedEvent(eventId)); // same transaction, so both or none }

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).

text Account events (key = accountId): AccountOpened(100) Deposited(50) Withdrawn(30) Deposited(10) Current balance = replay = 100 + 50 - 30 + 10 = 130
BenefitsCosts
Complete audit trail, temporal queries ('state at 10:00')Learning curve and different thinking
Rebuild read models or fix bugs by replayingEvent schema versioning is hard (events are forever)
Natural fit for Kafka's log and compactionQueries need read models (see CQRS). Deleting personal data (GDPR) needs special handling such as crypto-shredding
Kafka as event store: Kafka can hold events with infinite retention, but optimistic concurrency checks (reject a write if the version changed) are not built in. Many teams keep the aggregate event store in a database and use Kafka to distribute the events.

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.

text Command API --> write DB / event store --> events --> Kafka |--> Streams app --> order-summary view (Redis) |--> Connect sink --> search index (OpenSearch) |--> Connect sink --> analytics warehouse Query API reads from the best-fit read model
Eventual consistency: A read model is updated a moment after the write. The UI must handle 'my order is saved but not visible yet' (show the result from the command response, or poll).

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.

text Order service: OrderCreated ----------------------------------------> (wait) Payment service: on OrderCreated -> charge -> PaymentCompleted | PaymentFailed Inventory service: on PaymentCompleted -> reserve -> StockReserved | StockUnavailable Order service: on StockReserved -> mark CONFIRMED on PaymentFailed / StockUnavailable -> mark CANCELLED Payment service: on StockUnavailable -> refund (compensation)
StyleHowProsCons
ChoreographyEach service reacts to events and emits the next oneSimple, decoupled, no central pointFlow is spread over services, hard to see and debug as steps grow
OrchestrationA saga coordinator service sends commands and tracks stateClear flow, central place for timeouts and compensationOrchestrator is an extra component, risk of becoming a god service
  • Every step needs an idempotent handler and a defined compensation
  • Add timeouts: if no PaymentCompleted arrives 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

TopicGuideline
Naming<domain>.<entity>.<event>.<version> such as shop.orders.created.v1, lowercase, consistent separators
GranularityOne topic per event type, or per entity with all its events (when order across event types for the same key matters)
KeysEntity id (order id, customer id) so all events for the entity stay ordered in one partition
PartitionsPlan for future throughput and consumer count. Increasing later changes key-to-partition mapping
RetentionMatch the consumers' needs (days for events, compact for latest-state topics, long or infinite for event sourcing)
OwnershipEach 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 retire v1
  • Include eventId, eventType, eventTime, schemaVersion, correlationId in a standard envelope or in headers
json { "eventId": "7b2f1c0e-3f5a-4a52-9a77-0a2f6c1a9b11", "eventType": "OrderCreated", "eventTime": "2026-05-01T10:15:30Z", "schemaVersion": 1, "correlationId": "order-1001", "data": { "orderId": "1001", "customerId": "c-7", "items": [ { "sku": "A1", "qty": 2 } ], "total": 59.90, "currency": "EUR" } }

Anti-Patterns

Anti-patternProblemBetter
Kafka as a request-response RPC for everythingLatency, complexity, hidden couplingUse HTTP/gRPC for queries and immediate answers
Dual write (DB then Kafka in code)Lost or phantom eventsOutbox or CDC
One giant 'god event' with every fieldCoupling and constant schema changesFocused events with a clear contract
Consumers reading another service's database tables via CDCInternal schema becomes public APIPublish designed events (outbox)
Ignoring duplicates and orderingCorrupt stateIdempotent handlers, keys per entity
Everything in one topicNo isolation, hard permissionsSeparate 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.

Quick Summary: events not RPC; outbox; idempotent consumer; CQRS read models; saga with compensation; topic naming and keys.

Get Newsletter

Subscibe to our newsletter and we will notify you about the newest updates on Edugators