Event-driven architecture (EDA) is often described as a way for services
to communicate without waiting for one another. That is true, but
incomplete. A production event-driven system must deal with duplicate
delivery, delayed consumers, schema evolution, ordering, partial
failure, and the gap between committing a database transaction and
publishing a message. A broker does not solve these problems
automatically. Reliability comes from explicit contracts, idempotent
processing, deliberate delivery semantics, and operational discipline.
This guide develops the core concepts and applies them to Kafka,
RabbitMQ, Java, and Spring Boot. It distinguishes events from commands,
explains the transactional outbox and saga patterns, examines event
sourcing and CQRS, and assembles a production-oriented reference
architecture.
1. Why Event-Driven Architecture Exists
A synchronous request-response call is straightforward: Service A calls
Service B, waits, receives a response, and continues. This is
appropriate when the caller needs an immediate answer. It becomes
problematic when one business action triggers many independent
activities.
Consider an online order. After an order is accepted, the platform may
reserve inventory, authorize payment, send an email, update analytics,
notify a warehouse, and update a loyalty service. If the order service
calls every downstream service synchronously, its latency and
availability become coupled to all of them. A temporary email outage
could delay order acceptance even though email is not essential to
accepting an order.
An event-driven design separates the fact that something happened from
the work performed in response. The order service records an order and
publishes an OrderPlaced event. Inventory, notifications, analytics,
and other consumers subscribe independently. The producer does not need
to know every consumer.
1.1 What EDA provides
- Temporal decoupling: consumers can process messages later.
- Independent scaling: each consumer can scale according to its
own workload. - Fan-out: one event can trigger several independent reactions.
- Buffering: a broker can absorb bursts and help consumers recover
after interruptions. - Extensibility: new consumers can subscribe without changing the
producer, provided the contract contains the necessary facts.
These benefits have costs. EDA introduces eventual consistency,
infrastructure, schema governance, duplicate handling, and more
difficult debugging. It shifts complexity; it does not eliminate it.
1.2 When it is appropriate
Use asynchronous events when the producer does not need an immediate
result from every downstream activity, when several independent
consumers react to the same business fact, or when buffering and
independent scaling are valuable.
Prefer synchronous communication when the caller needs an immediate
answer, when an operation is inherently interactive, or when
asynchronous coordination would add more complexity than it removes. A
product page may synchronously query pricing because the user needs a
price now. The same page view can asynchronously emit an analytics event
because the user does not need to wait for analytics storage.
Most mature architectures combine both styles. Synchronous APIs handle
queries and immediate decisions; events communicate completed business
facts and initiate background work.
1.3 Start with requirements, not a broker
Before choosing Kafka or RabbitMQ, ask: Which business facts need to be
communicated? Who owns them? What must happen if a consumer is
unavailable? How quickly must the system converge? What ordering is
required? Broker selection follows from these answers.
2. Events, Commands and Messages
The terms event, command, and message are often used
interchangeably. They should not be.
A message is the general unit of communication. A command asks a
receiver to perform an action. An event states that something has
already happened.
Concept Meaning Typical name
Command Request to perform an action ReserveInventory
Event Fact about a completed occurrence InventoryReserved
Message Generic communication envelope Depends on payload
Commands are usually imperative and directed to a logical recipient.
Events are declarative and may have many consumers. ReserveInventory
can be rejected. InventoryReserved describes a reservation that has
already happened.
2.1 Name events as facts
Good event names use past tense: OrderPlaced, PaymentAuthorized,
ShipmentDispatched, CustomerAddressChanged. Avoid vague names such
as OrderUpdate. An event should represent a meaningful business
transition, not every internal method call. OrderEntitySaved leaks
persistence implementation; OrderPlaced expresses business meaning.
2.2 Domain events and integration events
A domain event represents something meaningful inside a domain model. An
integration event is a contract intentionally exposed to other systems.
They may carry similar information, but they have different stability
requirements.
A domain event can evolve with the internal model. An integration event
is a public boundary and should avoid exposing database rows, ORM
entities, or implementation-specific details. Mapping between the two
lets the owning service control what becomes externally observable.
2.3 Commands need explicit outcomes
A command handler should make its result observable. It may return a
synchronous response, publish a result event, or both. For asynchronous
commands, define how rejection is represented: a failure response,
rejection event, status resource, or dead-letter workflow. Broker
acceptance does not mean the business operation succeeded.
3. Synchronous and Asynchronous Communication
Synchronous communication creates a temporal dependency: the caller
waits for the callee. Asynchronous communication removes the immediate
wait, but the caller must accept that the outcome may arrive later.
Suppose an API calls three services sequentially. If their latencies are
40 ms, 80 ms, and 120 ms, the downstream portion takes approximately 240
ms before network overhead. Parallel calls may reduce latency toward the
slowest dependency, but availability still depends on all required calls
succeeding.
With asynchronous fan-out, the initiating request can finish after its
own durable work and publication intent are safely recorded. Downstream
tasks proceed independently. The user experience must represent a
pending state rather than falsely claiming that every activity has
completed.
3.1 Model asynchronous outcomes
HTTP 202 Accepted can communicate that processing has been accepted
but is not complete:
POST /orders
Idempotency-Key: checkout-51
HTTP/1.1 202 Accepted
Location: /orders/ord-8472/status
Content-Type: application/json
{
"orderId": "ord-8472",
"status": "ACCEPTED"
}
A status resource might later report CONFIRMED, REJECTED, or
REQUIRES_ACTION. These are business states, not broker states.
3.2 Avoid asynchronous theatre
If a producer waits for a reply event before completing every request,
the design may simply recreate synchronous RPC with more moving parts.
Request-reply messaging can be useful, but it needs correlation IDs,
deadlines, and explicit timeout behavior.
4. Message Brokers: Kafka, RabbitMQ and the Alternatives
A broker transports messages between producers and consumers. Different
brokers embody different models.
4.1 Kafka's log-based model
Apache Kafka stores records in partitioned, replicated logs called
topics. Producers append records. Consumers read records and track
offsets. Records are retained according to policy, so consumers can
often replay historical data.
Kafka is useful for high-throughput event streams, multiple independent
consumer groups, replay, and stream processing. Ordering is guaranteed
within a partition, not across an entire topic.
4.2 RabbitMQ's queue and exchange model
RabbitMQ routes messages through exchanges to queues using routing rules
and bindings. Consumers receive messages and acknowledge them. It is
well suited to task distribution, routing patterns, work queues, and
request/reply workflows.
Kafka and RabbitMQ are not interchangeable implementations of an
identical abstraction. Kafka emphasizes durable ordered logs and
consumer-controlled position. RabbitMQ emphasizes broker-managed routing
and queue delivery.
4.3 Practical comparison
Requirement Kafka RabbitMQ
Replay retained history Native log retention Requires a different
and offsets design or stream
features
Work queue semantics Consumer groups and Core queue model
partitions
Ordering Within a partition Queue ordering,
affected by concurrency
and requeue
Fan-out Multiple consumer Exchanges and bound
groups queues
Complex routing Usually topic/key Exchanges and bindings
conventions or stream are central
processing
Consumer progress Offsets managed by Delivery
consumers acknowledgements and
queue state
This is a conceptual comparison, not a benchmark. Throughput, latency,
durability, and operational complexity depend on configuration and
workload.
4.4 Select based on the workload
Ask whether consumers need replay, whether messages are streams or
tasks, whether routing rules are complex, how ordering is defined, what
retention is required, and which platform the team can operate
competently. An infrastructure platform that the organization cannot
monitor, upgrade, secure, or recover is not a sound choice.
5. Event Design and Schema Evolution
An event schema is an API contract. Once consumers depend on it,
changing it becomes a compatibility problem.
A useful event envelope commonly contains:
eventId: unique identifier for this event instance.eventType: stable semantic type.eventVersion: schema or contract version.occurredAt: time the business fact occurred.producer: logical producer identity.aggregateId: business entity identifier, where relevant.correlationId: identifier connecting related work.causationId: identifier of the message or action that caused this
event.traceparent: distributed tracing context, where supported.payload: business data.
Example:
{
"eventId": "evt-8b31d4",
"eventType": "com.example.orders.OrderPlaced",
"eventVersion": 2,
"occurredAt": "2026-11-28T08:30:00Z",
"producer": "order-service",
"aggregateId": "ord-8472",
"correlationId": "checkout-51",
"causationId": "cmd-119",
"payload": {
"orderId": "ord-8472",
"customerId": "cus-102",
"currency": "EUR",
"totalMinorUnits": 12990
}
}
Integer minor units avoid floating-point currency errors. Currency is
explicit. The event contains business facts needed by consumers, not a
serialized database entity.
5.1 Make contracts intentional
Do not publish fields merely because they happen to exist in the
producer's database. Every field is a potential long-term obligation.
Avoid personal data unless consumers genuinely need it. Prefer stable
identifiers and carefully selected facts.
5.2 Compatibility
A backward-compatible change allows a new consumer to read old events. A
forward-compatible change allows an old consumer to tolerate new events.
A fully compatible change supports both directions under the chosen
rules.
Adding an optional field with a defined default is often safe. Renaming
a field, changing its type or unit, or changing its meaning is usually
breaking. Use schema registries and formats such as Avro, Protobuf, or
JSON Schema when validation and governance justify the overhead.
Establish compatibility checks in CI.
5.3 Semantic compatibility
Changing total from gross to net value is breaking even if it remains
a decimal. Changing a timestamp from order creation time to payment
authorization time is also breaking. Contract review must consider
meaning, units, nullability, and lifecycle, not only field types.
6. Delivery Semantics: At-Most-Once, At-Least-Once and Exactly-Once
Delivery guarantees describe what may happen as messages move through a
system. They do not automatically guarantee business outcomes.
6.1 At-most-once
A message is delivered zero or one times. Loss is possible, duplication
is not. This can be acceptable for disposable telemetry where occasional
loss is explicitly tolerated.
6.2 At-least-once
A message is delivered one or more times. Duplication is possible. This
is a common choice for business messaging because the system can retry
after uncertain outcomes. Consumers must be idempotent.
A typical duplicate scenario:
- Consumer receives
evt-123. - Consumer updates its database.
- Consumer crashes before acknowledging the message.
- Broker redelivers
evt-123. - Consumer sees the same event again.
Without protection, the business update may happen twice.
6.3 Exactly-once is scoped
Kafka supports exactly-once processing for certain Kafka-to-Kafka
workflows using transactions and correctly configured producers and
consumers. That does not make an arbitrary database update, HTTP call,
email, or payment-provider invocation exactly once.
If a consumer writes to an external database and commits a Kafka offset
separately, a crash can occur between the operations. The application
still needs an atomicity strategy or idempotent processing.
6.4 Aim for effectively-once business effects
For most business consumers, the robust pattern is at-least-once
delivery plus deduplication and idempotent state transitions. Physical
execution may happen more than once; the intended business effect
happens once.
7. Ordering, Partitioning and Message Keys
Ordering is not a global property unless the system explicitly provides
it. Kafka guarantees order within a partition. When events for the same
aggregate must be processed in order, use a stable key such as
orderId.
7.1 Partition keys
If all events for ord-8472 use the same key, they are routed to the
same partition under a stable partitioning strategy. A consumer
processes that partition in offset order. Different orders can be
processed concurrently across partitions.
This gives per-aggregate ordering, not total ordering across all orders.
7.2 Hot keys
A key receiving a disproportionate share of traffic can overload one
partition while others remain underused. Splitting the key may improve
throughput but break ordering. Identify the smallest scope that
genuinely requires order.
7.3 Detect stale events
Events can arrive late, be replayed, or represent an older aggregate
version. Include aggregate versions or sequence numbers when consumers
need to detect stale updates. A consumer may reject an event whose
version is less than or equal to the version already applied, provided
the domain semantics support that rule.
Timestamps are not a safe ordering mechanism by themselves. Clocks
drift, and occurrence time is not necessarily commit order.
8. Idempotency and Duplicate Message Handling
Idempotency means repeating an operation has the same intended effect as
performing it once. It is a foundational property in distributed
systems.
8.1 Database-backed inbox
A consumer can maintain an inbox table with a unique constraint on the
event ID:
CREATE TABLE processed_events (
consumer_name VARCHAR(100) NOT NULL,
event_id VARCHAR(100) NOT NULL,
processed_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
PRIMARY KEY (consumer_name, event_id)
);
Within one database transaction:
- Attempt to insert the event ID.
- If it already exists, treat the message as a duplicate.
- If inserted, apply the business update.
- Commit both the inbox record and business update atomically.
- Acknowledge the message only after commit.
The uniqueness constraint is the concurrency control. A check followed
by an insert without a constraint is vulnerable to races.
8.2 Spring-oriented example
@Transactional
public void handle(OrderPlaced event) {
int inserted = inboxRepository.insertIfAbsent(
"inventory-projection",
event.eventId()
);
if (inserted == 0) {
return; // already applied
}
inventoryService.reserveFor(event.orderId(), event.items());
}
The repository should use a database-native insert-if-absent strategy or
safely handle unique-key conflicts. The inbox insert and business update
must share a transactional database. Broker acknowledgement must occur
after the transaction commits. Verify the actual listener-container
behavior for the framework version in use.
8.3 Prefer idempotent state transitions
"Set shipment status to DISPATCHED for shipment 88" is easier to make
idempotent than "increment dispatched shipment count." For increments,
use a deduplication key or derive the count from uniquely identified
records.
9. The Transactional Outbox Pattern
A dangerous failure window appears when a service updates its database
and publishes an event as two independent operations.
If an order row commits and the process crashes before publication, the
order exists but consumers never hear about it. If publication happens
first and the database transaction rolls back, consumers may act on an
order that does not exist.
The transactional outbox stores the business change and an event record
in the same database transaction.
9.1 Outbox schema
CREATE TABLE outbox_events (
id VARCHAR(100) PRIMARY KEY,
aggregate_type VARCHAR(100) NOT NULL,
aggregate_id VARCHAR(100) NOT NULL,
event_type VARCHAR(200) NOT NULL,
event_version INTEGER NOT NULL,
payload JSON NOT NULL,
occurred_at TIMESTAMP NOT NULL,
published_at TIMESTAMP NULL,
attempts INTEGER NOT NULL DEFAULT 0
);
CREATE INDEX idx_outbox_unpublished
ON outbox_events (published_at, occurred_at);
The order transaction inserts both the order and outbox record:
@Transactional
public Order placeOrder(PlaceOrder command) {
Order order = orderRepository.save(Order.create(command));
outboxRepository.insert(
OutboxEvent.from(
"OrderPlaced",
order.getId(),
OrderPlaced.from(order)
)
);
return order;
}
If the transaction commits, both records exist. If it rolls back,
neither exists.
9.2 Publishing the outbox
A separate publisher reads unpublished rows and sends them to the
broker. It marks them published only after a successful send. This can
be implemented with polling or change data capture (CDC), for example
through a CDC connector reading the database log.
The publisher may send an event and crash before marking the row
published. It will send the same event again after restart. The outbox
guarantees durable publication intent, not exactly-once delivery.
Consumers still need idempotency.
9.3 Polling versus CDC
Polling is conceptually simple and can work at moderate volume. It
requires careful locking, batching, retry handling, and cleanup. CDC can
reduce polling overhead and capture committed changes from the database
log, but adds connector infrastructure and operational complexity.
Do not delete outbox records immediately. Define retention, archival,
and cleanup policies that preserve the ability to investigate incidents.
9.4 Preserve aggregate order
Multiple publisher workers can claim rows concurrently and publish later
events before earlier ones. If per-aggregate order matters, partition
work by aggregate, use sequence numbers, or ensure a single ordered
publisher per shard. Database locking and query plans must be designed
for expected throughput.
10. Event Sourcing Is Not Event-Driven Architecture
The concepts are related but distinct.
Event-driven architecture uses events to communicate facts and trigger
reactions. A service may store current state in ordinary relational
tables and publish integration events through an outbox.
Event sourcing stores the sequence of domain events as the authoritative
record of state. Current state is reconstructed by replaying events or
loading a snapshot and applying later events.
10.1 Conventional persistence
A conventional order table might store:
order_id | status | total_minor_units
---------+-----------+------------------
ord-8472 | CONFIRMED | 12990
The current row is authoritative. An audit table may separately record
changes.
10.2 Event-sourced persistence
An event stream might contain OrderCreated, ItemAdded,
PaymentAuthorized, and OrderConfirmed. Current order state is
derived by applying those events in sequence.
10.3 Benefits and costs
Event sourcing can provide a rich audit trail, temporal reconstruction,
and the ability to build new projections from historical facts. It also
introduces event evolution, replay safety, snapshotting, retention,
privacy, and debugging challenges.
Corrections are normally appended as compensating or corrective events
rather than editing historical records. Use event sourcing when
historical transitions are central to the domain and the organization
can operate the model. Do not adopt it merely because the system already
uses Kafka.
11. CQRS and Read Model Projections
Command Query Responsibility Segregation (CQRS) separates the model used
to change state from the model used to read it. It does not require
event sourcing or separate physical databases.
A command model enforces business invariants. A query model is optimized
for reading. Events can update query projections asynchronously.
For example, an order-history projection may combine events from the
Order, Payment, and Shipping services into a read table designed for the
customer screen:
CREATE TABLE customer_order_view (
customer_id VARCHAR(100) NOT NULL,
order_id VARCHAR(100) NOT NULL,
status VARCHAR(40) NOT NULL,
total_minor BIGINT NOT NULL,
updated_at TIMESTAMP NOT NULL,
PRIMARY KEY (customer_id, order_id)
);
11.1 Rebuilding projections
A projection should be reproducible from source events or a documented
snapshot process. Rebuilds need a clear strategy for offsets,
versioning, and cutover. A safe approach is to build a new projection
generation, catch it up, validate it, and then switch reads.
11.2 Eventual consistency in the UI
After an order is placed, the read model may take time to reflect it.
The application should communicate this honestly. It can return the
command result directly for the immediate confirmation page and use the
projection for subsequent history queries. Where necessary, a
read-your-writes mechanism can temporarily query the authoritative
service or wait for a projection version.
12. Retries, Dead-Letter Queues and Poison Messages
A consumer can fail because of a temporary network problem, a database
outage, invalid data, a programming bug, or a downstream dependency.
Treating all failures identically is a reliable way to create a queue
full of repeatedly failing messages.
12.1 Classify failures
- Transient: network interruption, throttling, short-lived
database unavailability. Retry with bounded exponential backoff and
jitter. - Permanent data failure: malformed payload or unsupported schema.
Quarantine for investigation rather than retrying forever. - Business rejection: insufficient inventory or invalid state.
This is often a valid business outcome, not a technical exception. - Unknown failure: apply a bounded retry policy, preserve
diagnostic context, then route for investigation.
12.2 Backoff with jitter
A common delay formula is:
[ delay_n = \min{=tex}(maxDelay, baseDelay \times 2{=tex}^n) +
jitter ]
Jitter prevents many consumers from retrying at exactly the same moment.
Define a maximum attempt count and total retry time budget. A retry
policy should not turn a short outage into a multi-hour backlog without
an explicit reason.
12.3 Dead-letter queues
A dead-letter queue (DLQ) or dead-letter topic holds messages that
cannot be processed under the normal policy. A DLQ is not a rubbish bin.
It needs ownership, alerting, failure metadata, retention, access
controls, a replay procedure, and safeguards against replaying harmful
messages blindly.
Before replay, fix the underlying issue and determine whether earlier
attempts produced partial side effects. Idempotency protects against
duplicates; it does not repair incorrect business logic.
12.4 Poison messages
A poison message consistently crashes or blocks a consumer. In an
ordered partition, repeatedly retrying one poison record can prevent
later records from progressing. The system needs a deliberate policy:
pause and investigate, skip with an auditable record, or route to
quarantine while preserving the meaning of the ordering contract.
Skipping a record is a business decision when later events depend on it.
It must not be an invisible operational shortcut.
13. Distributed Consistency and Sagas
A business process often spans services, each with its own database. A
normal ACID transaction cannot usually cover all of them without tight
coupling and fragile availability dependencies.
A saga coordinates a sequence of local transactions. Each step commits
locally and may publish an event that triggers the next step. If a later
step fails, the workflow can run compensating actions.
13.1 Example: order fulfilment
- Create order in
PENDING. - Reserve inventory.
- Authorize payment.
- Arrange shipment.
- Mark order
CONFIRMED.
If payment authorization fails after inventory reservation, the workflow
may release the reservation and mark the order PAYMENT_FAILED.
13.2 Compensation is not rollback
A database rollback erases an uncommitted transaction. A saga
compensation is a new business action. A refund does not erase the
original charge from history. Releasing stock does not mean the
reservation never existed.
Compensations can fail too. They need retries, monitoring, and manual
recovery paths. Some actions are not reversible, such as sending an
email or dispatching a physical package. The workflow must model those
realities.
13.3 Choreography and orchestration
In choreography, services react to events without a central coordinator.
This works for a small number of simple steps, but complex workflows
become difficult to understand because control flow is distributed.
In orchestration, a workflow coordinator sends commands and tracks
progress. It improves visibility but introduces a component that must be
operated reliably.
Choose choreography for simple, loosely coupled reactions. Choose
orchestration when the workflow has many steps, deadlines, branching,
compensation, or a need for centralized operational visibility.
14. Kafka Architecture in Depth
Kafka's core abstractions are brokers, topics, partitions, records,
producers, consumer groups, and offsets.
14.1 Topics and partitions
A topic is a named stream divided into partitions. Each partition is an
ordered log. Each record has an offset within its partition. A partition
is replicated across brokers according to its replication factor, with
one replica acting as leader under normal operation.
Partition count affects parallelism, throughput, ordering, and
operational overhead. Increasing partitions is not a free tuning knob:
it can change key-to-partition mapping and complicate ordering
assumptions.
14.2 Replication and acknowledgements
Producer acknowledgement settings influence when a write is considered
successful. Important data commonly uses acknowledgements from all
in-sync replicas, alongside an appropriate replication factor and
minimum in-sync replica setting. These settings must be chosen together.
Test broker loss and leader election behavior under realistic
conditions.
14.3 Consumer groups
Within a consumer group, partitions are assigned among consumers. A
partition is generally processed by one consumer in the group at a time.
Adding consumers beyond the partition count does not increase
parallelism for that group.
Rebalances occur when consumers join, leave, or fail. Long processing
times and unstable membership can cause repeated rebalances. Consumers
should process within configured poll constraints or use a safe
pause-and-resume design.
14.4 Offset management
An offset is a consumer's position in a partition. Committing an offset
says that earlier records are considered processed according to the
consumer's policy. Committing too early can lose work after a crash.
Committing too late can cause redelivery. Manual or carefully configured
commits may be necessary when coordinating external side effects.
14.5 Retention and compaction
Time- or size-based retention keeps records for a configured period. Log
compaction retains the latest value for each key over time, subject to
cleanup behavior. Compaction can be useful for state topics, but it is
not a substitute for a full event history. Choose retention based on
replay needs, storage cost, privacy, and regulatory obligations.
15. Java and Spring Boot Implementation
Spring provides abstractions for messaging and transaction management.
These are useful, but they do not erase broker semantics.
15.1 Define explicit event types
Use immutable records for payloads where appropriate:
public record OrderPlaced(
String eventId,
String orderId,
String customerId,
long totalMinorUnits,
String currency,
Instant occurredAt
) {}
Keep transport metadata separate from business payload where possible.
Include stable identifiers and explicit time and currency semantics.
15.2 Kafka listener
@Component
public class OrderPlacedListener {
private final OrderProjectionService projectionService;
public OrderPlacedListener(OrderProjectionService projectionService) {
this.projectionService = projectionService;
}
@KafkaListener(
topics = "orders.events",
groupId = "order-history-projection"
)
public void onOrderPlaced(OrderPlaced event) {
projectionService.apply(event);
}
}
This is intentionally simplified. A production deployment must define
deserialization, type mapping, error handling, retry behavior,
acknowledgement mode, concurrency, transaction boundaries, and
observability.
15.3 RabbitMQ listener
@Component
public class ShipmentListener {
private final ShipmentService shipmentService;
public ShipmentListener(ShipmentService shipmentService) {
this.shipmentService = shipmentService;
}
@RabbitListener(queues = "shipment.commands")
public void handle(ArrangeShipment command) {
shipmentService.arrange(command);
}
}
For production, configure durable exchanges and queues where required,
persistent messages, dead-letter routing, publisher confirms, consumer
acknowledgements, prefetch, and retry behavior.
15.4 Externalize configuration
Keep broker addresses, credentials, topic names, concurrency, and retry
parameters outside application code. Use environment-specific
configuration and secret management. Avoid committing credentials or
embedding production topology in annotations.
15.5 Separate transport from application logic
A listener should validate and translate the incoming message, then
delegate to an application service. Business operations should be
testable without starting a broker. This separation makes transport
changes less invasive.
15.6 Understand transaction boundaries
@Transactional normally manages a transaction for a configured
transaction manager. It does not automatically make a database update
and Kafka publication atomic. Use an outbox or a deliberately supported
transaction strategy, and understand its exact failure guarantees.
16. Observability, Monitoring and Debugging
A distributed event flow is harder to debug than a single request
because work may cross processes and occur minutes later. Observability
must be designed into event metadata and dashboards.
16.1 Correlation and causation
A correlation ID groups messages belonging to one business workflow. A
causation ID identifies the immediate message or command that caused a
new event. These identifiers help reconstruct a chain without relying on
timestamps alone.
Propagate distributed trace context through message headers where
supported. Long-running workflows can outlive a single trace's useful
lifetime, so business correlation identifiers remain valuable even when
traces are sampled or expired.
16.2 Metrics to monitor
- consumer lag by group and partition;
- age of the oldest unprocessed message;
- publish rate, consume rate, and processing latency;
- retry and DLQ rates;
- processing failures by exception class;
- rebalance frequency and consumer availability;
- broker disk usage, replication health, and under-replicated
partitions; - outbox backlog and oldest unpublished event age;
- end-to-end workflow completion time;
- business outcomes such as order confirmation rate.
Consumer lag alone is not enough. A consumer can have low lag while
processing incorrectly, or high lag while still meeting the business
deadline.
16.3 Alert on meaningful symptoms
Alert on sustained lag growth, oldest-message age, failed replication,
outbox backlog, and DLQ growth. Set thresholds from service objectives.
A fixed threshold that pages for every short burst creates alert
fatigue.
16.4 Structured logs
Log event ID, event type, aggregate ID, consumer name, correlation ID,
attempt number, and outcome. Avoid logging full payloads by default
because they may contain personal or confidential data. Redact sensitive
fields and define retention.
17. Security and Operational Ownership
Messaging infrastructure is part of the application's attack surface. A
broker often carries data from multiple services and can become a
high-value target.
17.1 Authentication and authorization
Use authenticated connections and least-privilege permissions. A
producer should write only to the topics or exchanges it owns. A
consumer should read only what it needs. Separate identities by
application and environment.
17.2 Encryption
Use TLS for client-to-broker and, where required, broker-to-broker
communication. Manage certificate rotation as a planned operational
process.
17.3 Sensitive data
Events are copied, retained, replayed, and consumed by multiple systems.
Publishing personal data expands the number of places where deletion,
access control, and retention must be enforced. Prefer references or
minimized payloads when consumers can safely retrieve data through an
authorized API. Remember that references create dependencies and may not
preserve historical meaning.
17.4 Validate payloads
Validate event structure and required semantic fields at the boundary.
Apply size limits. Treat event payloads as untrusted input, even when
they arrive through an internal broker. Internal systems can be
compromised, misconfigured, or buggy.
17.5 Assign ownership
Define who owns each topic, queue, schema, consumer group, retention
policy, and DLQ. Establish naming conventions, lifecycle policies,
quotas, and deprecation procedures. Unowned topics become permanent
infrastructure clutter.
18. Performance, Scaling and Capacity Planning
Capacity planning begins with message rates and payload sizes, not
guesses about how many brokers "should be enough."
18.1 Estimate data rate
A first-order estimate is:
[ ingressBytesPerSecond = messagesPerSecond
\times {=tex}averagePayloadBytes ]
If a system receives 8,000 events per second with an average payload of
1.5 KB, raw ingress is about 12 MB/s before protocol overhead,
replication, indexes, and storage effects.
With replication factor three, the cluster stores multiple copies.
Retention multiplies storage requirements. Compression may reduce
storage and network traffic, but consumes CPU and depends on payload
characteristics.
18.2 Consumer capacity
If one consumer instance processes 400 messages per second and the
workload peaks at 4,000 messages per second, roughly ten instances are
needed before accounting for headroom, rebalances, downstream limits,
and uneven partition load. Partition count must support desired
parallelism.
18.3 Backpressure
A broker buffers work, but cannot create unlimited capacity. If
producers consistently outpace consumers, lag grows until retention,
disk, or business deadlines become a problem. Apply quotas, producer
throttling, admission control, and downstream protection. Define what
happens when the system cannot keep up.
18.4 Payload size
Large messages increase network, memory, serialization, and replication
costs. Prefer compact events that communicate facts and stable
identifiers. For large binary objects, store the object in an
appropriate object store and publish a reference with integrity metadata
and access controls. Ensure the object remains available for the
required processing window.
19. Common Architectural Mistakes
19.1 Publishing database rows as events
This couples consumers to persistence structure and leaks internal
fields. Publish business facts through explicit integration contracts.
19.2 Assuming the broker prevents duplicates
Practical delivery configurations can redeliver. Build idempotency into
consumers.
19.3 Treating a DLQ as a recovery strategy
A DLQ stores failures. It does not assign ownership, diagnose root
causes, or decide whether replay is safe.
19.4 Using one topic for everything
A generic topic can become a dumping ground with unclear retention,
access control, schema ownership, and consumer expectations. Topic
design should reflect domain boundaries, throughput, ordering, and
lifecycle.
19.5 Creating too many tiny events
Publishing every internal state mutation creates noise and burdens
consumers. Events should represent meaningful facts.
19.6 Creating enormous events
A giant event containing an entire aggregate and related entities is
hard to evolve, expensive to distribute, and often exposes data
unnecessarily. Design for the consumer contract.
19.7 Ignoring consumer lag
A system can appear healthy while events are hours behind. Monitor age
and business completion deadlines, not just process uptime.
19.8 Using timestamps as the only ordering mechanism
Timestamps are not a substitute for aggregate sequence numbers or broker
offsets. Clock skew and delayed publication make them ambiguous.
19.9 Making every interaction asynchronous
Asynchronous messaging is not inherently superior. If a user needs an
immediate answer, hiding it behind a message workflow can make the
product slower and harder to reason about.
19.10 Neglecting lifecycle and ownership
Topics, queues, schemas, and consumers need owners, retention rules,
deprecation plans, and runbooks.
20. A Production-Oriented Reference Architecture
Consider a commerce platform with an Order Service, Inventory Service,
Payment Service, Shipping Service, Notification Service, and Order
History Projection.
20.1 Service responsibilities
- Order Service: owns order state and accepts customer commands.
- Inventory Service: owns stock and reservation state.
- Payment Service: owns payment interactions and provider
reconciliation. - Shipping Service: owns shipment creation and dispatch state.
- Notification Service: sends email or push notifications.
- Projection Service: builds read-optimized order history.
- Message platform: transports events and commands with defined
retention and access controls.
Each service owns its database. No service writes directly into another
service's tables.
20.2 Order acceptance flow
- Client sends
PlaceOrderwith an idempotency key. - Order Service validates the request and creates a pending order.
- In the same database transaction, it inserts
OrderPlacedinto the
outbox. - Outbox publisher sends the event to the broker.
- Inventory Service consumes the event idempotently and attempts a
reservation. - Inventory Service publishes
InventoryReservedor
InventoryReservationRejectedthrough its own outbox. - Payment workflow begins after the required inventory outcome.
- Payment Service publishes
PaymentAuthorizedorPaymentRejected. - A saga coordinator or explicit workflow state machine decides the
next step. - Order Service transitions the order to
CONFIRMEDor a failure
state. - Notification and projection consumers react independently.
20.3 Conceptual event flow
Client
|
v
Order API -----> Order Database
|
| same transaction
v
Outbox Table
|
v
Outbox Publisher
|
v
Kafka Topic
/ | \
v v v
Inventory History Analytics
Service Projection
|
v
Inventory Outbox
|
v
Inventory Events
|
v
Workflow Coordinator
/ \
v v
Payment Order State
Service Update
This is conceptual. A deployment may use multiple topics, separate
command and event channels, CDC, and additional workflow components.
20.4 Explicit state transitions
PENDING
| inventory reserved
v
AWAITING_PAYMENT
| payment authorized
v
CONFIRMED
PENDING
| inventory rejected
v
REJECTED
AWAITING_PAYMENT
| payment rejected
v
PAYMENT_FAILED
Every transition should guard against duplicate and stale events. A
repeated PaymentAuthorized event must not trigger duplicate
fulfilment. A late InventoryReserved event must not revive a cancelled
order unless the domain explicitly permits it.
20.5 API idempotency
The client may retry POST /orders because it did not receive a
response. The Order Service should store the idempotency key with the
request result under a uniqueness constraint scoped to the caller or
tenant. Repeating the same key and same request should return the
original result. Reusing the key with a different request should be
rejected.
21. Testing Event-Driven Systems
Testing must cover more than whether a listener method runs.
21.1 Unit tests
Test domain transitions, event creation, idempotency decisions, and
compensation logic without a broker. Verify that invalid transitions are
rejected and repeated events do not produce repeated effects.
21.2 Contract tests
Validate event schemas and semantic expectations between producers and
consumers. Test old and new payloads against compatibility rules,
including missing optional fields, unknown fields, and boundary values.
21.3 Integration tests
Use real broker and database implementations in integration tests where
practical, often through disposable containers. Verify serialization,
routing, acknowledgement behavior, transactions, retries, and DLQ
configuration. An in-memory substitute may not reproduce the behavior
that matters.
21.4 Failure injection
Test crashes at dangerous boundaries:
- after database commit but before event publication;
- after broker publication but before outbox marking;
- after consumer database commit but before acknowledgement;
- during a rebalance;
- while the downstream database is unavailable;
- when a poison event blocks a partition;
- during replay of historical events.
For example, a crash after consumer commit but before acknowledgement
should cause redelivery, and the inbox should prevent a second business
effect.
21.5 Load and recovery tests
Test sustained peak throughput, bursts, slow consumers, broker restarts,
and recovery after backlog accumulation. Measure time to drain the
backlog, not just peak ingestion rate. A system that accepts a million
events but takes two days to recover is not necessarily resilient.
22. Engineering Decision Framework
Before introducing a broker, answer these questions.
Business requirements
- Does the caller need an immediate result?
- Which business facts are worth publishing?
- What is the acceptable delay for each consumer?
- Which workflows require ordering?
- What happens if a consumer never processes an event?
Data and consistency
- Which service owns each fact?
- What is the event's stable identity?
- What schema compatibility policy applies?
- Is the data sensitive?
- Can consumers rebuild their projections?
Reliability
- What delivery guarantee is required?
- How are duplicates handled?
- Is there a transactional outbox?
- What retry policy applies to each failure class?
- Who owns the DLQ and replay decision?
Operations
- Who operates the broker?
- What are the retention and capacity requirements?
- How are lag and workflow age monitored?
- How are credentials and certificates rotated?
- What is the recovery procedure after a cluster or regional failure?
If these questions have no clear answers, adding Kafka will not make the
architecture mature. It will merely make the uncertainty asynchronous.
23. Production Implementation Checklist
Event contracts
- Events represent business facts, not persistence operations.
- Event IDs, types, versions, timestamps, and correlation metadata
are defined. - Payloads are minimized and have stable semantics.
- Compatibility checks run in CI.
- Ownership and deprecation policies are documented.
Producer reliability
- Business changes and outbox records commit atomically.
- Publisher retries are bounded and observable.
- Duplicate publication is expected and safe.
- Ordering requirements are explicit.
- Outbox retention and cleanup are defined.
Consumer reliability
- Consumers are idempotent.
- Inbox records and business updates share a transaction where
required. - Acknowledgement occurs only after durable processing.
- Transient and permanent failures are classified.
- DLQ handling and replay are operationally owned.
Platform and operations
- Authentication, authorization, and encryption are configured.
- Replication and retention match recovery requirements.
- Consumer lag and oldest-message age are monitored.
- Capacity and backlog recovery are load-tested.
- Runbooks cover broker failure, consumer failure, and replay.
Business workflows
- State transitions are explicit.
- Saga compensation is modeled as a business action.
- Timeouts and stuck workflows are detected.
- User-facing states reflect asynchronous completion honestly.
- Duplicate and late events cannot corrupt business state.
24. Conclusion: Events Are Contracts, Not Just Messages
Event-driven architecture is a powerful way to coordinate independent
services, absorb bursts, and let multiple consumers react to business
facts. It also creates obligations: event contracts must evolve safely,
consumers must tolerate duplicates, ordering must be scoped
deliberately, and distributed workflows must handle partial failure.
The most reliable systems are not those with the most topics, brokers,
or elaborate diagrams. They are those whose business boundaries are
clear and whose failure behavior is designed rather than discovered in
production.
A practical starting point is modest: identify one workflow with genuine
asynchronous requirements, define a small set of business events,
implement a transactional outbox, make the consumer idempotent, and
monitor end-to-end completion. Add more sophisticated patterns only when
requirements justify them.
The central principle is simple: assume messages can be delayed,
duplicated, reordered outside their guaranteed scope, or temporarily
impossible to process. Then design the business workflow so those
conditions are survivable.
References and Further Reading
Consult the documentation matching the deployed software versions.
-
Apache Kafka Documentation: https://kafka.apache.org/documentation/
-
RabbitMQ Documentation: https://www.rabbitmq.com/docs
-
Spring for Apache Kafka Reference:
-
Spring AMQP Reference: https://docs.spring.io/spring-amqp/reference/
-
Spring Boot Reference Documentation:
-
Debezium Documentation: https://debezium.io/documentation/
-
CloudEvents Specification: https://cloudevents.io/
-
Martin Fowler, "Event-Driven":
-
Martin Fowler, "CQRS": https://martinfowler.com/bliki/CQRS.html
-
Chris Richardson, "Microservices Patterns":
-
Enterprise Integration Patterns:
-
AWS Prescriptive Guidance, Transactional Outbox Pattern:




