Scrivio Interview library
DesignAdvanced7 min read · updated 12 November 2026

Some services use long-lived persistence contexts (extended contexts or a session kept for a whole user conversation), others use one per transaction. What standard would you set and why?

I would make one persistence context per transaction the standard, because it keeps memory bounded, avoids stale data and matches how Spring manages EntityManagers. Long-lived contexts hold entities, and often connections, for a long time and are not thread-safe, so multi-step user conversations should keep their state in the client or in a draft record and use optimistic locking when they save. Batch jobs should clear the context in chunks, and the rule should be written into the platform guidelines with examples so teams can follow it without debate.

Why this question is asked

When different services handle persistence contexts in different ways, problems appear that only one team understands: memory that grows over a user's session, changes that silently overwrite someone else's, connections held while a user thinks. A senior engineer is expected to pick a standard, justify it, and give teams a clear path for the cases that seem to need something else. Interviewers ask this to test whether we can reason from the mechanics to a policy. In this answer, we will recap the two models, explain why per-transaction contexts should be the default, look at the problems with long-lived contexts, show how to handle multi-step conversations instead, cover batch jobs, and finish with how to write the standard.

1A Quick Recap of the Two Models

A persistence context is the set of entities an EntityManager tracks, with their snapshots for dirty checking and their pending changes. The question is how long it lives.

In the transaction-scoped model, the default in Spring, a new persistence context is created when a transaction starts and closed when it commits. Each request or unit of work gets a fresh one. In the long-lived model, a context, either a JPA extended persistence context or a Hibernate session kept in a user's HTTP session, survives across several transactions, often for a whole user conversation such as a multi-page form, so that entities stay managed between steps.

2Why Per-Transaction Should Be the Default

A persistence context per transaction has three properties that make it the right default. Its memory is bounded by the work of one transaction, so it cannot grow over hours. Its data is fresh: every transaction loads what it needs at that moment, so it does not keep an hour-old copy of a row that someone else has since changed. And it fits Spring's model exactly: JpaTransactionManager binds a new EntityManager per transaction to the current thread, so there is nothing to configure and nothing is shared between threads.

It also makes behaviour easy to reason about. When the transaction ends, everything is either committed or rolled back, and every entity is detached. There is no hidden state waiting to be flushed by a later step.

Per-transaction and long-lived persistence contexts
ConcernPer transactionLong-lived (extended or session-held)
MemoryBounded by one transactionGrows for the whole conversation
Freshness of dataLoaded at each stepStale copies kept between steps
Thread safetyOne thread, one contextNot thread-safe if shared
ConnectionsHeld only during the transactionOften held or reacquired unpredictably
Spring supportDefault, no configurationSpecial scopes and care needed

3The Problems With Long-Lived Contexts

A long-lived context keeps every entity it ever loaded, with snapshots, until it is closed. For a user conversation that lasts twenty minutes, that is twenty minutes of memory per user, and with ten thousand users it becomes a capacity problem. Depending on how it is implemented, it may also keep a database connection or a transaction open while the user is reading the screen, which exhausts the pool quickly.

Long-lived contexts also serve stale data. If a user loaded an order at minute one and another user changed it at minute five, the first user's context still has the old version at minute ten, and saving it may overwrite the other user's change unless optimistic locking catches it. And an EntityManager is not thread-safe: two requests from the same user arriving together, such as a double click, would use the same context at the same time and corrupt it.

4Handling Multi-Step Conversations Without a Long-Lived Context

The usual reason for long-lived contexts is a conversation that spans several requests, such as a three-step checkout or an editing wizard. We can support it without keeping a context alive. One way is to keep the state in the client: each step sends the data collected so far, and only the last step opens a transaction and saves. Another, for longer or resumable flows, is a draft record: each step saves its part to a draft row in its own short transaction, and the final step turns the draft into the real data.

Either way, the final save uses optimistic locking. The entity has a @Version column; the client carries the version it started from, and the final transaction checks it. If someone else changed the data in the meantime, the save fails with an optimistic locking exception, and the user sees a clear message instead of silently overwriting the other change.

