Implementing Transaction Management

1. Understanding ACID Properties

PropertyMeaning
AtomicityAll or nothing
ConsistencyConstraints hold before/after
IsolationConcurrent tx don't interfere (per level)
DurabilityCommitted data survives crash

2. Implementing Declarative Transactions

Example: @Transactional

@Service
public class TransferService {
    @Transactional
    public void transfer(AccountId from, AccountId to, Money amount) {
        accounts.withdraw(from, amount);
        accounts.deposit(to, amount);
    }
}
Warning: Spring proxies don't intercept self-invocation; calling this.method() bypasses transactional advice.

3. Implementing Programmatic Transactions

Example: TransactionTemplate

txTemplate.executeWithoutResult(status -> {
    try {
        accounts.withdraw(from, amount);
        accounts.deposit(to, amount);
    } catch (InsufficientFunds e) {
        status.setRollbackOnly();
        throw e;
    }
});

4. Designing Transaction Boundaries

RuleDetail
One use case = one txService method scope
Keep shortAvoid long DB locks
No remote calls insideFailures hold locks
No user input waitBegin only after input received

5. Understanding Transaction Isolation Levels

LevelDirty ReadNon-RepeatPhantom
READ UNCOMMITTEDYesYesYes
READ COMMITTEDNoYesYes
REPEATABLE READNoNoYes (PG: No)
SERIALIZABLENoNoNo

6. Implementing Transaction Propagation

PropagationBehavior
REQUIREDJoin existing or create (default)
REQUIRES_NEWSuspend, start new
NESTEDSavepoint inside outer
MANDATORYMust have existing
SUPPORTSJoin if exists
NEVERFail if exists
NOT_SUPPORTEDSuspend if exists

7. Implementing Optimistic Locking

MechanismDetail
JPA @VersionAuto-checked on update
ConflictOptimisticLockException
RetryRe-read, re-apply, save
Best forLow contention scenarios

8. Implementing Pessimistic Locking

Example: SELECT ... FOR UPDATE

@Lock(LockModeType.PESSIMISTIC_WRITE)
@Query("select a from Account a where a.id = :id")
Account lockById(@Param("id") Long id);
Warning: Always lock in consistent order to avoid deadlock.

9. Handling Transaction Rollback

ScenarioSpring Behavior
RuntimeExceptionRollback (default)
Checked exceptionCommit (configure rollbackFor)
ManualTransactionStatus.setRollbackOnly()
Caught exceptionNo rollback unless re-thrown

10. Implementing Read-Only Transactions

BenefitDetail
Hibernate skip dirty checkPerformance
DB hintMay route to replica
Prevent accidental writesSafer query methods

Example: read-only flag

@Transactional(readOnly = true)
public List<Order> search(OrderFilter f) { ... }

11. Understanding Distributed Transactions

PatternTrade-off
2PC (XA)Strong; slow, blocking
Saga (orchestration)Eventual; central coordinator
Saga (choreography)Eventual; via events
Outbox + idempotent consumerReliable event publish

12. Implementing Savepoints

Example: Nested rollback

@Transactional
public void process(List<Item> items) {
    for (Item i : items) {
        try { txTemplate.execute(s -> { processOne(i); return null; }); }
        catch (Exception e) { failed.add(i); }  // outer continues
    }
}