Skip to content

Instantly share code, notes, and snippets.

@K-Phoen
Created December 18, 2012 11:22
Show Gist options
  • Star 36 You must be signed in to star a gist
  • Fork 11 You must be signed in to fork a gist
  • Save K-Phoen/4327229 to your computer and use it in GitHub Desktop.
Save K-Phoen/4327229 to your computer and use it in GitHub Desktop.
Storing Symfony2 sessions in memcached
imports:
# ....
- { resource: services/session.yml }
framework:
# ....
session:
handler_id: session.handler.memcached
aptitude install memcached php5-memcached
parameters:
# ...
session_memcached_host: localhost
session_memcached_port: 11211
session_memcached_prefix: sess
session_memcached_expire: 3600
services:
session.memcached:
class: Memcached
arguments:
persistent_id: %session_memcached_prefix%
calls:
- [ addServer, [ %session_memcached_host%, %session_memcached_port% ]]
session.handler.memcached:
class: Symfony\Component\HttpFoundation\Session\Storage\Handler\MemcachedSessionHandler
arguments: [@session.memcached, { prefix: %session_memcached_prefix%, expiretime: %session_memcached_expire% }]
@asennoussi
Copy link

any changes in php.ini file?

@weyandch
Copy link

weyandch commented Sep 2, 2014

runs smooth, just tried it myself

@cmenning
Copy link

HUGE caveat here... Spent several hours figuring out what was going on.

If you are using Apache prefork, giving the persistent_id when instantiating the service creates a connection to memcached that lasts for as long as the Apache worker child stays alive (this can be a good thing... less overhead). However, the addServer call does not check for duplicates; this causes the memcached server to be listed in the server list and a connection to be opened once for every single request served by the worker.

The default Ubuntu settings are for a maximum of 400 workers, each able to handle 10000 requests before being killed. That means there might be as many as 4,000,000 open connections to the memcached server.

When we hit the memcached open connection limit of 1024, we were no longer able to store or retrieve any sessions from that point forward because the old connections just wouldn't die. There are two possible fixes for this:

  1. Create a wrapper class for the built-in Memcached class that checks for duplicates before adding the server.
  2. Don't use persistent connections - remove lines 4 & 5 in the session_services.yml snippet above.

Short term (because it's easier) I've gone with #2 - testing shows it's stable for now. There's obviously a performance overhead that would be negated by implementing #1.

@liverbool
Copy link

@cmenning Could you please show up your #1 gist?

@fpapadopou
Copy link

@cmenning you just made my day! Thanks a lot man!!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment