HTTP sessions are heap-resident state. Each active session holds references to its attribute objects, and those objects remain live until the session is invalidated or expires. Two configuration parameters bound this heap usage: the session timeout (how long a session can live) and maxActiveSessions (how many can exist simultaneously).

At their defaults, neither bounds memory. The session timeout defaults to 30 minutes. maxActiveSessions defaults to -1, meaning no limit. Under sustained traffic, bot-driven session creation, or a traffic spike, sessions accumulate until the heap fills. The result is either an OutOfMemoryError or a GC death spiral where the JVM spends most of its CPU collecting and barely processing requests.

What it is and why it matters

Tomcat’s session manager (StandardManager by default) stores HTTP sessions in the JVM heap. Each session object carries creation time, last access time, and a map of attribute name to value. The attribute values are application objects: shopping carts, user profiles, cached query results, CSRF tokens. Their size ranges from a few hundred bytes to megabytes depending on what the application stores.

Two settings bound the heap impact of this map:

  • Session timeout (<session-timeout> in web.xml): how long a session can remain idle before Tomcat expires it. Default is 30 minutes. A 30-minute timeout means sessions created during a traffic burst linger for half an hour after the user leaves.
  • maxActiveSessions (Manager attribute): the maximum number of concurrent sessions Tomcat will allow. Default is -1, meaning unlimited. When a non-negative limit is set and a new session would exceed it, Tomcat throws IllegalStateException instead of creating the session.

A short timeout with no ceiling still allows bursts to spike memory. A ceiling with a long timeout fills up permanently. You need both for effective bounding.

How it works

Session creation

Sessions are created when application code calls HttpServletRequest.getSession() or getSession(true). If the request carries no valid session cookie, Tomcat creates a new StandardSession, assigns it an ID, registers it in the session manager, and returns it. The session now consumes heap.

If maxActiveSessions is set to a non-negative value and the current session count equals or exceeds that value, creation fails. Tomcat throws IllegalStateException (TooManyActiveSessionsException) from inside getSession, so the exception surfaces within the application call path rather than before the servlet is invoked. The request fails with a 500, but the JVM survives and other users continue to be served.

flowchart TD
    A[New session requested] --> B{maxActiveSessions
reached?} B -- "Yes, cap set" --> C[IllegalStateException
clean rejection] B -- "No, or -1 unlimited" --> D[Session stored in heap] D --> E[Session lives until
idle timeout expires] E --> F[Background thread
expires session, frees heap] C --> G[Request fails
JVM survives]

With maxActiveSessions=-1 (the default) and a long timeout, the path from session creation through expiration runs faster than the background thread can clear stale sessions. activeSessions grows without bound.

Session expiration is not real-time

Sessions do not expire the instant their timeout elapses. Expiration is handled by a background processing thread that runs periodically on each container (Engine, Host, or Context). The check frequency depends on two settings:

  • backgroundProcessorDelay: the interval at which the background thread runs on the container.
  • processExpiresFrequency: how many background processing cycles pass between expiration sweeps on StandardManager. Default is 6.

With defaults of 10 seconds and 6 cycles, expiration sweeps run roughly every 60 seconds. Sessions can persist beyond their configured timeout by up to that interval. Under heavy load, if the background thread is starved by request processing or GC pauses, sessions may linger significantly longer. activeSessions can be higher than a naive calculation based on timeout alone would predict.

Session persistence across restarts

StandardManager can persist active sessions to disk across restarts. The behavior differs between Tomcat major versions:

  • Tomcat 9.0.x: Persistence is described as enabled by default, writing to a file named SESSIONS.ser, with sessions serialized on shutdown and deserialized on startup.
  • Tomcat 10.1.x: Persistence is disabled by default (pathname defaults to null). No sessions are saved or restored unless you explicitly set a pathname.

If persistence is enabled, deserialized sessions count toward maxActiveSessions immediately on startup. If the pre-restart session count was near the ceiling, new sessions are rejected right after startup with no apparent traffic cause.

Where it shows up in production

Bot and crawler traffic. Bots that do not send cookies create a new session on every request if the application calls getSession(). A crawler hitting hundreds of pages generates hundreds of sessions, each consuming heap for the full timeout period. With maxActiveSessions=-1 and a 30-minute timeout, this is a direct path to heap exhaustion.

Traffic spikes with long timeouts. A 30-minute timeout means every session created during a peak lives for 30 minutes after the user becomes idle. activeSessions accumulates linearly with traffic. The count reflects the last 30 minutes of unique visitors, not the current load. A midday traffic spike can push session-driven heap usage to dangerous levels hours after the spike subsides.

Post-restart session loading. If StandardManager persistence is enabled, restarting Tomcat reloads serialized sessions from SESSIONS.ser. These count toward maxActiveSessions. If the session count was near the ceiling before the restart, new sessions may be rejected immediately after startup.

