Skip to main content
skill CX Codex

spring-boot-event-driven-patterns — Claude Code skill: events

A Spring Boot 3.x skill for domain events, @TransactionalEventListener, Kafka messaging and the transactional outbox pattern. Useful when sync calls between services need to become events.

Install into Claude Code · Skills CLI (Vercel) All methods and platforms ↓
npx skills add giuseppe-trisciuoglio/developer-kit --skill spring-boot-event-driven-patterns -a claude-code
Open on GitHub

What spring-boot-event-driven-patterns does

The skill hands your agent a set of event-driven architecture patterns for Spring Boot. It covers domain events built on a DomainEvent base class with eventId, occurredAt and correlationId, publishing through ApplicationEventPublisher, and handling in @TransactionalEventListener with the AFTER_COMMIT phase so the listener runs only after the transaction commits.

A separate section deals with distributed messaging over Kafka: KafkaTemplate for producing, @KafkaListener for consuming, serializer settings in application.yml, plus the functional Spring Cloud Stream model with Consumer beans. For reliable delivery there is the transactional outbox — an OutboxEvent entity stores the event in the same transaction as the business data, and a scheduled processor publishes what is pending. Failed messages get retries via @RetryableTopic and a dead-letter topic.

The skill reads and writes files and runs commands: Read, Write, Edit and Bash are allowed. The Kafka part needs a broker, and the sample configuration points at localhost:9092. Without one running you cannot actually verify the producer and consumer templates, so set up the environment first.

What it helps with

  • replace blocking calls between services with published events
  • fire a listener only after the database transaction commits
  • wire a Kafka producer and consumer into Spring Boot
  • store an event in the same transaction as business data via outbox
  • add retries and a dead-letter topic for failed messages

Example prompts for the agent

  • Refactor processOrder so it publishes a domain event after saving the order, and move inventory reservation and payment into the handler.
  • Set up a @KafkaListener for the product-events topic and add @RetryableTopic with 3 attempts.
  • Show me the transactional outbox: the OutboxEvent entity and a processor that publishes pending events.

How to install spring-boot-event-driven-patterns

1Skills CLI (Vercel)

npx skills add giuseppe-trisciuoglio/developer-kit --skill spring-boot-event-driven-patterns -a claude-code

2Manually: put the files in place

~/.claude/skills/spring-boot-event-driven-patterns/SKILL.md

Copy the whole skill folder; for one project use .claude/skills/spring-boot-event-driven-patterns/

Step by step, with commands for each platform: How to install skills in Claude Code: five ways

Questions about spring-boot-event-driven-patterns

How do I install spring-boot-event-driven-patterns in Claude?

Run npx skills add giuseppe-trisciuoglio/developer-kit --skill spring-boot-event-driven-patterns -a claude-code. The skill lands in ~/.claude/skills/spring-boot-event-driven-patterns/SKILL.md.

What does spring-boot-event-driven-patterns do?

It provides event-driven architecture patterns for Spring Boot: domain events, @TransactionalEventListener with the AFTER_COMMIT phase, Kafka producers and consumers, the transactional outbox, and failure handling with retries and dead-letter topics.

What do I need for the Kafka part to work?

The sample configuration points at a broker on localhost:9092, so you need Kafka running to test the producer and consumer. The skill is allowed to use Read, Write, Edit and Bash.

Source text

SKILL.md · MIT
---
name: spring-boot-event-driven-patterns
description: Provides Event-Driven Architecture (EDA) patterns for Spring Boot — creates domain events, configures ApplicationEvent and @TransactionalEventListener, sets up Kafka producers and consumers, and implements the transactional outbox pattern for reliable distributed messaging. Use when implementing event-driven systems in Spring Boot, setting up async messaging with Kafka, publishing domain events from DDD aggregates, or needing reliable event publishing with the outbox pattern.
allowed-tools: Read, Write, Edit, Bash
---

# Spring Boot Event-Driven Patterns

## Overview

Implement Event-Driven Architecture (EDA) patterns in Spring Boot 3.x using domain events, ApplicationEventPublisher, `@TransactionalEventListener`, and distributed messaging with Kafka and Spring Cloud Stream.

## When to Use

- Implementing event-driven microservices with Kafka messaging
- Publishing domain events from aggregate roots in DDD architectures
- Setting up transactional event listeners that fire after database commits
- Adding async messaging with producers and consumers via Spring Kafka
- Ensuring reliable event delivery using the transactional outbox pattern
- Replacing synchronous calls with event-based communication between services

## Quick Reference

