title: When is HttpSessionDestroyedEvent sent and why
body: <p>We have a web app that uses spring mvc and spring security, among other things. When a session times out, we want to clean out data X.</p>
  
  <p>We register a listener that looks like this:</p>
  
  <pre><code>public class SessionDestroyedEventListener implements ApplicationListener&lt;HttpSessionDestroyedEvent&gt; {
  
      @Override
      public void onApplicationEvent(HttpSessionDestroyedEvent event) {
          for (SecurityContext securityContext : event.getSecurityContexts()) {
              AuthenticationDetails authenticationDetails = getAuthenticationDetails(securityContext.getAuthentication());
  
              // clean out data X
          }
      }
  }
  </code></pre>
  
  <p>defined as a bean</p>
  
  <pre><code>@Bean
  public SessionDestroydEventListener sessionDestroydEventListener() {
      return new SessionDestroydEventListener();
  }
  </code></pre>
  
  <p>As I said, the main use of this listener is to remove data X when a session has been inactive for too long. However, this listener is occasionally called before timeout for reasons we can't figure out, causing data X to be removed and the user session to break. These events happen unexpectedly, causing a bad user experience (the user gets logged out in the middle of actively working with our web site).</p>
  
  <p>I am trying to find out why SessionDestroyedEventListener.onApplicationEvent is called when I don't want it to. I am struggling with finding helpful information about this, or others having similar issues.</p>
  
  <p>One problem we're having is that our logs are silent when this happens - no stacktraces, it usually seems like everything is working perfectly when suddently SessionDestroyedEventListener is called out of the blue.</p>
  
  <p>The whole setup is complicated, and I feel it may be difficult to actually resolve our core issue in this stackoverflow report, I am mainly interested in tips on how to troubleshoot - is there somewhere I can find information about what caused the event (was it timeout, a bad jsessionid from the browser, etc) or some way to set it up so that we get more information about what is happening.</p>
  
  <p>Though I can mention that we have an apache frontend that load balances to two or more wildfly servers, each running our web app. Using sticky sessions, a browser session is locked to a wildfly server using jsessionid.</p>
  
  <p>Edit: to clarify, the main issue isn't really that we want to implement a check on why the session is destroyed, the issue is that the session is destroyed at all before timeout. To know the reason would be great, since it would give us an idea how the session is destroyed, so we could find the source of the problem.</p>