keepcalculator

06 Numbers and Powers

Share PHP Sessions Across Multiple Memcached Servers

Card No. 06·64437 · Updated · Standard formula, shown below

This guide explains how to configure PHP to store session data in a Memcached cluster, so that multiple web servers can share the same user sessions. You’ll learn how to set up the Memcached extension, configure PHP to use it, and handle failover when a Memcached node goes down. This setup is essential for load-balanced applications where a user might hit different servers during one session.

What You’ll Need

  • A PHP application running on a web server (Apache, Nginx, etc.)
  • Access to the PHP configuration file (php.ini) and the ability to restart the web server
  • At least two Memcached servers (or one for testing, but the guide focuses on multiple)
  • The Memcached extension for PHP installed (not the older memcache extension)
  • Basic familiarity with the command line and editing configuration files

Step-by-Step

  1. Install the Memcached extension. On Debian/Ubuntu, run sudo apt install php-memcached. On CentOS/RHEL, use sudo yum install php-pecl-memcached. After installation, verify it’s enabled with php -m | grep memcached.
  2. Set the session save handler. Edit your php.ini file and set session.save_handler = memcached.
  3. Define the Memcached server pool. Set session.save_path to a comma-separated list of your Memcached servers. For example: session.save_path = "192.168.1.10:11211,192.168.1.11:11211". You can also use Unix sockets if preferred.
  4. Configure failover (optional but recommended). To enable failover, set memcached.sess_remove_failed = 1 and memcached.sess_number_of_replicas = 1 (or more). This stores a replica of each session on another server, so if one node fails, the session is still available.
  5. Set a consistent session lifetime. Ensure session.gc_maxlifetime is set to a value that matches your application’s needs (e.g., 1440 seconds for 24 minutes). This is independent of Memcached’s own expiry.
  6. Restart your web server. After changing php.ini, restart Apache (sudo systemctl restart apache2 or httpd) or Nginx with PHP-FPM (sudo systemctl restart php-fpm).
  7. Test the setup. Create a simple PHP script that starts a session and sets a test variable. Access it from two different browsers or use curl with a cookie jar to verify the session persists across requests. Then, stop one Memcached server and confirm the session still works (if you enabled replicas).

Common Mistakes

  • Using the wrong extension. The older memcache extension (without the ‘d’) uses a different configuration syntax. Make sure you have memcached (with ‘d’).
  • Forgetting to restart the web server. Changes to session.save_handler in php.ini only take effect after a restart.
  • Setting session.save_path incorrectly. The format is a comma-separated list of host:port pairs. Do not include spaces after commas.
  • Not enabling replicas. Without replicas, if a Memcached node goes down, all sessions stored on that node are lost, causing users to be logged out.
  • Ignoring Memcached memory limits. If the Memcached server runs out of memory, it will evict old keys, including sessions. Monitor memory usage and set -m accordingly.

Tips

  • Use a consistent hashing strategy. The Memcached extension uses consistent hashing by default, which minimizes session loss when a server is added or removed. Keep this enabled (it’s the default).
  • Set a reasonable session lifetime. Don’t set session.gc_maxlifetime too high, as it increases memory usage on Memcached. Balance security and user experience.
  • Monitor your Memcached cluster. Use tools like memcached-tool or a monitoring solution to track hit rates, memory usage, and evictions.
  • Use a dedicated Memcached pool for sessions. If you use Memcached for caching other data, consider a separate pool or namespace to avoid session eviction due to cache pressure.
  • Consider using a load balancer with sticky sessions as a fallback. While Memcached enables shared sessions, sticky sessions reduce the need for cross-server session access, improving performance.

Troubleshooting

Session not persisting across servers: Check that all servers are using the same session.save_path and that the Memcached servers are reachable from each web server. Test connectivity with telnet <server> 11211.

PHP errors like “Failed to write session data”: This usually indicates a connection issue. Verify the Memcached servers are running and that the port is open. Check the PHP error log for more details.

Sessions are being lost randomly: If you haven’t enabled replicas, a Memcached node failure will cause session loss. Enable memcached.sess_number_of_replicas to protect against this.

Session data is not being stored at all: Confirm that the Memcached extension is loaded (php -m) and that session.save_handler is set to memcached (not memcache). Also, check that the Memcached server is not full; if it is, it may evict sessions immediately.

Performance issues: If sessions are slow, ensure your Memcached servers have enough memory and that you’re using a fast network between web servers and Memcached. Consider using Unix sockets if all on the same host.

Frequently Asked Questions

Can I use the older memcache extension instead?

Yes, but the configuration is different. You’d set session.save_handler = memcache and session.save_path = "tcp://host:port,tcp://host:port". However, the memcached extension is more feature-rich and recommended.

What is the difference between memcache and memcached extensions?

The memcache extension is older and less actively maintained. The memcached extension uses libmemcached, supports more features like consistent hashing and replication, and is generally preferred.

How do I set a different session lifetime for Memcached?

You can set session.gc_maxlifetime in php.ini, or use ini_set('session.gc_maxlifetime', 3600) in your code. Memcached will expire keys based on the TTL you set when storing, which PHP sets to the session lifetime.

Does Memcached persist sessions across restarts?

No, Memcached is an in-memory cache. If the Memcached server restarts, all session data is lost. For persistent sessions, consider using a database-backed session handler.

Can I use a mix of Memcached servers and other storage?

Yes, you can implement a custom session handler that falls back to a database if Memcached is unavailable, but that’s beyond the scope of this guide.

How many replicas should I configure?

One replica is usually sufficient for most applications. More replicas increase redundancy but also increase memory usage and write overhead.

Related

Method: the standard formula for this calculation, rounded as each result states. See how the calculators work or report an error.

More cards in this drawer

The whole Numbers and Powers drawer →