Using memcached to store sessions

April, 2013

After experiencing problems with long IO/wait times on the sheltermanager website, I tracked the problem down to using the DBStore with my user sessions.

Despite it being such a small table, postgresql performed terribly at reading it back and inserting new sessions. Whilst I could have tried to tune it further (eg: by making a new tablespace on a RAM disk to contain it), I decided to investigate memcached since this is just the sort of thing it's best at.

All you need software-wise is the memcache daemon itself and the python client library. If you're using Debian, install the appropriate packages:

apt-get install memcached python-memcache

Here's the session sample with a minimal memcache store:

import web
import memcache

class MemCacheStore(web.session.Store):
    mc = None
    def __init__(self): = memcache.Client([''], debug=0)
    def __contains__(self, key):
        return != None
    def __getitem__(self, key):
    def __setitem__(self, key, value):, value, time = web.config.session_parameters["timeout"])
    def __delitem__(self, key):
    def cleanup(self, timeout):
        pass # Not needed as we assigned the timeout to memcache

web.config.debug = False
urls = (
    "/count", "count",
    "/reset", "reset"

app = web.application(urls, locals())
session = web.session.Session(app, MemCacheStore(), initializer={'count': 0})

class count:
    def GET(self):
        session.count += 1
        return str(session.count)

class reset:
    def GET(self):
        return ""

if __name__ == "__main__":





Free Software