Video in progress

You need to keep a history of data changes. How do you choose between Hibernate Envers, CDC (Debezium) and DB triggers?

Envers gives a convenient entity-level history inside the application, but only sees changes that went through Hibernate. CDC captures any change in the database and is independent of the service. Triggers are the most reliable, but the logic stays in the database and is hard to observe.

📖 Answer

First I pin down the requirement: who needs the history? A screen for the user showing "who changed this document and when", a tamper-proof journal for an auditor, or a stream of changes for other systems? There is a different answer for each of the three.

Envers. You add @Audited, an _AUD table appears for each entity, and you can query the state by revision.

@Entity @Audited
class Contract { ... }

AuditReader reader = AuditReaderFactory.get(em);
Contract old = reader.find(Contract.class, id, revision);

Downsides: bulk JPQL, native SQL, and changes made by another service or a DBA do not reach the history. Every write is an extra INSERT, so the write load goes up noticeably. The _AUD tables grow fast.

CDC (Debezium). Reads from the WAL/binlog, so it catches a change wherever it comes from. It adds no load to the application. But the "who changed it" information is not in the WAL: you have to write the user ID to a table column (updated_by). Infrastructure: Kafka Connect, monitoring.

Triggers. In the same transaction, impossible to bypass. The strongest guarantee for an auditor. But the logic lives in the database, it is harder to version and test, and writes slow down under heavy load.

What I do in practice: Envers for an internal "change history" screen, because it is fast and cheap. A trigger or CDC for financial auditing, since the requirement is "no change may be missed". For integration: outbox or CDC, not Envers.