Putting script objects in session scope is a bad idea because it breaks the stateless model of web applications, causes memory bloat and unpredictable performance, creates concurrency and serialization problems, and makes applications harder to scale and maintain. Session scope is designed for small, serializable data—not for live code objects that hold references to server resources.
Background: What Session Scope Is For
In web development, session scope refers to data stored per user for the duration of a visit. When a user logs in, the server creates a session and assigns a unique identifier, usually stored in a cookie. Any data placed in session scope is tied to that identifier and persists across requests until the session expires or is invalidated.
Session scope was designed for lightweight, user-specific state: a user ID, a display name, a shopping cart, a language preference, or a CSRF token. These are small, serializable values that can be written to a session store—memory, a database, or a distributed cache—and reconstructed on the next request.
Script objects are different. A script object is a live instance of a class that contains executable code and often references runtime resources: open files, network connections, thread pools, or native handles. Such objects are not plain data; they are active participants in the server process.
How Session Storage Works Under the Hood
Most application servers and frameworks implement session storage in one of two ways:
- In-memory sessions: The session object lives in the server's heap. Each active user consumes memory for the entire session lifetime.
- Persistent or distributed sessions: Session data is serialized and written to a database, file system, or distributed cache. On each request, it is deserialized back into memory.
Both models assume that session contents are small and serializable. Script objects violate both assumptions. They can be large, and many cannot be serialized at all because they hold references to non-serializable resources.
When a session is persisted, the container attempts to serialize every attribute. If a script object contains a file handle or a database connection, serialization fails with an exception. Even if serialization succeeds, deserialization creates a new object that may not be functionally equivalent—connections are not re-established automatically, and internal state may be lost.
Memory and Performance Costs
Every object stored in session scope stays in memory for the life of the session. A typical session might last 20 to 30 minutes of inactivity, but many servers keep sessions alive for hours. If each session holds a script object that consumes several megabytes—common for objects that cache data or hold buffers—memory usage grows linearly with the number of active users.
Consider a server with 1,000 concurrent sessions. If each session stores a 2 MB script object, that is roughly 2 GB of heap consumed by session data alone. This leaves less memory for request processing, increases garbage collection pressure, and can lead to out-of-memory errors under load.
Performance also suffers. Serializing and deserializing large objects on every request adds latency. In distributed environments, session data must be replicated or fetched from a central store, turning a local operation into a network round trip.
Concurrency and Thread-Safety Problems
Script objects are often not thread-safe. In a web application, multiple requests from the same user can arrive concurrently—for example, when a page loads several resources in parallel or when the user opens multiple tabs. If those requests share a session-scoped script object, they may access and modify it simultaneously.
Without explicit synchronization, this leads to race conditions, corrupted state, and intermittent bugs that are difficult to reproduce. Adding synchronization introduces lock contention, which can degrade performance and even cause deadlocks if the object calls back into the container.
A common misconception is that session scope guarantees single-threaded access. It does not. Session scope only guarantees that the same session object is available to all requests carrying the same session ID; it says nothing about concurrent access.
Common Problems and Failure Modes
Storing script objects in session scope produces a predictable set of failures:
- Serialization errors: The container throws
NotSerializableExceptionduring session persistence or server shutdown. - Memory leaks: Objects are not released when the session expires because background threads or listeners still hold references.
- Stale state: After failover or restart, the object is reconstructed without its original resources, causing null pointer exceptions or silent data loss.
- Class loader leaks: In application servers that support hot redeployment, session-scoped objects can pin the old class loader in memory, preventing garbage collection.
- Security exposure: Session data may be replicated to other nodes or written to disk, increasing the attack surface if the object contains sensitive runtime information.
These problems often appear only under production load or during deployment, making them expensive to diagnose and fix.
Better Alternatives for Script Objects
Instead of storing script objects in session scope, use request scope or application scope depending on the object's purpose:
- Request scope: Create the object at the start of each request and discard it when the request ends. This is the safest choice for objects that are cheap to construct and hold no cross-request state.
- Application scope: Use a singleton managed by the container for shared, thread-safe services such as caches or connection pools. Ensure the object is designed for concurrent access.
- Dependency injection: Let the framework provide the object where it is needed, rather than storing it manually in session.
- Stateless design: Keep session data to small, serializable values—identifiers, flags, and simple strings—and reconstruct any needed objects from those values on each request.
If an object must persist across requests, store only the minimal data needed to recreate it, not the object itself. For example, store a user ID and fetch the user object from a service or database when required.
Frequently Asked Questions
Can I store a script object in session scope if my server never serializes sessions?
It is still risky. Even without serialization, the object consumes memory for the session lifetime and may be accessed concurrently by multiple requests. It also prevents clustering and failover, because the object cannot be moved to another node.
What happens to session-scoped objects when the server restarts?
If sessions are persisted, the container attempts to deserialize them. Script objects that cannot be serialized cause errors, and those that can be serialized may lose their runtime resources, leading to broken behavior after restart.
Is session scope the same as application scope?
No. Session scope is per user and lasts for the session; application scope is shared across all users and lasts for the life of the application. Application scope is suitable for thread-safe shared services, while session scope is for small user-specific data.
Why do I get a NotSerializableException only in production?
Development servers often keep sessions in memory and never serialize them. Production servers may persist sessions for failover or clustering, triggering serialization that exposes non-serializable objects.
Can I make a script object serializable to avoid problems?
Making an object serializable is not enough. Serialization captures state, not live resources such as connections or threads. The deserialized object may be unusable, and concurrency issues remain.
What is the recommended maximum size for session data?
Keep session data as small as possible—typically a few kilobytes. Large session objects increase memory usage, slow down replication, and raise the risk of serialization failures.