Spring Data JPA transaction behavior is easy to describe incorrectly because the annotation is only one part of the picture. Proxies, transaction managers, database connections, persistence contexts, flush timing, and database-specific locking rules all affect the outcome.
This article frames the issues senior Java developers are expected to reason about: how propagation changes transaction boundaries, how isolation interacts with JPA and different databases, why rollback decisions can surface later, and how optimistic locking protects—or fails to protect—concurrent updates.
All 20 answers below are free. Want the full set, every answer with a worked example?
Java Spring Boot & Microservices Interview Q&A (200 Qs)
Get the guideREQUIRES_NEW suspends the order transaction and starts a separate physical transaction for the audit insert. The audit transaction can commit successfully, after which the suspended order transaction can still roll back, leaving an audit row for an order that never committed.
@Transactional
public void placeOrder(OrderCommand command) {
orderRepository.save(createOrder(command));
auditService.record("ORDER_CREATED"); // REQUIRES_NEW
chargePayment(); // later failure
}
@Transactional(propagation = Propagation.REQUIRES_NEW)
public void record(String event) {
auditRepository.save(new AuditEvent(event));
}
Spring suspends the outer transaction, including its resources, then obtains a transaction and usually a separate persistence context for the audit call. When that inner transaction commits, its data is durable independently of the outer transaction. A later exception, deadlock, constraint violation, or rollback-only marker affects only the outer transaction. The audit row may therefore describe an attempted action, not a committed business fact; that distinction should be explicit.
Useful production signals include:
Choose the boundary deliberately:
REQUIRED so it commits or rolls back with the order.Interview takeaway: REQUIRES_NEW is appropriate only when the independent commit is intentional; otherwise the audit must share the order transaction or use an outbox.
Propagation.REQUIRED does not create a second transaction when one already exists: it joins the caller’s transaction. If the participating method fails in a way that marks that transaction rollback-only, catching the exception in the outer method does not make the transaction committable; the outer commit normally ends with UnexpectedRollbackException.
@Transactional
public void process() {
orderRepository.save(order);
try {
inventoryService.reserve(order); // REQUIRED, joins this transaction
} catch (InventoryException ex) {
log.warn("Reservation failed", ex);
}
// Commit attempt: UnexpectedRollbackException
}
Spring maintains one physical transaction but can have several logical transaction scopes. An inner REQUIRED scope that encounters a runtime exception, or an exception configured for rollback, calls the transaction manager’s rollback-only operation. Some persistence failures, such as a failed flush or constraint violation, can also make the transaction unusable. The outer scope may continue executing because the exception was caught, but the transaction manager refuses a normal commit to prevent partial success. This is different from an inner savepoint: REQUIRED has no independent rollback boundary.
Check for:
UnexpectedRollbackException; the final exception is often only the symptom.@Transactional on the actual Spring bean method. Self-invocation does not pass through Spring’s proxy, so the expected interceptor may not run.rollbackFor and noRollbackFor, and flush timing. JPA may flush at commit rather than at save.Fix it by making the business outcome explicit:
REQUIRES_NEW operation, and accept its independent-commit semantics.NESTED with a supported transaction manager and JDBC savepoints; JPA state still needs careful handling.Interview takeaway: With REQUIRED, a caught inner failure can leave the single shared transaction rollback-only, so recovery requires a real boundary, not merely a catch block.
REQUIRES_NEW suspends the caller but does not release its database connection. The inner transaction needs another connection, so a request with one suspended outer transaction and one active inner transaction can consume two pool entries; enough concurrent nesting can exhaust the pool and make all callers wait or time out.
request 1: [outer connection held] -- suspend -- [inner connection]
request 2: [outer connection held] -- suspend -- [inner connection]
request N: [outer connection held] -- suspend -- [waiting for inner]
The risk is approximately the maximum simultaneous connection demand per request multiplied by concurrency, not just the number of application threads. Multiple REQUIRES_NEW calls can increase that demand further, and an inner call can itself invoke another independent transaction. A pool may therefore be configured with enough connections for ordinary requests but not for the suspended-transaction peak. If every worker holds an outer connection while waiting for an inner connection, the system can deadlock at the pool level until connection acquisition times out. The database may show fewer active statements than expected because requests are blocked before they reach it.
Production evidence includes:
Reduce the risk deliberately:
REQUIRES_NEW inside long-running or high-concurrency transactions when the work can share the outcome.Interview takeaway: Count connections held by suspended transactions when sizing capacity; REQUIRES_NEW can turn one request into multiple simultaneous pool borrowers.
Database savepoint support is not enough for JPA NESTED propagation. Spring must have a transaction manager that can create JDBC savepoints, and the JPA persistence context must remain consistent with a partial database rollback; standard JPA does not define nested transactions or savepoints, so the call may be rejected or behave unsafely.
@Bean
JpaTransactionManager transactionManager(EntityManagerFactory emf) {
JpaTransactionManager tm = new JpaTransactionManager(emf);
tm.setNestedTransactionAllowed(true); // JDBC savepoints; not standard JPA nesting
return tm;
}
With JpaTransactionManager, nested transactions are not enabled by default. Enabling them permits savepoint-based behavior for JDBC access when the driver and connection support savepoints, but it does not turn JPA into a nested-transaction API. A rollback to a savepoint changes database state while managed entities, dirty checking, pending inserts, and the first-level cache may still reflect work that was rolled back. Flush timing can make the result surprising. With a JTA transaction manager, nested propagation is generally not available; the transaction manager may reject it rather than emulate it. Exact behavior depends on Spring, the transaction manager, provider, driver, and resource participation.
Diagnose the actual boundary:
PlatformTransactionManager Spring selected and whether nested transactions are allowed.NestedTransactionNotSupportedException.Prefer one of these designs:
REQUIRED when all work should succeed or fail together.REQUIRES_NEW when an independent commit is the real requirement, accepting extra connections and separate-transaction semantics.Interview takeaway: NESTED is a transaction-manager and resource capability, not a portable JPA feature; a database savepoint by itself does not make managed entity state safe.
Spring’s test framework commonly wraps each test method in a transaction and rolls it back afterward. That outer test transaction can make a REQUIRED service appear correct while production invokes it without a caller transaction, and it can hide or create contamination through REQUIRES_NEW commits and cached JPA state.
@SpringBootTest
@Transactional // test transaction surrounds the service call
class OrderTests {
@Test
void failureIsHandled() {
orderService.placeOrder(command); // REQUIRED joins test transaction
}
}
A test calling a REQUIRED method may never exercise its normal top-level transaction boundary: the method joins the test transaction, and all its work is rolled back by the test listener. In production, the same method may start and commit its own transaction, flush at a different point, or throw UnexpectedRollbackException only at the caller’s commit. Conversely, a REQUIRES_NEW method commits despite the test transaction’s rollback, leaving rows for later tests. The same persistence context can also return an in-memory managed entity without querying the database, masking visibility and flush problems. Context caching, @Commit, @Rollback(false), and incomplete cleanup add more order dependence.
Make the boundary visible and reproduce the failure:
REQUIRES_NEW row survives an outer rollback if that is the contract.@Commit, @Rollback, and @DirtiesContext, and avoid relying on test execution order.A test that passes alone but fails in a suite often indicates leaked committed data, shared application context state, or a transaction boundary that differs between the test and production—not necessarily a random database failure.
REQUIRES_NEW operation can commit outside the test rollback, so later tests may observe its rows unless they clean up committed state.Interview takeaway: Test with the same transaction boundary as production, because a framework-managed test transaction can both hide rollback bugs and leak independent commits.
An upgrade can expose deadlocks because isolation determines which rows or ranges remain locked, while the new database version may also change defaults, query plans, or lock acquisition order. A deadlock is not proof that isolation is incorrectly configured: two transactions can deadlock even at READ_COMMITTED if they lock the same resources in opposite orders.
Typical changes that make the problem visible include:
Diagnose and fix it in this order:
pg_locks; InnoDB reports the latest deadlock through SHOW ENGINE INNODB STATUS. Correlate SQL, transaction IDs, indexes, and application trace IDs.try {
transactionTemplate.execute(status -> service.transfer(from, to));
} catch (DeadlockLoserDataAccessException | CannotAcquireLockException ex) {
// Retry the complete transaction, not just the failed statement.
}
The trade-off is straightforward: stronger isolation can prevent anomalies but increases contention, while lower isolation improves concurrency but shifts correctness to version checks, constraints, and application logic.
Interview takeaway: I would correlate the deadlock graph with the changed plans and isolation semantics, then fix lock ordering and transaction scope before weakening isolation.
READ_COMMITTED prevents a transaction from reading another transaction's uncommitted data, but it does not prevent two transactions from reading the same committed version and then overwriting each other. In JPA, a normal entity update has no conflict predicate unless the entity uses optimistic versioning or an explicit locking strategy.
A common sequence is:
Account with balance 100.@DynamicUpdate can reduce overwritten columns, but it does not detect a conflicting update to the same row. JPQL bulk updates bypass the persistence context and need explicit care.@Entity
class Account {
@Id
Long id;
@Version
long version;
BigDecimal balance;
}
// Hibernate includes the version in the UPDATE predicate:
// update account set balance=?, version=?
// where id=? and version=?
To diagnose and correct it:
@Version to the entity and treat OptimisticLockException or Spring's translated ObjectOptimisticLockingFailureException as a conflict.set balance = balance - ? where id = ? and balance >= ?, and check the affected-row count.PESSIMISTIC_WRITE only when conflicts are frequent enough to justify blocking.A version column also protects against stale detached updates, because the old version no longer matches after another transaction commits. It does not automatically protect native SQL or bulk JPQL unless those statements implement an equivalent predicate and the persistence context is handled correctly.
Interview takeaway: READ_COMMITTED protects visibility, not read-modify-write integrity; JPA needs @Version, an atomic statement, or an explicit pessimistic lock.
The same JDBC isolation name does not guarantee identical behavior because PostgreSQL and MySQL implement snapshots and locking differently. The biggest practical trap is that PostgreSQL defaults to READ_COMMITTED, while InnoDB defaults to REPEATABLE_READ, and even matching labels have different effects on locking reads and serialization.
Important differences for InnoDB and PostgreSQL are:
SELECT ... FOR UPDATE is a current, locking read rather than an ordinary snapshot read in both systems, subject to each engine's lock and index rules.-- PostgreSQL: statement-level visibility at READ COMMITTED
SET TRANSACTION ISOLATION LEVEL READ COMMITTED;
-- InnoDB: inspect the actual session setting
SELECT @@SESSION.transaction_isolation;
-- PostgreSQL: inspect the actual transaction setting
SHOW transaction_isolation;
When diagnosing a portability issue:
FOR UPDATE, range predicates, and inserts into the range.The trade-off is portability versus engine-specific concurrency. Declare isolation deliberately, test the exact SQL and indexes, and do not infer semantics from the isolation label alone.
Interview takeaway: I would compare snapshot rules and locking reads on the actual engine, not assume that a matching JDBC isolation constant means matching behavior.
EntityManager.flush() synchronizes pending changes in the persistence context with the database; it does not commit them. Once those INSERT, UPDATE, or DELETE statements execute, a subsequent query in the same transaction can see those uncommitted changes, and Hibernate may also flush automatically before a query whose tables overlap the pending changes.
This can surprise developers because:
flush(), transaction commit, or a provider-selected auto-flush point.FlushMode.AUTO, JPQL or Criteria queries can trigger a flush when Hibernate detects relevant query spaces. The exact auto-flush behavior is provider and version dependent; explicit flush is the portable guarantee.entity.setStatus(Status.PAID);
entityManager.flush(); // SQL is issued now
List<Order> paid = entityManager.createQuery(
"select o from Order o where o.status = :status", Order.class)
.setParameter("status", Status.PAID)
.getResultList(); // can include the flushed row
For diagnosis and control:
FlushModeType.COMMIT cautiously for read-heavy work, but verify query results because pending changes may not be flushed before the query. Separate read and write units of work when that is clearer.The persistence context may also return an already-managed object without querying, so application-visible state can come from both the first-level cache and the database. That is why SQL logs alone do not always explain every result.
Interview takeaway: flush() is an SQL synchronization boundary, not a commit, and it can make same-transaction queries observe pending changes earlier than expected.
@Lock(LockModeType.PESSIMISTIC_WRITE) asks Spring Data JPA to apply a database write lock when it loads the matching entity, typically resulting in SQL such as SELECT ... FOR UPDATE where the dialect supports it. A competing transaction must usually wait, fail on a lock timeout, or encounter a deadlock until the first transaction commits or rolls back.
public interface OrderRepository extends JpaRepository<Order, Long> {
@Lock(LockModeType.PESSIMISTIC_WRITE)
@Query("select o from Order o where o.id = :id")
Optional<Order> findForUpdate(@Param("id") Long id);
}
@Transactional
public void reserve(Long id) {
Order order = repository.findForUpdate(id)
.orElseThrow();
order.reserve();
}
The important behavior and limits are:
Use it deliberately:
@Version for low-contention workloads, because optimistic locking avoids blocking and detects conflicts at flush. Use pessimistic locking when waiting is preferable to conflicting work or when the decision depends on a row that must not change during the transaction.Pessimistic locking changes contention from silent last-write-wins behavior into waiting or failure, but it does not remove the need for transaction design, timeout handling, and deadlock prevention.
Interview takeaway: PESSIMISTIC_WRITE reserves the database row for the transaction, so concurrent code waits or fails instead of freely performing a stale update.
Preparing for a full interview loop? Full interview kit (600 Qs: Java, Spring Boot, database, DevOps, cloud, system design, microservices)
By default, Spring rolls back for RuntimeException and Error, but not for checked exceptions. A checked exception therefore normally reaches the transaction interceptor as a successful completion, and the transaction manager commits unless the method declares a matching rollbackFor rule or explicitly marks the transaction rollback-only.
@Transactional(rollbackFor = IOException.class)
public void importFile(Path path) throws IOException {
repository.save(batch);
readAndValidate(path); // IOException now causes rollback
}
The important details are:
rollbackFor matches an exception type, including subclasses. rollbackForClassName uses a name or pattern and is easier to match accidentally.TransactionAspectSupport.currentTransactionStatus().setRollbackOnly(), or rethrow an exception covered by the transaction rule.To diagnose and fix it:
rollbackFor rule and tests for both success and failure paths.Interview takeaway: A checked exception is not a rollback signal in Spring by default, so declare the required rollbackFor policy or mark the transaction rollback-only explicitly.
Catching DataIntegrityViolationException does not necessarily make the transaction usable again. The exception may already have caused Spring or the JDBC/JPA provider to mark the current transaction rollback-only, so a later commit rolls everything back and commonly reports UnexpectedRollbackException.
@Transactional
public void placeOrder(Order order) {
try {
orderRepository.saveAndFlush(order); // constraint checked here
} catch (DataIntegrityViolationException ex) {
auditRepository.save(new Audit("duplicate order"));
// The surrounding transaction may already be rollback-only.
}
}
Why this surprises teams:
save.DataIntegrityViolationException, but translation does not clear the database transaction's failed state.UnexpectedRollbackException only when it tries to commit, hiding the original location unless it was logged.Use one of these designs after confirming the failure:
REQUIRES_NEW and invoke that method through a proxy. The inner transaction can roll back without poisoning the outer one.Interview takeaway: Once a constraint failure marks the transaction rollback-only, catching the exception changes control flow but not the transaction outcome.
When both rollbackFor and noRollbackFor match, Spring applies the strongest matching rule: the most specific exception type or pattern wins. Thus a specific noRollbackFor can override a broader rollback rule, while a specific rollbackFor can override a broad no-rollback rule.
@Transactional(
rollbackFor = Exception.class,
noRollbackFor = BusinessWarning.class
)
public void process() throws Exception {
// BusinessWarning: commit candidate; another checked Exception: rollback
}
The mechanism and its limits are:
rollbackFor = Exception.class normally rolls back checked exceptions, but the more specific BusinessWarning exclusion wins in the example.rollbackForClassName can match similarly named classes and nested classes; class-based rules are safer when the type is available.To verify a production rule:
UnexpectedRollbackException from an outer transaction.noRollbackFor to suppress failures that leave JPA state or database constraints unreliable.Interview takeaway: The most specific matching rollback rule wins, so use narrow, non-conflicting rules and test the exception hierarchy explicitly.
A database transaction and Kafka publication are separate resource commits, so one can succeed while the other fails. The usual reliable solution is a transactional outbox: write the business change and an outbox row in one database transaction, then publish the outbox row to Kafka with retries and idempotent handling.
@Transactional
public void createOrder(OrderCommand command) {
Order order = orderRepository.save(Order.create(command));
outboxRepository.save(OutboxEvent.orderCreated(order.getId()));
}
// Separate relay: claim unsent rows, publish, then mark sent.
// Consumers deduplicate by event id.
Why this prevents the observed inconsistency:
A practical rollout is:
Interview takeaway: Do not try to make ordinary database and Kafka sends appear atomic; persist the intent with the database and publish it reliably from an outbox.
TransactionTemplate exposes the decision through its callback status: call status.setRollbackOnly() when the code has handled a condition but the whole transaction must still be undone. The callback can return normally, yet the transaction manager sees the rollback-only marker at completion and rolls the transaction back.
TransactionTemplate template = new TransactionTemplate(transactionManager);
Boolean saved = template.execute(status -> {
repository.save(entity);
if (!policy.allows(entity)) {
status.setRollbackOnly();
return false;
}
return true;
});
// saved may be false; the transaction was rolled back, not committed.
This is useful because:
setRollbackOnly() marks the current transaction; it does not immediately undo SQL or guarantee that no later code runs in the callback.UnexpectedRollbackException, depending on the transaction manager and propagation context.setRollbackOnly() when normal return is intentional but commit is not.To use it safely:
Interview takeaway: With TransactionTemplate, setRollbackOnly() makes a handled-but-non-committable outcome explicit while preserving the surrounding transaction semantics.
You prove @Version is missing by showing that Hibernate’s UPDATE statement has no version predicate and that two concurrent transactions both report one updated row. With optimistic locking configured correctly, the SQL includes where id = ? and version = ?; the second update affects zero rows and Hibernate raises an optimistic-locking exception.
@Entity
class Account {
@Id
private Long id;
@Version
private long version;
private String status;
}
-- Expected shape with optimistic locking
update account
set status = ?, version = version + 1
where id = ? and version = ?
Diagnose it with evidence from both the mapping and the database:
@Version field is mapped and included in the persistence unit.where clause and increments the version.OptimisticLockException or Spring’s translated ObjectOptimisticLockingFailureException.Also check for misleading evidence:
@Version changes the update contract and can expose existing retry or conflict-handling bugs. Deploy the schema and application mapping together, then test stale writes before enabling the path broadly.Interview takeaway: I would prove it from generated SQL: without version = ? in the update predicate and a zero-row conflict for the loser, @Version is not protecting that write.
@Version protects entity state transitions, not arbitrary bulk DML. A JPQL update is translated directly into SQL and does not load each entity, compare its in-memory version, increment @Version automatically, or invoke entity lifecycle callbacks.
@Modifying
@Query("update Order o set o.status = :status where o.createdAt < :cutoff")
int closeOldOrders(Instant cutoff, Status status);
That statement can change rows while managed Order objects in the current persistence context still contain the old status and version. A later flush may overwrite the bulk change, or the application may return stale data. Hibernate also cannot perform one optimistic check per entity because the operation is intentionally set-based.
Important consequences include:
@Version. Hibernate has a versioned bulk-HQL extension, but that is provider-specific and still needs careful cache and persistence-context handling.Choose the behavior explicitly:
where status = :expectedStatus; inspect the affected row count and treat an unexpected count as a conflict.EntityManager.clear() or isolate the operation in a transaction whose entities are not reused. Evict affected cache regions when required.Interview takeaway: Bulk JPQL is direct set-based SQL, so use entity updates for normal version checks or implement the predicate, version increment, and cache clearing explicitly.
Handle OptimisticLockException as a failed transaction, not as a validation warning inside the same transaction. Once the flush or commit detects a stale version, the transaction is normally marked rollback-only; recover by rolling it back, starting a fresh transaction, rereading current state, and then deciding whether to retry or report a conflict.
@Retryable(retryFor = ObjectOptimisticLockingFailureException.class,
maxAttempts = 3)
@Transactional
public void rename(long id, String name) {
User user = repository.findById(id).orElseThrow();
user.rename(name);
}
@Recover
public void conflict(ObjectOptimisticLockingFailureException ex,
long id, String name) {
throw new ConflictException("The user changed; reload and retry", ex);
}
The exception may be raised during flush() or transaction commit, and Spring may translate the JPA exception into ObjectOptimisticLockingFailureException. Catching it inside the transactional method and continuing can produce an UnexpectedRollbackException at the boundary, because the transaction cannot be committed successfully.
A safe response pattern is:
Retries are not universally correct:
Interview takeaway: After an optimistic conflict, discard the failed persistence context and either retry the reread-and-update operation in a new transaction or return a clear conflict.
A stale second-level cache entry can supply an entity with an old version to a transaction, and that transaction then issues an update using the stale version. The database’s version predicate rejects it with a zero-row update, so the cache causes a visible optimistic conflict; it does not defeat the database guard or silently permit a lost update.
-- Database contains version 6
-- Node B read version 5 from its stale L2 cache
update customer
set name = ?, version = version + 1
where id = ? and version = 5;
-- Result: 0 rows; Hibernate raises an optimistic-lock exception
The usual sequence is that node A updates version 5 to version 6, but invalidation or replication to node B is delayed, lost, or misconfigured. Node B’s persistence context obtains version 5 from its cache and flushes it. A correct @Version check prevents corruption, but users may see avoidable conflicts or repeated retries.
Diagnose the path rather than assuming the database is wrong:
Typical fixes are:
Interview takeaway: The stale cache explains why the old version was used, but the database version predicate still does its job by converting that stale read into a safe conflict.
@TransactionalEventListener(phase = AFTER_COMMIT) runs only after the transaction manager reports a successful commit. If flush or commit fails, including because of an optimistic-lock or constraint error, the transaction rolls back and there is no successful commit phase in which that listener can run.
@Component
class OrderEvents {
@TransactionalEventListener(phase = TransactionPhase.AFTER_COMMIT)
public void sendConfirmation(OrderPlaced event) {
// Runs only after the enclosing transaction commits successfully.
}
@TransactionalEventListener(phase = TransactionPhase.AFTER_ROLLBACK)
public void recordRollback(OrderPlaced event) {
// Runs when the enclosing transaction rolls back.
}
}
The event is associated with a transaction synchronization when it is published inside an active transaction. Spring’s default fallbackExecution is false, so if no transaction exists, the listener is skipped rather than executed immediately. Also, AFTER_COMMIT is not a durable message queue: a process crash after the database commit but before listener execution can still lose the in-process notification.
Diagnose and design around the boundary:
AFTER_ROLLBACK for rollback-specific local cleanup, or AFTER_COMPLETION when code must observe either outcome; do not use those phases to pretend a failed commit succeeded.One further trade-off matters: an AFTER_COMMIT listener runs after the original transaction is complete. If it must write to the database, give it a separate transaction, commonly through another proxied service with REQUIRES_NEW; an exception there cannot undo the already completed commit. Keep that work idempotent.
AFTER_COMMIT execution.Interview takeaway: AFTER_COMMIT means successful commit, not method completion, so a failed commit correctly suppresses it; use rollback handling or an outbox when the outcome must be reliable.
REQUIRES_NEW suspends the existing transaction and uses an independent transaction and usually an independent connection.REQUIRED method can mark the shared transaction rollback-only even when its exception is caught by the caller.REQUIRES_NEW work can exhaust a connection pool under concurrency.READ_COMMITTED prevents dirty reads but does not by itself prevent lost updates.Error, while checked exceptions normally require an explicit rule.@Version checks automatically.@TransactionalEventListener(AFTER_COMMIT) is conditional on a successful commit and cannot compensate for a transaction that rolls back.Spring resolves transaction advice through the configured transaction manager, the transaction annotation, and any qualifiers or explicit configuration. A JpaTransactionManager coordinates a JPA EntityManager, while a JDBC manager coordinates JDBC resources; they are not interchangeable in every scenario. When multiple managers exist, make the choice explicit and verify that the repository, datasource, and transaction boundary use the same resource model.
Usually not. Isolation is a concurrency policy and should be selected for a specific consistency requirement, not applied indiscriminately. Start with the database default, then raise or lower isolation only where the required behavior is clear. Also verify the database, driver, transaction manager, and connection pool actually honor the requested level, because unsupported or mapped levels can produce different effective behavior.
No. A retry is appropriate only when the operation is designed to be repeatable and its external side effects are controlled. Re-run the database work in a new transaction and persistence context, use an idempotency key where needed, and avoid sending duplicate messages or charging an external system inside an operation that may be retried. Limit retries and record the final failure.
Use an outbox when a database change and a message publication must represent one business decision but the systems do not share a reliable atomic commit protocol. Store the event in the same database transaction as the state change, then publish it asynchronously and track delivery. Consumers should be idempotent because retries, redelivery, and process crashes remain possible.
Use integration tests with the real transaction manager and a database engine that matches production behavior where locking matters. Assert committed state from a separate transaction, inspect rollback and propagation boundaries, and include concurrent tests for conflicts and deadlocks. Avoid relying only on a test-level transaction, because it can keep changes uncommitted and hide connection, visibility, or cleanup problems.
Reliable transaction design requires separating Java control flow from transaction and database state. A caught exception may still leave a shared transaction doomed, a successful method return may precede a failed commit, and an apparently safe update may have no version check at all. Treat propagation, isolation, flushing, rollback rules, messaging, and locking as one system. Then verify the assumptions with integration and concurrency tests that observe behavior from independent transactions, not just from the test thread’s persistence context.
Which question would you find the hardest? Tell me in the comments.
Java Spring Boot & Microservices Interview Q&A (200 Qs)
https://topmate.io/logicbrace/2278363
Full interview kit (600 Qs: Java, Spring Boot, database, DevOps, cloud, system design, microservices)
https://topmate.io/logicbrace/2294498
Complete Java Full Stack Developer Kit (900 Qs: Core Java, Spring Boot & Microservices, Cloud/DevOps/System Design, React & Angular)
https://topmate.io/logicbrace/2306382

0 Comments