Duplicate writes observed when retrying JPA persist with IDENTITY after rollback
0 reputation · 21 Apr 2021, 12:30 UTC
When a Spring‑annotated method uses @Transactional and @Retryable to persist a JPA entity whose primary key is generated by the database (IDENTITY), a transient exception thrown after the INSERT causes the transaction to roll back. On retry the same persist call is executed again, but the entity instance still holds the identifier that was assigned during the first attempt. Because the identifier is not regenerated, the second INSERT attempts to reuse the same key, which can result in a duplicate row if the database does not reject the duplicate key.
The goal is to configure the retry mechanism so that a retried write is safe without requiring the developer to manually add idempotency checks. The uncertainty lies in whether the retry framework should automatically invoke a user‑provided idempotency validator or leave that responsibility to the application code, leaving the behavior ambiguous in the current documentation.
Should Spring Retry provide an optional idempotency‑check callback that runs before each retry attempt? Does Resilience4j’s Retry module expose a hook for verifying idempotency when used with manual transaction boundaries? What configuration or pattern guarantees that a retry after a rollback will not produce duplicate writes for IDENTITY‑generated keys?