Scrivio Interview library
DebuggingIntermediate6 min read · updated 12 November 2026

A @PostPersist listener sends a Kafka message that a new customer was created. Sometimes the message is sent but the customer is missing in the database. Why?

@PostPersist runs right after the INSERT is executed, or at persist() time for IDENTITY ids, not after the transaction commits, so the transaction can still roll back after the message has gone. Consumers then see a customer that never existed. Publishing from @TransactionalEventListener(phase = AFTER_COMMIT) fixes the ordering but can lose the message if the process crashes between commit and send; for reliable delivery we write an outbox row in the same transaction and relay it to Kafka. In general, JPA callbacks should not have side effects in external systems.

Why this question is asked

This bug is a textbook case of two systems disagreeing about what happened: the database rolled back, but Kafka already told the world. Downstream services then send welcome emails, create accounts or bill a customer who does not exist, and the cause is hard to find because the code looks correct and works most of the time. Interviewers ask it to see whether we understand when JPA callbacks run relative to the commit, and whether we know the patterns for publishing events reliably. In this answer, we will see exactly when @PostPersist runs, reproduce the bug, and then fix it in two steps: after-commit publishing and the outbox.

1A Quick Recap: When @PostPersist Runs

@PostPersist is a JPA lifecycle callback that runs after an entity has been made persistent, which means after its INSERT. When that INSERT happens depends on the id strategy. With a sequence or UUID id, Hibernate usually delays the INSERT until flush, so @PostPersist runs during the flush, typically just before commit. With an IDENTITY id, Hibernate must insert immediately to learn the id, so @PostPersist runs at the persist() call itself.

In both cases the transaction is still open. The row exists only inside this transaction. Nothing guarantees that the commit will happen: a later statement can fail, a constraint can be violated at commit, or the code can throw an exception, and then the INSERT is rolled back.

2Reproducing the Bug

Here is the code in question, followed by a failure later in the same transaction.

Java
public class CustomerEvents {
@PostPersist
void created(Customer c) { kafka.send("customers", c.getId().toString(), "created"); } // sent now
}
@Transactional
public void register(SignUp s) {
Customer c = customerRepo.save(new Customer(s.email())); // IDENTITY: insert, then @PostPersist -> message sent
accountRepo.save(new Account(c, s.plan())); // throws: plan not found
}
// Kafka topic customers: key=871 value=created
// database: transaction rolled back, customer 871 does not exist
Step throughThe message escapes before the commit
ServiceHibernateDatabaseKafka
save(customer)
INSERT customer 871
@PostPersist: send created 871
save(account)
exception: plan not found
ROLLBACK: customer 871 removed
consumers already read created 871

7 messages in order. Play them, or step through them one at a time.

The database and Kafka now disagree about whether customer 871 exists.

Notice the order of events: the message leaves at the moment of the insert, and the failure comes after. The consumer reads customer 871 created and looks it up, but the row is gone. The bug is intermittent because it shows only when something fails after the insert in the same transaction. There is also a milder version of the same race: even when the commit succeeds, a fast consumer can look the customer up before the commit is visible and conclude that it is missing.

3Fix 1: Publish After Commit

Spring can hold an event until the transaction finishes. The service publishes an application event, and a method annotated with @TransactionalEventListener runs only in the chosen phase. The default phase is AFTER_COMMIT, so if the transaction rolls back, the listener never runs.

Java
@Transactional
public void register(SignUp s) {
Customer c = customerRepo.save(new Customer(s.email()));
accountRepo.save(new Account(c, s.plan()));
events.publishEvent(new CustomerCreated(c.getId())); // held until the transaction ends
}
@Component
class CustomerCreatedPublisher {
@TransactionalEventListener(phase = TransactionPhase.AFTER_COMMIT)
void on(CustomerCreated e) { kafka.send("customers", e.id().toString(), "created"); }
}
// rollback: no message; commit: message sent after the row is visible

This removes the ghost customers. But there is a catch: the commit and the send are still two separate steps. If the process crashes, is killed during a deployment, or Kafka is unreachable right after the commit, the customer exists but the message is never sent. For a cache refresh that may be acceptable; for billing or provisioning it is not.

4Fix 2: The Transactional Outbox