| Concept | Description |
|---------|-------------|
| **Domain Events** | Immutable events extending `DomainEvent` base class with eventId, occurredAt, correlationId |
| **Event Publishing** | `ApplicationEventPublisher.publishEvent()` for local, `KafkaTemplate` for distributed |
| **Event Listening** | `@TransactionalEventListener(phase = AFTER_COMMIT)` for reliable handling |
| **Kafka** | `@KafkaListener(topics = "...")` for distributed event consumption |
| **Spring Cloud Stream** | Functional programming model with `Consumer` beans |
| **Outbox Pattern** | Atomic event storage with business data, scheduled publisher |

## Examples

### Monolithic to Event-Driven Refactoring

**Before (Anti-Pattern):**
```java
@Transactional
public Order processOrder(OrderRequest request) {
    Order order = orderRepository.save(request);
    inventoryService.reserve(order.getItems()); // Blocking
    paymentService.charge(order.getPayment()); // Blocking
    emailService.sendConfirmation(order); // Blocking
    return order;
}
```

**After (Event-Driven):**
```java
@Transactional
public Order processOrder(OrderRequest request) {
    Order order = Order.create(request);
    orderRepository.save(order);

    // Publish event after transaction commits
    eventPublisher.publishEvent(new OrderCreatedEvent(order.getId(), order.getItems()));

    return order;
}

@Component
public class OrderEventHandler {
    @TransactionalEventListener(phase = TransactionPhase.AFTER_COMMIT)
    public void handleOrderCreated(OrderCreatedEvent event) {
        // Execute asynchronously after the order is saved
        inventoryService.reserve(event.getItems());
        paymentService.charge(event.getPayment());
    }
}
```

See [examples.md](references/examples.md) for complete working examples.

## Instructions

### 1. Design Domain Events

Create immutable event classes extending a base `DomainEvent` class:

```java
public abstract class DomainEvent {
    private final UUID eventId;
    private final LocalDateTime occurredAt;
    private final UUID correlationId;
}

public class ProductCreatedEvent extends DomainEvent {
    private final ProductId productId;
    private final String name;
    private final BigDecimal price;
}
```

See [domain-events-design.md](references/domain-events-design.md) for patterns.

### 2. Publish Events from Aggregates

Add domain events to aggregate roots, publish via `ApplicationEventPublisher`:

```java
@Service
@Transactional
public class ProductService {
    public Product createProduct(CreateProductRequest request) {
        Product product = Product.create(request.getName(), request.getPrice(), request.getStock());
        repository.save(product);

        product.getDomainEvents().forEach(eventPublisher::publishEvent);
        product.clearDomainEvents();

        return product;
    }
}
```

See [aggregate-root-patterns.md](references/aggregate-root-patterns.md) for DDD patterns.

### 3. Handle Events Transactionally

Use `@TransactionalEventListener` for reliable event handling:

```java
@Component
public class ProductEventHandler {
    @TransactionalEventListener(phase = TransactionPhase.AFTER_COMMIT)
    public void onProductCreated(ProductCreatedEvent event) {
        notificationService.sendProductCreatedNotification(event.getName());
    }
}
```

**Validate:** Confirm the event handler fires only after the transaction commits by checking that the database state is committed before the handler executes.

See [event-handling.md](references/event-handling.md) for handling patterns.

### 4. Configure Kafka Infrastructure

Configure KafkaTemplate for publishing, `@KafkaListener` for consuming:

```yaml
spring:
  kafka:
    bootstrap-servers: localhost:9092
    producer:
      value-serializer: org.springframework.kafka.support.serializer.JsonSerializer
```

**Validate:** Send a test event via `KafkaTemplate` and confirm it appears in the consumer logs before proceeding to production patterns.

See [dependency-setup.md](references/dependency-setup.md) and [configuration.md](references/configuration.md).

### 5. Implement Outbox Pattern

Create `OutboxEvent` entity for atomic event storage:

```java
@Entity
public class OutboxEvent {
    private UUID id;
    private String aggregateId;
    private String eventType;
    private String payload;
    private LocalDateTime publishedAt;
}
```

**Validate:** Confirm the scheduled processor picks up pending events by checking the `publishedAt` timestamp is set after the scheduled run.

Scheduled processor publishes pending events. See [outbox-pattern.md](references/outbox-pattern.md).

### 6. Handle Failure Scenarios

Implement retry logic, dead-letter queues, idempotent handlers:

```java
@RetryableTopic(attempts = "3")
@KafkaListener(topics = "product-events")
public void handleProductEvent(ProductCreatedEventDto event) {
    orderService.onProductCreated(event);
}
```

