Catalogue / spring-event-outbox-sagas
spring-event-outbox-sagas
Older skill: source not recordedSignedBuilds reliable event-driven Java services on Spring: local domain events with transaction-aware listeners, Kafka and Spring Cloud Stream contracts, the transactional outbox with an ack-gated relay, idempotent consumers, sagas and event-sourcing replay. Use when the user asks to "publish domain even…--- name: spring-event-outbox-sagas description: >- Builds reliable event-driven Java services on Spring: local domain events with transaction-aware listeners, Kafka and Spring Cloud Stream contracts, the transactional outbox with an ack-gated relay, idempotent consumers, sagas and event-sourcing replay. Use when the user asks to "publish domain events after commit", "set up an outbox pattern", "make a Kafka consumer idempotent", "wire a saga with compensation", or "replay events safely". Not for non-JVM messaging systems, GUI dashboarding, or guaranteeing exactly-once external side effects. ---
Choose the consistency boundary
Four layers, four guarantees — pick deliberately:
| Layer | Survives a crash? | Atomic with your DB commit? | |---|---|---| | In-process ApplicationEventPublisher | No | Shares the caller's transaction | | Broker event (Kafka / Cloud Stream) | Yes | No — separate system | | Transactional outbox row | Yes | Yes — same transaction | | External side effect (email, payment) | Yes | Never guaranteed — needs idempotency keys |
Before writing anything, inspect the project's actual Spring Boot/Framework, Kafka and Cloud Stream versions, the broker and database configuration, and the transaction manager in use. Pull dependencies through the project's BOM: spring-context, spring-web if needed, spring-boot-starter-data-jpa, spring-kafka, the Cloud Stream Kafka binder, jackson-databind with the Java-time module, and spring-boot-starter-test (Testcontainers optional).
Confirm the exact scope with the user before: writing code or configuration, starting services or containers, creating topics, running migrations, publishing real events, or deploying consumers that mutate data. An existing explicit request covers that scope and its isolated tests; anything beyond needs fresh confirmation.
Design events as reconstructible facts
- Name events in past tense (
SeatsReserved, notReserveSeats). - Keep payloads immutable: event ID, aggregate ID and type, event type plus
schema version, UTC occurrence time, correlation ID, and tenant/causation metadata when the domain requires it.
- Preserve one correlation ID across the whole flow; do not mint a fresh
unrelated ID at each hop.
- Exclude payment credentials and large mutable object graphs.
- Plain records or POJOs are enough; extending
ApplicationEventis optional
and not a sign that a class is deprecated.
Let the aggregate buffer pending events after a validated state transition, expose an unmodifiable copy, and clear the buffer only after local publication or durable outbox storage succeeded. Validate stock, quantity and money constraints *before* emitting. Use optimistic locking when concurrent requests touch the same aggregate.
import java.time.Instant;
import java.util.*;
public final class SeatPool {
public record Event(UUID eventId, UUID aggregateId, String type, int schemaVersion,
Instant occurredAt, UUID correlationId, Map<String,Object> payload) {
public Event { payload = Map.copyOf(payload); }
}
private final UUID id;
private int available;
private final List<Event> pending = new ArrayList<>();
private SeatPool(UUID id, int available) { this.id=id; this.available=available; }
public static SeatPool open(int seats, UUID correlation) {
if (seats < 0) throw new IllegalArgumentException("Negative capacity");
Objects.requireNonNull(correlation);
SeatPool pool = new SeatPool(UUID.randomUUID(),seats);
pool.emit("SeatPoolOpened",correlation,Map.of("available",seats));
return pool;
}
public void reserve(int quantity, UUID correlation) {
if (quantity < 1 || quantity > available)
throw new IllegalArgumentException("Invalid reservation quantity");
Objects.requireNonNull(correlation);
available -= quantity;
emit("SeatsReserved",correlation,Map.of("quantity",quantity,"available",available));
}
private void emit(String type, UUID correlation, Map<String,Object> data) {
pending.add(new Event(UUID.randomUUID(),id,type,1,Instant.now(),correlation,data));
}
public UUID id() { return id; }
public int available() { return available; }
public List<Event> events() { return List.copyOf(pending); }
public void clearEvents() { pending.clear(); }
}Persist aggregate changes and outbox rows inside one database transaction — a serialization failure must roll back both. Initialize retry counters explicitly. Serialize stable DTOs with registered Java-time support; a Java class simple name is not a cross-service schema contract.
Time local listeners correctly
Facts about Spring's local events that most code gets wrong:
ApplicationEventPublisher.publishEvent(Object)accepts ordinary objects;
the legacy overload also takes ApplicationEvent.
- A plain
@EventListeneris synchronous under the default multicaster and
may run inside the caller's transaction.
@TransactionalEventListenerphases:BEFORE_COMMIT,AFTER_COMMIT(the
default), AFTER_ROLLBACK, AFTER_COMPLETION.
- With no active transaction, a transactional listener does not run unless
fallback execution was deliberately enabled.
- SpEL
conditionexpressions andclassesfilters can narrow a listener;
keep conditions simple and never feed arbitrary user input into them.
"AFTER_COMMIT" does not mean "another thread", and it is not a durable queue:
- Listener DB writes need their own transaction — usually
REQUIRES_NEWon a
separate proxied bean, not a self-invocation.
- Seeing committed data after commit does not prove a new transaction began.
- Slow external calls still run on the committing thread and delay the caller.
- For notifications that must not be lost, prefer outbox + broker over adding
@Async. If async local handling is genuinely right, configure a bounded executor, an error handler and context propagation explicitly.
Wire a service by constructor-injecting its repository and publisher. Inside @Transactional: save the aggregate, publish buffered events (or append outbox rows), then clear the buffer. Local audit, inventory and notification concerns become separate listeners — each must honour transaction semantics. Avoid circular listener chains that re-publish while handling.
Define broker contracts and consumer groups
Direct Kafka pairs an injected KafkaTemplate with @KafkaListener methods over a stable integration DTO. Key messages by aggregate identity so ordering holds per partition — never globally, and retries, rebalances or parallel consumers can still disturb business sequence. Configure topic, consumer group and serializers explicitly. Allowlist JSON types or decode into an explicit DTO; never set spring.json.trusted.packages='*'.
Spring Cloud Stream's functional model: a Consumer<EventEnvelop> bean receives, a Supplier<EventEnvelop> bean produces. Bindings follow <functionName>-in-0 / <functionName>-out-0; set destination, group and spring.cloud.function.definition. Remember:
- Consumers in the same group compete for records — they do not each get
every event. Use separate groups for independent projections, or one discriminator-aware consumer routing created/updated/released events.
- A polling
Suppliermust not invent a new business event per poll; it
drains already-authorized durable intent.
Configuration families to review against the installed binder version:
- Bootstrap servers / binder brokers; producer string keys + JSON values;
consumer group with validated JSON deserialization.
- Binding destinations and groups; a verified partition-key expression.
- Producer tuning such as
linger.ms=10,batch.size=1024— examples to
verify for unit and workload, not defaults to copy.
- Retry presets (for example 3 attempts, 1 000 ms initial backoff, multiplier
2.0, 10 000 ms max): classify which exceptions are retryable; validation and authentication failures are not.
- Dead-letter enablement, DLQ name and DLQ producer settings; confirm topic
provisioning and binder restrictions before trusting any key.
isolation.level=read_committedreads only committed Kafka transactions —
it does not make your SQL and the broker atomic.
Give every consumer a bounded processing deadline. Retry only on top of durable idempotency. Dead-lettered records need access control, redacted diagnostics, schema/version context, a documented investigation path and an explicitly approved re-drive. Never silently acknowledge failed business processing, and never retry a poison message forever.
Ship an outbox relay that waits for acknowledgement
The relay below is implementation-agnostic Java: Store methods run in short transactions with atomic leases and owner-token fencing, claiming only a bounded batch so a crashed worker's lease expires. The aggregate ID is the partition key and eligibility respects per-aggregate ordering.
import java.time.*;
import java.util.*;
import java.util.concurrent.*;
public final class OutboxRelay {
public record Row(UUID id, String aggregateId, String type, String payload,
UUID correlationId, int attempts) {}
public interface Store {
List<Row> claim(String worker, int limit, Instant now, Duration lease);
void acknowledged(UUID id, String worker, Instant publishedAt);
void retry(UUID id, String worker, Instant nextAttempt, String errorCode);
}
public interface Broker {
CompletionStage<Void> publish(String key, UUID eventId, String type, String payload);
}
private final Store store;
private final Broker broker;
private final String worker;
private final Clock clock;
private final Duration deadline;
public OutboxRelay(Store store, Broker broker, String worker, Clock clock,
Duration deadline) {
if (deadline.isZero() || deadline.isNegative())
throw new IllegalArgumentException("Invalid deadline");
this.store=Objects.requireNonNull(store); this.broker=Objects.requireNonNull(broker);
this.worker=Objects.requireNonNull(worker); this.clock=Objects.requireNonNull(clock);
this.deadline=deadline;
}
public int tick() {
int completed=0;
Duration lease=deadline.multipliedBy(2).plusSeconds(10);
// One row per claim so a sequential batch cannot outlive its leases.
for (int i=0;i<25;i++) {
List<Row> rows=store.claim(worker,1,clock.instant(),lease);
if (rows.isEmpty()) break;
Row row=rows.get(0);
try {
broker.publish(row.aggregateId(),row.id(),row.type(),row.payload())
.toCompletableFuture().get(deadline.toMillis(),TimeUnit.MILLISECONDS);
store.acknowledged(row.id(),worker,clock.instant());
completed++;
} catch (InterruptedException ex) {
Thread.currentThread().interrupt();
store.retry(row.id(),worker,clock.instant().plusSeconds(5),"interrupted");
break;
} catch (ExecutionException | TimeoutException | RuntimeException ex) {
long seconds=Math.min(300,1L << Math.min(8,Math.max(0,row.attempts())));
store.retry(row.id(),worker,clock.instant().plusSeconds(seconds),"publish-unconfirmed");
}
}
return completed;
}
}Adapt Broker.publish to the real KafkaTemplate.send future and treat it as complete only when the broker acknowledges. Mark the row published *after* that acknowledgement, never right after enqueueing the async send.
Consequences to state plainly:
- Ack succeeds but the DB update fails → the row is retried → the broker may
see the event twice. This is at-least-once; consumers must deduplicate.
Preview shortened. The full SKILL.md is in the pack.
| File | Size | SHA-256 |
|---|---|---|
| SKILL.md | 20.1 kB | 1973e8771d20 |
| examples.json | 2.1 kB | 5e8895f6119a |
Published verbatim from the pinned commit. Nothing is rewritten.
| Version | Pinned commit | Signed | |
|---|---|---|---|
| 1.0.0 Current | Not recorded | 2 Oct 2026 |
Locking a skill to one version needs Pro.