GC death spiral from session accumulation. Sessions that survive long enough are promoted to old gen. A large old gen population of session objects drives Full GCs. With G1GC, any Full GC is a red flag: it means the concurrent collector failed to keep up. The heap appears full after every GC cycle because the sessions are live data that cannot be collected. This looks like a memory leak but is actually a sizing problem: too many sessions, too long-lived.

Checking session state

Session metrics require JMX. They are not exposed via the Manager application’s status XML.

# Check active sessions, rejections, expiry, and max alive time for the root context.
# Adjust host= and context= to match the deployed application.
java -jar jmxterm.jar -l localhost:9090 -n -v silent -e \
  "get -b Catalina:type=Manager,host=localhost,context=/ activeSessions rejectedSessions expiredSessions sessionMaxAliveTime"

If rejectedSessions is above zero, the ceiling is being hit. If expiredSessions is not increasing over time, expiration has stalled. If activeSessions is growing monotonically without a plateau, sessions are accumulating faster than they expire.

Tradeoffs and when to use it

Setting the session timeout

Tune the timeout to match real user behavior. For an interactive web application where users make requests every few seconds, a 5 to 15 minute timeout is usually sufficient. A 30-minute or longer timeout is appropriate only for applications with genuine long idle periods between interactions (admin consoles, dashboards, internal tools).

Shortening the timeout is the single most effective change for reducing session-driven heap pressure. It costs nothing in infrastructure and directly reduces the steady-state session count. It is reversible: if user complaints about session expiry increase, lengthen it.

The timeout can also be set programmatically via HttpSession.setMaxInactiveInterval(). Note the unit difference: web.xml specifies minutes, while setMaxInactiveInterval() takes seconds. A mismatch here is a common source of “sessions expire too fast” or “sessions never expire” tickets.

Setting maxActiveSessions

maxActiveSessions is a circuit breaker, not a performance tuning knob. Its purpose is to prevent session-driven OOM by converting unbounded heap growth into a bounded, observable failure. When the ceiling is hit, requests that try to create new sessions get IllegalStateException instead of the JVM dying.

To size it, estimate per-session memory cost. Take a heap dump during normal operation, identify the session objects and their retained size, and divide by the session count. Multiply average per-session size by the number of sessions your heap can absorb, leaving headroom for non-session heap usage. Set maxActiveSessions to that value.

The tradeoff is user experience: legitimate users may be rejected if the ceiling is too low. Monitor rejectedSessions. When it starts climbing, either the timeout is too long, traffic has grown beyond the heap budget, or both. The fix is to shorten the timeout or increase heap, not to raise the ceiling without understanding why it was hit.

Handling the IllegalStateException error page

When maxActiveSessions is reached, IllegalStateException is thrown from inside getSession(). If you configure an error page in web.xml for this exception, use a plain HTML file, not a JSP. JSPs call getSession() by default during page processing, which triggers the same IllegalStateException in the error page, producing an unhelpful loop. If you must use JSP for the error page, add <%@ page session="false" %> at the top.

Signals to watch in production

SignalWhy it mattersWarning sign
activeSessions (JMX)Core count of live sessions consuming heapGrowing monotonically without plateau
rejectedSessions (JMX)Shows maxActiveSessions ceiling being hitAny value above zero in steady state
expiredSessions (JMX)Confirms expiration is actually happeningNot increasing over time
sessionMaxAliveTime (JMX)Longest-lived session since startupFar exceeds configured timeout
JVM heap post-GC (Old Gen)Session objects promoted to old gen are live dataRising post-GC baseline over time
Full GC count (G1GC)Session pressure drives major collectionsAny Full GC warrants investigation
HTTP 500 rateIllegalStateException surfaces as server errorSpike correlated with rejectedSessions climbing

All session metrics come from the Manager MBean: Catalina:type=Manager,host=localhost,context=/<app>. Check each deployed context separately, as session behavior varies by application.

How Netdata helps

  • activeSessions per context: Netdata collects the Manager MBean per deployed application, so you see session counts per context rather than a single aggregate. A monotonic rise in one context isolates the problem application.
  • rejectedSessions alongside activeSessions: When rejectedSessions starts climbing, Netdata shows it next to activeSessions and JVM heap in the same time window. You can confirm the ceiling was hit and see the heap pressure that caused it without cross-referencing separate tools.
  • Post-GC heap baseline per pool: Netdata tracks heap utilization per memory pool (Eden, Survivor, Old Gen, Metaspace). The post-GC valley of Old Gen reveals whether sessions are accumulating as live data. A rising Old Gen baseline correlated with a rising activeSessions count confirms session-driven heap growth.
  • GC frequency and duration: Full GC count and cumulative GC time are collected per collector. Correlating GC pauses with session count changes distinguishes session-driven pressure from other heap consumers.
  • expiredSessions rate: Netdata shows expiredSessions as a rate over time. If the rate drops to near zero while activeSessions climbs, expiration has stalled, pointing to background thread starvation or a misconfigured processExpiresFrequency.