Skip to content
Tutorials Center
My learning

Topics

Lesson 24 of 37 ยท Clustering and Sessions

Sessions and Session Persistence in Tomcat

Understand how Tomcat stores HttpSession data, what the session manager does, how sessions survive restarts, and which settings control timeout and cookies.

HTTP has no memory: each request is independent. A session gives a web application memory by attaching a small server-side object to each visitor, found again through a cookie named JSESSIONID. Shopping carts, login state and form wizards usually live in the session. In Tomcat, every HttpSession is created, looked up, expired and (optionally) saved by a Manager component. Understanding it explains many production surprises: users logged out after a restart, memory filling up with sessions, or carts that vanish when you add a second server.

This lesson covers how the manager works, how sessions persist across restarts, and the settings you will actually change. The XML is read-only (Tomcat cannot run on this site); the Java stand-ins reproduce the ideas.

What a session is

When your code calls request.getSession(), Tomcat creates a StandardSession object holding a random id, creation time, last-accessed time, a max-inactive interval and a map of attributes. It sends the id in a Set-Cookie: JSESSIONID=...; Path=/; HttpOnly header. On the next request the browser returns the cookie, and Tomcat finds the object in a ConcurrentHashMap in the manager. The id is long and random (from a SecureRandom-based generator), so it cannot be guessed.

The map lives in the JVM heap. That is fast, but it means three things: sessions use memory, they are lost when the JVM stops (unless saved), and a second Tomcat does not know about them.

Managers

Manager Behavior
StandardManager The default. Keeps sessions in memory; on a clean shutdown it writes them to SESSIONS.ser in the work directory and reads them back at startup.
PersistentManager Keeps sessions in memory but swaps idle ones out to a Store (a FileStore or JDBCStore), and can back up each one.
DeltaManager / BackupManager Cluster managers that copy sessions to other nodes (see session replication).

A manager is configured in a <Context>:

XML
<Context>
  <Manager className="org.apache.catalina.session.PersistentManager"
           maxIdleSwap="300" minIdleSwap="60" maxIdleBackup="30">
    <Store className="org.apache.catalina.session.FileStore"
           directory="/var/lib/tomcat/sessions"/>
  </Manager>
</Context>

maxIdleSwap is the number of seconds after which an idle session is moved out of memory to the store, and maxIdleBackup makes Tomcat save sessions even while active, so a crash loses little. With the default StandardManager, a crash (not a clean stop) loses everything.

To stop Tomcat from saving sessions at shutdown, set an empty pathname:

XML
<Manager pathname="" />

Serializable attributes

To be written to disk or sent over the network, every object you put in the session must implement java.io.Serializable, along with everything it references. A common bug is a session attribute holding a database connection, an InputStream or a non-serializable domain object. The save fails, Tomcat logs a NotSerializableException, and the session is lost on restart. Test this early rather than at the first production deployment.

The inactivity timeout defaults to 30 minutes. Set it per application in web.xml:

XML
<session-config>
  <session-timeout>20</session-timeout>   <!-- minutes -->
  <cookie-config>
    <http-only>true</http-only>
    <secure>true</secure>
  </cookie-config>
  <tracking-mode>COOKIE</tracking-mode>
</session-config>

Allow only the COOKIE tracking mode so session ids never appear in URLs (where they leak through referrers and logs). The SameSite attribute is normally set with a Rfc6265CookieProcessor in the context: <CookieProcessor sameSiteCookies="lax"/>. In code you can call session.setMaxInactiveInterval(seconds) for a single session and session.invalidate() at logout. After login call request.changeSessionId() to avoid session fixation.

Expired sessions are removed by a background thread: every processExpiresFrequency ticks of the container background process (default 6, about once a minute) the manager scans for sessions past their timeout.

Stand-in: an in-memory session manager with expiry

The first stand-in is a miniature StandardManager: ids from SecureRandom, a map, a timeout and an expiry sweep. The clock is injectable so the output is deterministic.

Java Stand-in: session manager with expiry

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Every successful find refreshes the last-access time, which is why an active user is never logged out mid-session, while an idle one is removed by the sweep.

Stand-in: serializing sessions to disk

StandardManager and FileStore write sessions with Java serialization. This stand-in saves two sessions to a byte array and reads them back, and shows what happens when an attribute is not serializable:

Java Stand-in: persisting sessions

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

The restored line prints the same user and cart, but the byte count can vary by JDK, so do not rely on it. The error is the one you will see in catalina.out when a session attribute is not serializable.

Common mistakes

  • Storing large objects (result sets, entire catalogs) in the session; memory use is sessions times object size.
  • Creating a session for every request, including bots and health checks (set <%@ page session="false" %> and avoid getSession() on static or API calls).
  • Assuming sessions survive a hard crash with StandardManager.
  • Using URL rewriting, which exposes session ids.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Where does StandardManager keep sessions while Tomcat runs?

    Sessions are objects in a map in memory, which is fast but not shared between servers.
  2. 2. What must session attributes be to survive a restart or replicate to another node?

    Tomcat uses Java serialization, so the attribute and everything it references must implement Serializable.
  3. 3. What does PersistentManager maxIdleSwap control?

    After this many idle seconds the session is written to the Store and removed from memory.
  4. 4. How do you avoid session ids in URLs?

    tracking-mode COOKIE disables URL rewriting, so ids are only sent in cookies.

Summary

  • Tomcat's Manager stores HttpSession objects keyed by a random JSESSIONID.
  • StandardManager persists on clean shutdown only; PersistentManager swaps and backs up to a Store.
  • Anything in the session must be Serializable and small.
  • Set timeout, HttpOnly/Secure/SameSite cookies, and COOKIE-only tracking.
  • Change the session id on login.

Next: Session replication and clustering