How can I prevent RuntimeError("Unable to create a new session key.")?

Just solved same problem with apt-get install memcached. May be it's your case too.

Ou, sorry, this is not your case. I'vr just read question with more attention. But I will left my answer - cause it's about this runtime error.


Looking at the python-memcached code on launchpad, you should be able to tweak dead_retry and retry_timeout. Another option may be to run a low memory, low connections instance of memcached on one or both of the app servers as a fallback when the primary memcached server is unreachable.


https://github.com/django/django/blob/master/django/contrib/sessions/backends/cache.py

def create(self):
    # Because a cache can fail silently (e.g. memcache), we don't know if
    # we are failing to create a new session because of a key collision or
    # because the cache is missing. So we try for a (large) number of times
    # and then raise an exception. That's the risk you shoulder if using
    # cache backing.
    for i in xrange(10000):
        self._session_key = self._get_new_session_key()
        try:
            self.save(must_create=True)
        except CreateError:
            continue
        self.modified = True
        return
    raise RuntimeError("Unable to create a new session key.")
  • you can monkey-patch django.contrib.sessions.backends.base.SessionBase._get_new_session_key to do a time.sleep(0.001).
  • you could also check your entropy:

here's the command:

cat /proc/sys/kernel/random/entropy_avail