Get rid of session files in an API

A quick blogpost about building APIs with Symfony2 and FOSRestBundle, just so I won't forget this and can always refer to this blogpost if I start wondering about this again...

Some time ago I inherited an API project that was built on top of Symfony2 and the FOSRestBundle after the previous developer was unable to continue his work due to personal circumstances. I finished the project and everything was up and running fine. A couple of weeks ago, I got an e-mail from the customer because their systems had lots of issues. It turned out that the session-directory contained a couple of hundred thousand session files. This seemed odd, since there is a very limited web interface to this API.

The first thing I did was pragmatic: I wrote a simple command to clean out the session directory from files older than 1 hour (since sessions typically last only a couple of minutes). This was the quick fix, but it didn't sort the cause of the problem.

This morning, I actually dove into the code to try and solve the problem. And the fix was literally a one-liner. In the firewall configuration, I just needed to add a single line:

        pattern:   ^/api
        wsse:      { nonce_dir: null, lifetime: 3600, realm: "Secured API", profile: "UsernameToken" }
        anonymous:    true
        stateless:    true

The last line was all that was needed: It configures Symfony2 to work in a stateless way for this firewall. And stateless applications don't need sessions. Such a simple fix, but it takes a short while to figure it out.