Cleaning Up Expired Sessions From App Engine Datastore

If you have enabled sessions for your GAE application, you probably already know that sessions are persisted in datastore. But, do you know that expired sessions are not deleted automatically? If you don’t take care of expired session, they’ll slowly eat your storage quota.

Fortunately,¬†Google has provided a Java servlet that deletes expires session (although 100 per invocation) but for some strange reason this is not documented. Here’s what do you need to do…

Add SessionCleanupServlet to your web.xml:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
  ...
  <servlet>
    <servlet-name>_ah_sessioncleanup</servlet-name>
    <servlet-class>com.google.apphosting.utils.servlet.SessionCleanupServlet</servlet-class>
  </servlet>

  <servlet-mapping>
    <servlet-name>_ah_sessioncleanup</servlet-name>
    <url-pattern>/_ah/sessioncleanup</url-pattern>
  </servlet-mapping>
  ...

  <security-constraint>
    <web-resource-collection>
      ...
      <url-pattern>/_ah/sessioncleanup</url-pattern>
    </web-resource-collection>
    <auth-constraint>
      <role-name>admin</role-name>
    </auth-constraint>
  </security-constraint>

Use cron.xml to schedule periodic cleanup:

1
2
3
4
5
6
7
8
<cronentries>
  ...
  <cron>
    <url>/_ah/sessioncleanup?clear</url>
    <description>Clean up sessions</description>
    <schedule>every 15 minutes</schedule>
  </cron>
</cronentries>

Considering that the servlet deletes maximum of 100 session per call, you should set an appropriate cleanup schedule for your application to make sure sessions do not pile up.

Comments