Quick revision
The short answer
The retry errors come from SERIALIZABLE isolation, which many distributed SQL databases use by default: when transactions conflict, one is aborted with a retryable error (SQLSTATE 40001), and the application must rerun the whole transaction, which in Spring means a retry wrapped around the transactional method and short transactions. The slow inserts come from the sequential primary key, which sends every insert to the last range, so one range leader does all the work; UUIDs, a hash-sharded index or the product's recommended key pattern spread them. We also check contention metrics, remove hot rows, and re-test JPA batching and ID generation.
What to remember
In this answer, we saw that the frequent retry errors come from SERIALIZABLE isolation, where conflicting transactions are aborted with SQLSTATE 40001 and must be rerun from the start, so in Spring the retry wraps the whole transaction, with backoff and a limit, and transactions stay short. Slow inserts come from a sequential key sending every insert to the last range, fixed with UUIDs, hash-sharded indexes or the product's key pattern. We also reduce hot rows using the contention metrics, and re-test JPA id generation and batching.
Your turn
Answer it aloud as you would in the interview, or type your answer below. Then show one part at a time and compare.
The retry errors come from SERIALIZABLE isolation, which many distributed SQL databases use by default: when transactions conflict, one is aborted with a retryable error (SQLSTATE 40001), and the application must rerun the whole transaction, which in Spring means a retry wrapped around the transactional method and short transactions. The slow inserts come from the sequential primary key, which sends every insert to the last range, so one range leader does all the work; UUIDs, a hash-sharded index or the product's recommended key pattern spread them. We also check contention metrics, remove hot rows, and re-test JPA batching and ID generation.
Why this question is asked
Teams often migrate to a distributed SQL database expecting PostgreSQL that scales, and then meet two surprises in the first week: errors they never saw before, and inserts slower than on their old single server. Both have clear causes in how these databases work. Interviewers ask this scenario to see whether we can connect symptoms to internals and fix them in the application. In this answer, we will explain why serialization failures appear, write a correct retry in Spring, see why a sequential key creates a hot range and how to fix it, and finish with contention hot spots and JPA behaviour.
1Why the Retry Errors Appear
In PostgreSQL the default isolation level is READ COMMITTED. Two transactions updating the same row simply wait for each other, and most other conflicts are invisible. Many distributed SQL databases default to SERIALIZABLE instead; CockroachDB does, while YugabyteDB and TiDB have different defaults and options, so check your product and configuration. SERIALIZABLE promises that the result is the same as if transactions ran one after another. To keep that promise without global locks, the database detects conflicts, for example two transactions that read and write overlapping data, or a read that would see a value from the future of its timestamp, and aborts one of them.
The aborted transaction gets an error with SQLSTATE 40001, serialization failure, with a message saying it can be retried. That error is not a bug in the database; it is part of the contract. The transaction did nothing, and the application is expected to run it again from the start. Code that was written for PostgreSQL's defaults never expected this, so the error goes up to the user.
2Retrying the Whole Transaction in Spring
The key rule is that the retry must wrap the transaction, not run inside it. Once the database has aborted a transaction, every statement in it fails, so retrying one statement is useless. We need to start a new transaction and redo all the reads and writes, because the data we read the first time may have changed. In Spring, that means the retry sits outside the @Transactional boundary. A simple and explicit way is TransactionTemplate inside a loop.
Notice three details. Checking the SQLSTATE by walking the cause chain works whether the exception came through JDBC, JPA or Hibernate, and it avoids depending on which Spring exception class the translator chose, which has changed between versions. The jittered backoff keeps two conflicting transactions from colliding again at the same instant. And the transaction must be safe to rerun: no emails or Kafka messages sent from inside it, or they would be sent once per attempt; those go through an outbox written in the same transaction. Spring Retry's @Retryable on a method that calls the transactional method, or the retry support built into Spring Framework 7 (check your version), are alternatives, as long as the retry stays outside the transaction. Keeping transactions short, with no remote calls or user think time inside, reduces conflicts in the first place.
3Why Sequential Keys Make Inserts Slow
A distributed SQL database stores each table as a sorted key space split into ranges, and each range has one leader that handles its writes and replicates them through consensus. With a sequential primary key, such as a sequence or a timestamp, every new row has the highest key so far, so every insert goes to the last range. That one range leader, on one node, does all the insert work while the rest of the cluster is idle. When the range splits, the new last range becomes the hot spot. On single-node PostgreSQL, this pattern was ideal, because appending to the end of a B-tree is cache friendly; here it is the worst case.
| Key | Where inserts go | Effect |
|---|---|---|
| Sequence / auto-increment | Always the last range | One hot range leader; slow inserts |
| Timestamp first | Always the last range | Same hot spot |
| Random UUID | Spread over all ranges | Even load; no ordering by key |
| Hash-sharded index (product feature) | Spread over N buckets | Even load; range scans fan out |
| Tenant or entity id + local id | Spread by tenant | Even if tenants are many and similar |
The fix is to make inserts land in different ranges. A random UUID primary key spreads them across the whole key space. CockroachDB offers hash-sharded indexes, which prefix the key with a hash bucket so sequential values are spread over several ranges, and YugabyteDB uses hash sharding on the first primary key column by default in YSQL. The best choice depends on the product, so we follow its documented key recommendation. If the application needs ordering by time, we keep a created_at column with a secondary index rather than ordering by the key.
4Reducing Contention and Hot Rows
Serialization failures cluster around hot rows: a single counter row incremented by every order, a single status row such as 'last processed id', or a popular product's stock row. Every transaction touching that row conflicts with every other one. The database's console usually shows contention metrics or the statements with the most retries; CockroachDB has contention views and insights, and other products have similar tools. We look there first and redesign the hottest rows: split a counter into several rows that are summed on read, replace a status row with an append-only table, or move a high-frequency aggregate out of the transactional path.
5Re-Testing JPA and Hibernate Behaviour
Finally, the persistence layer behaves differently. With GenerationType.SEQUENCE, Hibernate fetches ids in blocks using the sequence's increment, and sequences in distributed databases can be slower or work differently, so a larger allocation size or UUIDs may be needed. With GenerationType.IDENTITY, Hibernate cannot batch inserts, since it needs each id back immediately, so batch inserts silently become one statement per row. Switching to UUIDs, with @GeneratedValue(strategy = GenerationType.UUID) in Jakarta Persistence 3.1 and later, solves both the hot range and the batching question. We also confirm that hibernate.jdbc.batch_size and the driver's batch rewriting (reWriteBatchedInserts for the PostgreSQL driver) actually take effect, by measuring statements per second on a realistic load test.
6Follow-up questions
Why not just lower the isolation level to READ COMMITTED?
Some products support it, and it reduces retries, but it also gives up guarantees the team may rely on without realising, and it does not remove the need to handle retries entirely, since distributed databases can still abort transactions for other reasons. It is a valid choice when understood, not a shortcut.
Is it safe to retry any failed transaction?
Only those that failed with a retryable error before committing, such as 40001, and only if the transaction has no side effects outside the database. An error on COMMIT whose result is unknown, for example a lost connection, needs idempotency, such as a unique request id, because the commit may have succeeded.
Where should the retry go in a layered Spring application?
Around the outermost transactional unit of work, typically in the service method that the controller calls, never inside a repository call and never inside an already running transaction.
7Conclusion
In this answer, we saw that the frequent retry errors come from SERIALIZABLE isolation, where conflicting transactions are aborted with SQLSTATE 40001 and must be rerun from the start, so in Spring the retry wraps the whole transaction, with backoff and a limit, and transactions stay short. Slow inserts come from a sequential key sending every insert to the last range, fixed with UUIDs, hash-sharded indexes or the product's key pattern. We also reduce hot rows using the contention metrics, and re-test JPA id generation and batching.
Open with
There are two separate causes. The retry errors come from isolation: many distributed SQL databases, CockroachDB for example, default to SERIALIZABLE, so when transactions conflict the database aborts one with SQLSTATE 40001 and expects the application to rerun it.
Then, if they want more
PostgreSQL at READ COMMITTED would mostly just wait, so the old code never handled this.
In Spring I would wrap the whole transaction in a retry, for example a loop around TransactionTemplate, or Spring Retry on a method that calls the transactional one, checking for SQLSTATE 40001 in the cause chain, with jittered backoff and a cap of maybe five attempts.
The retry must be outside the transaction, since an aborted transaction cannot continue, and the transaction must have no external side effects, so messages go through an outbox. Keeping transactions short and looking at the contention metrics to find hot rows like counters or a single status row reduces the conflicts.
The slow inserts come from the sequential primary key: data is stored in key-ordered ranges, so every new row goes to the last range and one leader does all the inserting. I would switch to UUIDs, or use the product's hash-sharded index, and keep created_at as an indexed column for ordering.
Finally I would re-test Hibernate: IDENTITY disables insert batching and sequences behave differently, so UUID generation plus checking that JDBC batching really happens is usually the right move.
About this answer
- Last updated
- 12 November 2026
- Versions it names
- Spring Framework 7
- Checked
- Its structure and format are checked automatically. Use it as a carefully prepared study note: where a detail matters, confirm it against the documentation below. What the checks cover
- Where the question comes from
- Written by Scrivio for practice. It is not taken from an interview.
- Official documentation
- PostgreSQL documentation, MySQL reference manual
Report an issue with this answer
Copy the line below and send it to the author with what you found. It carries the address of this page.
Issue with "A team migrated from PostgreSQL to a distributed SQL database and sees frequent...": https://scrivio-interview-library.netlify.app/databases/partitioning-and-sharding/54b10906be/