0 day streak
java / intermediate
Snippet

Compensating Actions on Transaction Rollback Using TransactionPhase

When a transactional method fails and rolls back, domain operations inside that transaction are undone. Using @TransactionalEventListener with TransactionPhase.AFTER_ROLLBACK lets you execute compensating actions, cleanup jobs, or persistent failure logs after a transaction aborts without contaminating the primary transaction context.

snippet.java
java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
@Component
public class PaymentAuditLogger {
private final AuditLogRepository auditLogRepository;
public PaymentAuditLogger(AuditLogRepository auditLogRepository) {
this.auditLogRepository = auditLogRepository;
}
@Async
@TransactionalEventListener(phase = TransactionPhase.AFTER_ROLLBACK)
public void handlePaymentFailure(PaymentFailedEvent event) {
AuditRecord failureRecord = new AuditRecord(
event.orderId(),
event.reason(),
event.timestamp()
);
auditLogRepository.save(failureRecord);
}
}
spring
Breakdown
1
@Async
Executes the event listener on a detached thread pool to avoid blocking the caller during rollback processing.
2
@TransactionalEventListener(phase = TransactionPhase.AFTER_ROLLBACK)
Configures the listener to trigger exclusively if the originating transaction fails and rolls back.
3
public void handlePaymentFailure(PaymentFailedEvent event)
Receives the strongly-typed failure domain event published during the unsuccessful business operation.
4
auditLogRepository.save(failureRecord);
Persists failure details independently in a new, separate database transaction.