Keeping database writes and events consistent with Outbox
Solve dual-write failures in Spring Boot and PostgreSQL using the Transactional Outbox pattern, FOR UPDATE SKIP LOCKED polling, and idempotent consumers.
Saving a row to PostgreSQL and sending an event to an external service cannot share a single transaction. This post explains how I fixed dropped and duplicate registration notifications using the Transactional Outbox pattern and a
FOR UPDATE SKIP LOCKEDpolling relay.
Tested with Spring Boot 3.5.3, Java 21, Kotlin 2.1.21, PostgreSQL 17, and Spring Data JPA (Hibernate 6.6).
Background
When a member confirms a club event registration, our service sends an HTTP event to a separate notification server, which then dispatches Discord and email alerts. Initially I triggered that HTTP call inside @TransactionalEventListener(phase = AFTER_COMMIT), following the event pattern I wrote about in domain events and async processing.
In production, two failure modes kept biting us. First, if a deployment restarted the app right after the database commit finished, the in-memory AFTER_COMMIT listener never ran and the user never received a confirmation. Second, when the notification server processed a request slowly and timed out on our side, a retry fired and delivered the same notification twice.
This is the classic dual-write problem. Your database and an external HTTP endpoint are separate systems, so there’s always a window where one succeeds and the other fails. An AFTER_COMMIT listener lives only in JVM memory: if the process dies before delivery, the event vanishes, and any exception thrown in the listener can’t roll back a transaction that already committed.
How the Transactional Outbox pattern works
The fix is to turn external event publishing into a local database write. Inside the same transaction that saves the registration, you insert an event row into an outbox_event table. Because both writes share one PostgreSQL transaction, they either commit together or roll back together. A separate background relay then polls unpublished rows and delivers them.
flowchart TD
A["Registration transaction"] --> B["INSERT registration + outbox_event"]
B --> C["Database commit"]
C --> D["Relay poll (FOR UPDATE SKIP LOCKED)"]
D --> E["Send to notification server"]
E --> F["Update published_at"]
One layer deeper, when multiple application instances run the relay concurrently, PostgreSQL’s FOR UPDATE SKIP LOCKED prevents two relays from grabbing the same rows. Any row already locked by another transaction is skipped without blocking, so each relay instance claims a disjoint batch. I covered how row locks interact with MVCC in transaction isolation levels and MVCC.
This design guarantees at-least-once delivery, not exactly-once. If the relay sends the HTTP request and crashes before updating published_at, the next poll sends the same event again. That means the consumer must be idempotent.
Implementation
1
2
3
4
5
6
7
// build.gradle.kts
dependencies {
implementation("org.springframework.boot:spring-boot-starter-web")
implementation("org.springframework.boot:spring-boot-starter-data-jpa")
implementation("com.fasterxml.jackson.module:jackson-module-kotlin")
runtimeOnly("org.postgresql:postgresql")
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
-- src/main/resources/db/outbox.sql
CREATE TABLE outbox_event (
id BIGSERIAL PRIMARY KEY,
event_id UUID NOT NULL UNIQUE,
aggregate_type VARCHAR(50) NOT NULL,
aggregate_id VARCHAR(50) NOT NULL,
event_type VARCHAR(100) NOT NULL,
payload JSONB NOT NULL,
created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
published_at TIMESTAMPTZ,
attempts INT NOT NULL DEFAULT 0
);
-- Partial index keeps polling cost flat as historical rows accumulate
CREATE INDEX idx_outbox_unpublished ON outbox_event (id) WHERE published_at IS NULL;
1
2
3
4
5
# src/main/resources/application.yml
outbox:
relay:
fixed-delay: 2s
batch-size: 50
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
// src/main/kotlin/com/example/club/outbox/OutboxWriter.kt
package com.example.club.outbox
import com.fasterxml.jackson.databind.ObjectMapper
import org.springframework.jdbc.core.simple.JdbcClient
import org.springframework.stereotype.Component
import org.springframework.transaction.annotation.Propagation
import org.springframework.transaction.annotation.Transactional
import java.util.UUID
@Component
class OutboxWriter(
private val jdbcClient: JdbcClient,
private val objectMapper: ObjectMapper,
) {
// Fails fast if called outside an active transaction so outbox rows always commit with domain data
@Transactional(propagation = Propagation.MANDATORY)
fun append(aggregateType: String, aggregateId: String, eventType: String, payload: Any) {
jdbcClient.sql(
"""
INSERT INTO outbox_event (event_id, aggregate_type, aggregate_id, event_type, payload)
VALUES (:eventId, :aggregateType, :aggregateId, :eventType, CAST(:payload AS jsonb))
""".trimIndent()
)
.param("eventId", UUID.randomUUID())
.param("aggregateType", aggregateType)
.param("aggregateId", aggregateId)
.param("eventType", eventType)
.param("payload", objectMapper.writeValueAsString(payload))
.update()
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
// src/main/kotlin/com/example/club/registration/RegistrationService.kt
package com.example.club.registration
import com.example.club.outbox.OutboxWriter
import org.springframework.stereotype.Service
import org.springframework.transaction.annotation.Transactional
data class RegistrationConfirmed(val registrationId: Long, val eventId: Long, val memberId: Long)
@Service
class RegistrationService(
private val registrationRepository: RegistrationRepository,
private val outboxWriter: OutboxWriter,
) {
@Transactional
fun confirm(eventId: Long, memberId: Long): Long {
val saved = registrationRepository.save(Registration(eventId = eventId, memberId = memberId))
outboxWriter.append(
aggregateType = "Registration",
aggregateId = saved.id.toString(),
eventType = "RegistrationConfirmed",
payload = RegistrationConfirmed(saved.id!!, eventId, memberId),
)
return saved.id!!
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
// src/main/kotlin/com/example/club/outbox/OutboxRelay.kt
package com.example.club.outbox
import org.slf4j.LoggerFactory
import org.springframework.beans.factory.annotation.Value
import org.springframework.jdbc.core.simple.JdbcClient
import org.springframework.scheduling.annotation.Scheduled
import org.springframework.stereotype.Component
import org.springframework.transaction.annotation.Transactional
import java.util.UUID
data class OutboxRow(val id: Long, val eventId: UUID, val eventType: String, val payload: String)
@Component
class OutboxRelay(
private val jdbcClient: JdbcClient,
private val notificationClient: NotificationClient,
@Value("\${outbox.relay.batch-size}") private val batchSize: Int,
) {
private val log = LoggerFactory.getLogger(javaClass)
@Scheduled(fixedDelayString = "\${outbox.relay.fixed-delay}")
@Transactional
fun relay() {
val rows = jdbcClient.sql(
"""
SELECT id, event_id, event_type, payload::text AS payload
FROM outbox_event
WHERE published_at IS NULL AND attempts < 10
ORDER BY id
LIMIT :limit
FOR UPDATE SKIP LOCKED
""".trimIndent()
)
.param("limit", batchSize)
.query(OutboxRow::class.java)
.list()
for (row in rows) {
try {
// Pass event_id in the Idempotency-Key header so the consumer can deduplicate
notificationClient.send(row.eventId, row.eventType, row.payload)
jdbcClient.sql("UPDATE outbox_event SET published_at = now() WHERE id = :id")
.param("id", row.id).update()
} catch (e: Exception) {
log.warn("Outbox relay failed id={} type={}", row.id, row.eventType, e)
jdbcClient.sql("UPDATE outbox_event SET attempts = attempts + 1 WHERE id = :id")
.param("id", row.id).update()
break // Stop this batch so later events aren't sent ahead of a failed one
}
}
}
}
Enable scheduling with @EnableScheduling on a configuration class. On the receiving notification server, run INSERT INTO processed_event(event_id) VALUES (:eventId) ON CONFLICT (event_id) DO NOTHING first. If zero rows are affected, treat the event as already processed and skip it. Wrap that insert and the actual dispatch record in the same transaction to make deduplication airtight.
Comparing approaches and when not to use Outbox
| Approach | Event loss risk | Operational overhead | Best fit |
|---|---|---|---|
AFTER_COMMIT + direct call | Lost on restart or crash | Very low | Best-effort cache invalidation or analytics |
| Outbox + polling relay | Very low | One table + scheduled job | Small to medium services on a single DB |
| Outbox + CDC (Debezium) | Very low | Kafka + Kafka Connect cluster | High-throughput systems already running a broker |
CDC reads PostgreSQL’s WAL directly and streams outbox_event inserts to a message broker without polling latency or extra read load—Debezium even ships an Outbox Event Router SMT. Still, running logical replication slots, Kafka, and Kafka Connect was way too much infrastructure for a student club service, so a polling relay hit the sweet spot.
There are also times not to use Outbox. Don’t add an outbox table and cleanup job for non-critical side effects where dropping an occasional event is acceptable. If the downstream system can’t be made idempotent (for example, a third-party webhook with no deduplication key), Outbox alone won’t prevent duplicate side effects. And if you need end-to-end delivery latency under a few dozen milliseconds, a polling interval introduces noticeable delay.
Production caveats and cleanup
Notice that the relay above holds row locks and a database connection open while the HTTP call is in flight. If the notification server slows down, that transaction stretches out—so always put a short read timeout on
notificationClient. Also, running multiple relay instances withSKIP LOCKEDcan deliver two events for the same aggregate out of order. If strict ordering matters, either run a single active relay instance or attach an aggregate version number so consumers ignore stale events.
Published rows grow indefinitely unless you prune them. Deleting millions of rows in one query causes long locks and WAL spikes, so clean them up in small batches.
1
2
3
4
5
6
7
8
-- Run nightly: delete published rows older than 7 days in 1,000-row chunks
DELETE FROM outbox_event
WHERE id IN (
SELECT id FROM outbox_event
WHERE published_at < now() - INTERVAL '7 days'
ORDER BY id
LIMIT 1000
);
- Is the outbox write enforced inside the business transaction (for example, via
Propagation.MANDATORY)? - Does the consumer deduplicate incoming events by
event_id? - Does the relay’s HTTP client enforce a short read timeout so DB connections aren’t held open?
- If event order matters, have you restricted the relay to a single worker or added version checks on the consumer?
- Are you alerting on rows that hit the
attemptslimit and running a batched cleanup job for old published rows?