Building Event-Driven Java Backends
Reliable messaging, asynchronous processing, and real-time data in a Java backend with Spring Boot, Apache Kafka, the Transactional Outbox pattern, and Server-Sent Events.
Modern backend applications are expected to do much more than receive HTTP requests and return responses. They must process background tasks, communicate with external services, deliver notifications, maintain data consistency, and provide real-time updates to connected clients.
As applications grow, implementing all these responsibilities inside synchronous request-response workflows becomes increasingly difficult.
A better approach is to combine event-driven architecture, asynchronous messaging, transactional consistency, and streaming technologies.
In this article, we will explore how to build these capabilities into a Java backend using familiar technologies such as Spring Boot, Apache Kafka, relational databases, and Server-Sent Events.
The goal is not to introduce another framework or abstraction layer. It is to understand how these components work together to create a reliable and scalable backend architecture.
1. Why Synchronous Backend Processing Eventually Becomes a Problem
Consider a typical user registration workflow. When a user creates an account, the backend might need to validate the request, store the user, send a verification email, notify internal services, update analytics, and trigger additional background processing.
A straightforward implementation might look like this:
@Service
@RequiredArgsConstructor
public class RegistrationService {
private final UserRepository userRepository;
private final EmailService emailService;
private final AnalyticsService analyticsService;
@Transactional
public User register(RegisterRequest request) {
User user = userRepository.save(
new User(
request.email(),
request.username()
)
);
emailService.sendWelcomeEmail(user);
analyticsService.trackRegistration(user);
return user;
}
}
This implementation is easy to understand, but it introduces several problems.
- Response latency increases. The HTTP request must wait for every operation to finish.
- External dependencies become part of the transaction workflow. If the email provider is unavailable, registration may fail even though the database operation could have succeeded.
- Failures become difficult to isolate. A temporary analytics outage should not prevent a user from creating an account.
- Scaling becomes more complicated. Every additional operation increases the workload of the application handling the original request.
The solution is to separate business transactions from secondary processing. This is where event-driven architecture becomes useful.
2. Event-Driven Architecture with Apache Kafka
In an event-driven system, services communicate through events rather than directly invoking one another for every operation. Instead of asking the analytics service to process a registration immediately, the registration service publishes an event.
public record UserRegisteredEvent(
UUID eventId,
Long userId,
String email,
Instant occurredAt
) {}
The event describes something that has already happened. Other services can subscribe to this event and independently perform their responsibilities.
Client Application
|
v
REST Controller
|
v
Registration Service
|
v
Database
|
v
Event Publishing
|
v
Kafka Topic
|
+-----------+-----------+
| | |
v v v
Email Analytics Notification
Service Service Service
A Spring Boot application can publish events using KafkaTemplate.
@Service
@RequiredArgsConstructor
public class UserEventPublisher {
private final KafkaTemplate<String, Object> kafkaTemplate;
public void publish(UserRegisteredEvent event) {
kafkaTemplate.send(
"user.registered",
event.userId().toString(),
event
);
}
}
The event key is based on the user ID. This helps Kafka maintain ordering for events with the same key within a partition.
However, simply publishing an event after saving a database record introduces a consistency problem. What happens if the database transaction commits successfully but Kafka is unavailable? Or what happens if Kafka receives the event but the database transaction rolls back? These scenarios require a more reliable publishing strategy.
3. Transactional Outbox: Keeping Database Changes and Events Consistent
The Transactional Outbox pattern addresses the consistency problem between a relational database and a message broker. Instead of publishing directly to Kafka during the business transaction, the application writes the event into an outbox table.
Both the business record and the outbox record are committed within the same database transaction.
CREATE TABLE outbox_events (
id UUID PRIMARY KEY,
aggregate_id VARCHAR(100) NOT NULL,
event_type VARCHAR(150) NOT NULL,
payload JSONB NOT NULL,
created_at TIMESTAMP NOT NULL,
published_at TIMESTAMP NULL
);
The registration service now saves the user and the event together:
@Transactional
public User register(RegisterRequest request) {
User user = userRepository.save(
new User(
request.email(),
request.username()
)
);
UserRegisteredEvent event =
new UserRegisteredEvent(
UUID.randomUUID(),
user.getId(),
user.getEmail(),
Instant.now()
);
outboxRepository.save(
OutboxEvent.from(event)
);
return user;
}
The important detail is that both operations belong to the same database transaction. If the transaction rolls back, neither record is persisted. If it commits, both records are available for subsequent processing.
Publishing pending events
A background publisher can periodically retrieve unpublished events and send them to Kafka.
@Component
@RequiredArgsConstructor
public class OutboxPublisher {
private final OutboxRepository repository;
private final KafkaTemplate<String, String> kafkaTemplate;
@Scheduled(fixedDelay = 1000)
public void publishPendingEvents() {
List<OutboxEvent> events =
repository.findUnpublishedEvents(100);
for (OutboxEvent event : events) {
kafkaTemplate.send(
"user.events",
event.getAggregateId(),
event.getPayload()
).whenComplete((result, error) -> {
if (error == null) {
repository.markAsPublished(event.getId());
}
});
}
}
}
This example illustrates the basic mechanism. A production implementation should use database-level locking or atomic claiming to prevent multiple publisher instances from processing the same rows concurrently.
It should also consider:
- Retry policies.
- Duplicate publication.
- Event ordering.
- Failed-event monitoring.
- Outbox retention and cleanup.
- Broker delivery acknowledgements.
An important distinction: the Outbox pattern does not automatically provide exactly-once delivery. A publisher can send an event successfully and crash before marking it as published. Consumers must therefore be designed to handle duplicate events.
4. Building Reliable Kafka Consumers
Publishing events is only half of an event-driven system. Consumers must process messages reliably, handle failures, and avoid repeating business operations unnecessarily.
A Spring Kafka listener can be implemented as follows:
@Component
@RequiredArgsConstructor
public class UserRegisteredListener {
private final EmailService emailService;
private final ProcessedEventRepository processedEvents;
@KafkaListener(
topics = "user.registered",
groupId = "email-service"
)
public void handle(UserRegisteredEvent event) {
if (processedEvents.existsById(event.eventId())) {
return;
}
emailService.sendVerificationEmail(
event.email()
);
processedEvents.save(
new ProcessedEvent(event.eventId())
);
}
}
The processed-event check introduces a basic idempotency mechanism. However, the example has an important limitation: sending an email and recording the event as processed are two separate operations. A crash between them can still cause a duplicate email.
For stronger guarantees, the consumer needs a carefully designed processing strategy, such as:
- A transactional inbox table.
- A durable email delivery queue.
- Provider-supported idempotency keys.
- Retry and dead-letter handling.
Retry and Dead Letter Topics
Not every message can be processed successfully on the first attempt. Some failures are temporary: database connection interruptions, external API timeouts, rate limiting, and temporary service unavailability. Other failures are permanent: invalid message structures, unsupported event versions, and missing mandatory business information.
Repeatedly retrying permanent failures wastes resources. A typical processing flow looks like this:
Kafka Topic
|
v
Message Consumer
|
v
Business Processing
|
+------ Success ------> Acknowledge
|
+------ Temporary Error
| |
| v
| Retry
| |
| v
| Success
|
+------ Permanent Error
|
v
Dead Letter Topic
Dead Letter Topics make failed messages available for investigation and controlled reprocessing. They should be monitored as part of the operational architecture, not treated as a place where failed messages can be forgotten.
5. Asynchronous Email Delivery
Email delivery is another operation that should generally remain outside the critical HTTP request path. The application should create a durable email job and let a background worker handle delivery.
public record EmailJob(
UUID id,
String recipient,
String subject,
String template,
Map<String, Object> variables,
Instant createdAt
) {}
The email service can then process jobs independently:
@Service
@RequiredArgsConstructor
public class EmailWorker {
private final JavaMailSender mailSender;
public void send(EmailJob job) {
SimpleMailMessage message =
new SimpleMailMessage();
message.setTo(job.recipient());
message.setSubject(job.subject());
message.setText(
"Your request has been processed successfully."
);
mailSender.send(message);
}
}
In a production application, the email job should be stored durably or published through a reliable messaging mechanism before processing.
A robust email delivery architecture should include:
- Retry with exponential backoff.
- Maximum delivery attempts.
- Permanent failure classification.
- Delivery status tracking.
- Template versioning.
- Provider response logging.
- Rate limiting.
Email delivery should also be treated as an external side effect. A successful database transaction does not guarantee that an email has reached the recipient. This distinction is particularly important for password resets, verification codes, invoices, and security notifications.
6. Real-Time Backend Communication with Server-Sent Events
Traditional REST APIs are based on client-initiated requests. The client requests information, and the server returns a response. But some applications need continuous updates: live transaction monitoring, background job progress, dashboard metrics, notification streams, AI-generated response tokens, and system health information.
Polling is one possible solution, but it generates repeated HTTP requests even when no new information is available. Server-Sent Events (SSE) provide a simpler alternative for one-way communication from server to client.
Unlike WebSockets, SSE uses a standard HTTP connection and delivers events through a persistent response stream.
Implementing an SSE endpoint
A Spring Boot endpoint can expose a stream using SseEmitter.
@RestController
@RequestMapping("/api/stream")
public class NotificationController {
private final List<SseEmitter> clients =
new CopyOnWriteArrayList<>();
@GetMapping("/notifications")
public SseEmitter subscribe() {
SseEmitter emitter =
new SseEmitter(0L);
clients.add(emitter);
emitter.onCompletion(
() -> clients.remove(emitter)
);
emitter.onTimeout(
() -> clients.remove(emitter)
);
emitter.onError(
error -> clients.remove(emitter)
);
return emitter;
}
public void broadcast(String message) {
for (SseEmitter client : clients) {
try {
client.send(
SseEmitter.event()
.name("notification")
.data(message)
);
} catch (IOException exception) {
clients.remove(client);
}
}
}
}
This is a minimal single-instance example. A production system should not rely on an in-memory client list when running multiple application instances. A shared event source, such as Kafka or Redis Pub/Sub, can distribute notifications across instances.
Consuming SSE from JavaScript
The browser provides a native EventSource API:
const source = new EventSource(
"/api/stream/notifications"
);
source.addEventListener("notification", event => {
const message = event.data;
console.log("New notification:", message);
});
source.onerror = error => {
console.error("SSE connection error:", error);
};
The browser automatically attempts to reconnect when the connection is interrupted. For more advanced applications, SSE can also use event IDs and the Last-Event-ID header to support resuming a stream from a previously received event.
This requires the server to retain or retrieve the relevant event history. Automatic reconnection alone does not guarantee that missed events will be recovered.
When should you use SSE instead of WebSockets?
| Requirement | Recommended technology |
|---|---|
| Server-to-client notifications | SSE |
| Live dashboards | SSE |
| AI token streaming | SSE |
| Bidirectional communication | WebSockets |
| Real-time multiplayer applications | WebSockets |
| Continuous telemetry | SSE or WebSockets |
The correct choice depends on communication direction, latency requirements, infrastructure, and connection scale.
7. Java Records as Immutable Data Models
Java Records provide a concise way to represent immutable data structures. They are particularly useful for domain events, API request and response models, messaging payloads, configuration objects, and value objects.
public record PaymentCompletedEvent(
UUID eventId,
Long paymentId,
Long customerId,
BigDecimal amount,
String currency,
Instant completedAt
) {}
The compiler automatically generates a canonical constructor, accessor methods, equals(), hashCode(), and toString(). This eliminates a considerable amount of boilerplate.
Records and persistence
It is important to distinguish between an immutable data model and a persistence entity. Standard Jakarta Persistence entities have requirements that ordinary Java Records do not satisfy. Records are final and do not provide the mutable, no-argument entity structure traditionally required by JPA.
A practical approach is to use records for events and DTOs while maintaining dedicated persistence entities:
@Entity
@Table(name = "payments")
public class PaymentEntity {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private Long customerId;
private BigDecimal amount;
private String currency;
// Constructors, getters and setters
}
The application can map between the persistence model and immutable event model:
public static PaymentCompletedEvent toEvent(
PaymentEntity payment
) {
return new PaymentCompletedEvent(
UUID.randomUUID(),
payment.getId(),
payment.getCustomerId(),
payment.getAmount(),
payment.getCurrency(),
Instant.now()
);
}
This separation prevents persistence concerns from leaking into messaging contracts. It also makes event schemas easier to evolve independently from database structures.
8. Combining the Components into One Architecture
The technologies discussed above are most useful when they operate as parts of a coherent system. Consider an application that processes payments. A successful payment should persist the payment, record a payment-completed event, publish the event to Kafka, trigger invoice generation, send an email notification, and update the customer's live dashboard.
Client Application
|
v
REST API
|
v
Payment Service
|
Database Transaction
|
+------+------+
| |
v v
Payment Data Outbox Event
|
v
Outbox Publisher
|
v
Kafka
|
+--------------------+--------------------+
| | |
v v v
Invoice Service Email Service Dashboard Service
| | |
v v v
Invoice DB SMTP Provider SSE Stream
Each component has a specific responsibility. The payment service owns the business transaction. The outbox publisher handles reliable event publication. Kafka distributes events to independent consumers. The invoice and email services perform asynchronous operations. The dashboard service translates backend events into real-time client updates.
This architecture allows individual components to scale and evolve independently.
9. Operational Considerations: Reliability Is More Than Code
A distributed backend can look correct in a development environment and still fail under production conditions. Several operational concerns must be addressed.
- Message observability: Track message publication, consumption latency, retry counts, consumer lag, and dead-letter volume.
- Idempotency: Design consumers so that processing the same event more than once does not create duplicate business effects.
- Schema evolution: Use explicit event versions and compatible schema changes. Avoid silently changing the meaning of existing event fields.
- Backpressure: Control consumer concurrency and queue growth. A downstream service should not be overwhelmed simply because an upstream service can publish events faster.
- Security: Protect Kafka connections with appropriate authentication and encryption. Validate message contents and avoid placing unnecessary personal information in event payloads.
- Data retention: Define retention policies for Kafka topics, outbox records, processed-event records, and application logs.
- Failure recovery: Document how to replay messages, recover consumers, investigate dead-letter events, and restore service after an infrastructure failure.
These concerns are not optional additions. They are part of the architecture itself.
10. Final Thoughts
Building a modern backend is not simply about selecting a web framework or connecting a database. It is about designing how information moves through the system, how failures are handled, and how individual components cooperate without becoming tightly coupled.
Apache Kafka provides distributed event delivery. The Transactional Outbox pattern improves consistency between database transactions and message publication. Asynchronous workers isolate slow external operations. Server-Sent Events provide efficient one-way real-time communication. Java Records help establish clear and immutable data contracts.
Together, these techniques provide a foundation for building backend systems that are easier to scale, maintain, and operate.
The most important architectural principle is simple:
A successful business transaction should not depend on every secondary operation completing immediately.
Once that principle is reflected in the design, backend applications become significantly more resilient to external failures, traffic spikes, and increasing system complexity.
Modern backend engineering is ultimately about controlling complexity while preserving reliability.
Comments (0)
No comments yet; be the first.
Leave a comment