Java
@Entity
class Order {
@Id Long id;
@Version long version; // carried by the client through the conversation
...
}
@Transactional
public void confirm(long orderId, long expectedVersion, CheckoutForm form) {
Order o = orders.findById(orderId).orElseThrow();
if (o.getVersion() != expectedVersion) throw new ConcurrentChangeException(orderId); // someone else edited it
o.apply(form);
} // UPDATE ... WHERE id=? AND version=? -- also checked by Hibernate at flush
Step throughA three-step conversation with the standard
  1. Step 1: load data, return it with its versionshort read-only transaction
  2. Step 2: save progress to a draft or keep it in the clientshort transaction or none
  3. Step 3: confirmnew transaction, apply changes
  4. Version unchanged?
    YesCommitNoOptimistic lock error: show the user the newer data

4 steps in order. Play them, or step through them one at a time.

No persistence context survives between steps.

5Batch Jobs: Clear in Chunks

Batch jobs are the other place where a context lives too long, not across requests but across millions of rows in one transaction. The standard for them is chunking: process a fixed number of entities, flush, and clear the context, or commit a transaction per chunk, so memory stays flat and progress is durable. Read-only exports use DTO projections, which are never managed, and simple changes use bulk UPDATE statements. Spring Batch gives this structure with restart support for jobs that run regularly.

6Writing the Standard Down

A standard only works if teams can find it and apply it without debate. We write it into the platform guidelines in a short page: the rule (one persistence context per transaction, no extended contexts and no sessions stored in HTTP sessions), the reasons in two or three sentences, and the approved patterns for the exceptions, namely client state or a draft record with @Version for conversations, and chunking with flush and clear or Spring Batch for batch jobs. Each pattern links to a small, working example in the platform's sample repository.

We also add something checkable. A test or architecture rule can fail the build on PersistenceContextType.EXTENDED, and setting spring.jpa.open-in-view=false in the platform starter removes the most common accidental long-lived context. Existing services using long-lived contexts get a migration ticket with the matching pattern, prioritised by how much memory or how many conflicts they cause today.

7Follow-up questions

Isn't Open Session in View a long-lived context too?

It is a request-scoped one: it keeps the persistence context open for the whole web request, not across requests. It is far less dangerous than a conversation-long context, but it still holds the context, and often a connection once lazy loading happens, during rendering, and it hides lazy loading in the view layer. Many teams include turning it off in the same standard.

Are there any cases where an extended context is justified?

Rarely in Spring services. A single-user desktop application or a tool where one thread owns one EntityManager for a long editing session can benefit from keeping entities managed. For server-side services with many concurrent users, the costs outweigh the convenience, and the patterns above cover the same needs.

What if the conversation must survive the user closing the browser?

Then the draft record is the right pattern, because client-side state would be lost. The draft lives in the database with an owner and a timestamp, each step updates it in a short transaction, and a cleanup job deletes drafts that were abandoned after, say, seven days.

8Conclusion

In this answer, we chose one persistence context per transaction as the standard, because it keeps memory bounded, data fresh and thread use safe, and it is exactly what Spring provides by default. Long-lived contexts grow, serve stale data, can hold connections and are not thread-safe. Multi-step conversations keep state in the client or a draft record and use @Version for optimistic locking at the final save, batch jobs clear the context in chunks, and the rule goes into the platform guidelines with examples and automated checks.

What to say in the interviewAbout 90 seconds aloud

Open with

I would set one persistence context per transaction as the standard. That is what Spring does by default: JpaTransactionManager creates an EntityManager per transaction, binds it to the thread and closes it at commit.

Then, if they want more

It keeps memory bounded to one unit of work, every step loads fresh data, and nothing is shared between threads.

Long-lived contexts, whether JPA extended contexts or a Hibernate session kept in the HTTP session, hold every entity and snapshot for the whole conversation, which adds up with thousands of users, can hold connections while the user is thinking, serve stale data that can overwrite other people's changes, and are not thread-safe, so a double click can corrupt them.

For multi-step conversations, I would keep state in the client, or in a draft record saved in short transactions for long or resumable flows, and make the final save check a @Version that the client carried from the start, so concurrent edits produce a clear optimistic lock error.

For batch jobs, the standard is chunking: flush and clear every N entities or commit per chunk, DTOs for reads, bulk updates for simple changes, or Spring Batch.

I would write this into the platform guidelines with working examples, turn off Open Session in View in the starter, add a build rule against PersistenceContextType EXTENDED, and give existing services migration tickets.

About this answer

Last updated
12 November 2026
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.
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 "Some services use long-lived persistence contexts (extended contexts or a session kept...": https://scrivio-interview-library.netlify.app/databases/jpa-fundamentals/c55d88a32c/