**Validate:** Confirm messages reach the dead-letter topic after exhausting retries before moving to observability.

### 7. Add Observability

Enable Spring Cloud Sleuth for distributed tracing, monitor metrics.

## Best Practices

- **Use past tense naming**: `ProductCreated` (not `CreateProduct`)
- **Keep events immutable**: All fields should be final
- **Include correlation IDs**: For tracing events across services
- **Use AFTER_COMMIT phase**: Ensures events are published after successful database transaction
- **Implement idempotent handlers**: Handle duplicate events gracefully
- **Add retry mechanisms**: For failed event processing with exponential backoff
- **Implement dead-letter queues**: For events that fail processing after retries
- **Log all failures**: Include sufficient context for debugging
- **Make handlers order-independent**: Event ordering is not guaranteed in distributed systems
- **Batch event processing**: When handling high volumes
- **Monitor event latencies**: Set up alerts for slow processing

## References

- **[dependency-setup.md](references/dependency-setup.md)** — Maven/Gradle dependencies
- **[configuration.md](references/configuration.md)** — Kafka and Spring Cloud Stream configuration
- **[domain-events-design.md](references/domain-events-design.md)** — Domain event design patterns
- **[aggregate-root-patterns.md](references/aggregate-root-patterns.md)** — Aggregate root with event publishing
- **[event-publishing.md](references/event-publishing.md)** — Local and distributed event publishing
- **[event-handling.md](references/event-handling.md)** — Event handling and consumption patterns
- **[outbox-pattern.md](references/outbox-pattern.md)** — Transactional outbox pattern for reliability
- **[testing-strategies.md](references/testing-strategies.md)** — Unit and integration testing approaches
- **[examples.md](references/examples.md)** — Complete working examples
- **[event-driven-patterns-reference.md](references/event-driven-patterns-reference.md)** — Detailed reference documentation

## Constraints and Warnings

- Events published with `@TransactionalEventListener` only fire after transaction commit
- Avoid publishing large objects in events (memory pressure, serialization issues)
- Be cautious with async event handlers (separate threads, concurrency issues)
- Kafka consumers must handle duplicate messages (implement idempotent processing)
- Event ordering is not guaranteed in distributed systems (design handlers to be order-independent)
- Never perform blocking operations in event listeners on the main transaction thread
- Monitor for event processing backlogs (indicate system capacity issues)

## Related Skills

- `spring-boot-security-jwt` — JWT authentication for secure event publishing
- `spring-boot-test-patterns` — Testing event-driven applications
- `aws-sdk-java-v2-lambda` — Event-driven processing with AWS Lambda
- `langchain4j-tool-function-calling-patterns` — AI-driven event processing

© giuseppe-trisciuoglio · MIT · giuseppe-trisciuoglio/developer-kit

Similar skills

Everything for Backend and APIs →

From the same set93

unit-test-service-layer A skill that gives the agent a Mockito pattern for service-layer unit tests: mock repositories, verify calls, cover exception paths. CX Codex +1 3,800installs nestjs-best-practices A skill that hands your agent a rulebook for NestJS: module boundaries, provider scopes, exception filters, DTO validation and Drizzle ORM. CX Codex +1 3,800installs spring-boot-cache Configures caching in Spring Boot services using Caffeine, Redis, or Ehcache providers. Helps set up TTL policies, apply cache annotations, and trace cache misses. CX Codex +1 3,800installs zod-validation-utilities Guides Zod v4 validation for TypeScript APIs, forms, and configuration. Use it when external input needs parsing, coercion, and clear validation errors. CX Codex +1 3,800installs chunking-strategy Configures document chunking workflows and overlap for RAG pipelines and vector search. It validates semantic coherence and tunes retrieval precision. CX Codex +1 3,800installs aws-sdk-java-v2-rds Guides AI agents in managing Amazon RDS databases via the AWS SDK for Java 2.x. Useful for provisioning instances, snapshots, and parameter groups. CX Codex +1 3,700installs aws-sdk-java-v2-kms This skill provides AWS KMS patterns for AWS SDK for Java 2.x, covering keys, encryption, data keys, signatures, and Spring Boot integration. CX Codex +1 3,700installs aws-sdk-java-v2-secrets-manager A skill for pulling AWS Secrets Manager values into Java services: retrieval, caching, rotation-aware access and Spring Boot wiring. CX Codex +1 3,700installs

Project sponsors

Companies that keep this analytics open
Gold sponsor

Impressions, clicks and code copies — open statistics. We keep the numbers public for the same reason NeBlask itself is public. Become a sponsor