The outbox pattern makes the message part of the same transaction as the data. Instead of sending to Kafka, the service inserts a row into an outbox table in the same database, in the same transaction. Either both the customer and the outbox row commit, or neither does. A separate relay then reads committed outbox rows, publishes them to Kafka and marks them as sent, retrying until Kafka accepts them.

Java
@Transactional
public void register(SignUp s) {
Customer c = customerRepo.save(new Customer(s.email()));
accountRepo.save(new Account(c, s.plan()));
outboxRepo.save(new OutboxEvent("customers", c.getId().toString(), "created")); // same transaction
}
// commit: customer 871 and outbox row 5501 are both stored
// relay (polling or change data capture such as Debezium): send 5501 to Kafka, then mark it sent
Step throughChoosing how to publish
  1. Is losing a message acceptable?
    Yesafter-commit listenerNotransactional outbox
  2. Outbox row in the same transactioncommits or rolls back with the data
  3. Relay publishes committed rowspolling or change data capture
  4. Consumers deduplicate by event iddelivery is at least once

4 steps in order. Play them, or step through them one at a time.

The relay delivers at least once: if it crashes after sending but before marking the row, it sends the message again. So consumers must be idempotent, for example by remembering processed event ids. In exchange, no message is lost and no message describes data that was rolled back.

5Keep External Side Effects Out of JPA Callbacks

The underlying rule is that JPA callbacks are part of the persistence operation and run before the outcome of the transaction is known. They are a good place to set fields on the entity itself and a bad place for anything another system can observe: messages, emails, HTTP calls, files. Even after-commit work belongs in the service layer, where it is explicit and testable, rather than hidden in an entity listener that runs whenever any code persists a customer.

6Follow-up questions

Would @PostPersist be safe with a sequence id, since the insert happens at flush?

No. The insert, and so the callback, still happens before commit, and the commit itself can fail, for example on a deferred constraint, a serialization failure or a lost connection. Only the timing inside the transaction changes.

Can we use Kafka transactions to make this atomic?

Kafka transactions make writes to several Kafka partitions atomic, but they do not span the database. Coordinating them with the database commit brings back the dual-write problem. The outbox keeps one source of truth, the database, and makes Kafka follow it.

What does @TransactionalEventListener do if there is no transaction?

By default the event is dropped, because there is no transaction phase to wait for. Setting fallbackExecution = true makes it run immediately in that case, which is useful when the same event is published from both transactional and non-transactional code.

7Conclusion

In this answer, we saw that @PostPersist runs after the INSERT, or at persist() for IDENTITY ids, but always before the commit, so a later failure rolls back the customer after the Kafka message has already been sent. Publishing with @TransactionalEventListener(phase = AFTER_COMMIT) removes the ghost messages but can lose one on a crash, while a transactional outbox with a relay and idempotent consumers gives reliable delivery. External side effects do not belong in JPA callbacks.

What to say in the interviewAbout 90 seconds aloud

Open with

The problem is timing. PostPersist does not mean after commit; it runs right after the INSERT is executed, which with an IDENTITY id is at the persist call itself, and with sequences is during the flush.

Then, if they want more

Either way, the transaction is still open. So the listener sends created to Kafka, then something later in the transaction fails, say saving the account, or the commit itself fails, the database rolls back, and consumers process a customer that never existed. It only shows up when something fails after the insert, which is why it looks random.

The first fix is to move publishing out of the JPA callback and into the service: publish an application event and handle it with TransactionalEventListener in the AFTER_COMMIT phase, so nothing is sent on rollback. That still has a gap: if the process crashes or Kafka is down right after the commit, the message is lost.

If the downstream needs every event, I would use a transactional outbox: insert an outbox row in the same transaction as the customer, so they commit or roll back together, and have a relay, polling or change data capture like Debezium, publish committed rows to Kafka and mark them sent. That is at-least-once delivery, so consumers need to be idempotent.

The general rule I follow is no side effects in external systems from JPA callbacks.

About this answer

Last updated
12 November 2026
Checked
Its structure and format are checked automatically. Use it as a carefully prepared study note: where a detail matters, confirm it against the documentation below. What the checks cover
Where the question comes from
Written by Scrivio for practice. It is not taken from an interview.
Report an issue with this answer

Copy the line below and send it to the author with what you found. It carries the address of this page.

Issue with "A @PostPersist listener sends a Kafka message that a new customer was created. Sometimes...": https://scrivio-interview-library.netlify.app/databases/jpa-fundamentals/aa2152c1f2/