Driver FixRecommendedSound, Wi-Fi or graphics acting up? Check drivers firstFind missing or outdated drivers fast.Check DriversHalloween DealsAmazon USHalloween week deals: useful picks before month-endAmazon US: current deals, useful picks and tech finds.Check DealsClean PCRecommendedOne scan can reveal what keeps slowing WindowsLook for cleanup and repair opportunities.Run Scan×
Skip to content
World desk10 min

How to Share PHP Sessions Across Multiple Memcached Servers

A practical guide to sharing PHP sessions across Memcached servers, covering php-memcached and memcache syntax, consistent hashing, locking, replicas, failover, protocol settings, and cache-loss recovery.
Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Configure every PHP worker with the same session handler, the same Memcached server pool, compatible cookie settings, and consistent hashing. For the memcached extension, enable session locking and use a configuration like session.save_path = "sess-a:11211,sess-b:11211,sess-c:11211". Requests can then reach any application server and still find the session by its key, without load-balancer stickiness.

The configuration that makes sessions shared

PHP sessions are shared when all web and PHP workers address the same logical Memcached pool. The session ID remains in the client’s cookie; each worker uses that ID to calculate the session key and retrieve the corresponding value. A request routed to a different worker therefore reads the same session instead of creating a second, unrelated session.

As an Amazon Associate I earn from qualifying purchases.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

For the actively maintained memcached PHP extension, a practical baseline is:

session.save_handler = memcached
session.save_path = "sess-a:11211,sess-b:11211,sess-c:11211"
memcached.sess_consistent_hash = On
memcached.sess_locking = On

session.save_path is a comma-separated list of hostname:port entries for Memcached sessions. Put the equivalent settings on every PHP worker, not just on the server that receives most traffic.

#1 Best Overall
Sale
TOZO A1 Wireless Earbuds Bluetooth 5.3 Light Weight in Ear Headphones | IPX5 Waterproof,2 Mics for AI Calls,Immersive Premium Sound Bass Headset with Charging Case,32 EQ via App Black
  • [Ultra-Lightweight Ear Buds Designed for Small Ears] Each earbud weighs only 3.7g and features a compact, ergonomic in-ear design made especially for small ears. Secure, low-profile, and comfortable for workouts, all-day wear or overnight sleeping.The ultra-slim profile sits flush in your ear with no hard edges poking or rubbing, so you can even sleep on your side without discomfort.
  • [Immersive Stereo Sound with TOZO OrigX Technology] TOZO OrigX tuning delivers clear vocals, balanced mids, and natural stereo sound for music, podcasts, and videos.
  • [Long Battery Life for Daily Use] Get up to 7 hours of playtime on a single charge, with up to 32 hours total using the charging case—ideal for workdays, commuting, and extended listening sessions.
  • [Bluetooth 5.3 & Stable Connection] Bluetooth 5.3 provides fast pairing, stable wireless performance, and reduced dropouts as you move around home or office.
  • [Deep Bass with Clear Vocals] High-performance drivers produce punchy bass while keeping vocals clean and detailed for everyday listening.

This arrangement removes the need for sticky sessions at the load balancer. Stickiness can still be useful for other reasons, but it should not be the mechanism that makes PHP sessions work.

What must match on every PHP worker

A shared pool cannot correct differences in the way workers name, encode, or expire sessions. Before adding a second application server, make the following values and extension versions compatible:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
  • Session handler: use the same extension family and the same session.save_handler value everywhere.
  • Server list: use the same Memcached hostnames, ports, and ordering unless you have deliberately designed different weighted pools.
  • Cookie behavior: keep the session cookie name and its path, domain, secure, HTTP-only, and SameSite choices consistent. A browser that sends different cookie names to different hosts is not sharing one session.
  • Serialization and protocol options: use compatible extension settings, including binary-protocol mode and any proxy requirements.
  • Session lifetime: set session.gc_maxlifetime deliberately and make sure the cache can retain active entries for at least that period.

Deploy configuration as one versioned change. A worker with memcache and another with memcached may both be able to talk to the cluster, but their directive names, hashing controls, and failover behavior are different.

Configure the php-memcached extension

Set the handler and pool

The memcached extension uses the configuration shown above. Each entry is a host and port, separated by commas. For example:

session.save_handler = memcached
session.save_path = "cache-1.internal:11211,cache-2.internal:11211,cache-3.internal:11211"

Do not add a tcp:// prefix to this syntax unless your installed extension documentation specifically requires it. The PHP memcached session reference defines the pool as comma-separated hostname:port entries.

Use consistent hashing

Set memcached.sess_consistent_hash = On. The PHP documentation describes this as libketama consistent hashing: when a node is added or removed, only a smaller portion of keys is remapped than with a simple modulo calculation.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Current documented versions of memcached default this session setting to On, but explicitly setting it makes the intended behavior clear and protects you from surprises when extension packages differ. Where supported, memcached.sess_consistent_hash_type can select ketama or ketama_weighted. Use the weighted form only when the nodes have intentionally different capacities and your installed version supports it.

Rank #2
Sale
Smart Watch for Men Women Compatible with iPhone Samsung Android Phone 1.69 inch Full Touch Screen IP68 Waterproof Bluetooh Fitness Tracker Heart Rate/Sleep Monitor (Black)
  • 【IP68 Waterproof Multifunctinal Smart Watch】Torjalph fitness activity tracker smart watch is IP68 waterproof technology ,you can wear it when swimming,handwashing,it's rain-proof which means that you perform multiple exercise modes outside without worrying about sweat or rain corroding your fitness smart watch,and this watch equipped with a 230 mAh large capacity battery magnetic charging ,and this sports activity tracker watch can be used 5-7 days If fully charged.
  • 【Larger 1.83'' Full Screen Watch & Multi-dial Selection】1.83 inch full HD color touch screen smart watch for men / women provides excellent 240*284 resolution image quality ,This Bluetooth smart watch offers a better touch experience and remarkable immersion and ,more than 200 watch faces for you to choose from App"Da Fit ", you can change the dial style according to your mood to wear keeping the world on your wrist
  • 【Accurate Activity Tracker Smart Watch 】sports watch activity tracker uses sweat and dust resistant breathable silicone strap, our Fitness Tracker Smart Watch for Android iOS Phones supports 12 sports modes,walking,running,bicycle,swimming,badminton,basketball,football,rope skipping. This bluetooth calls smart watch for men women is lightweight and stylish, bringing more convenient and relaxing sports experience while also providing more protection.
  • 【Your 24 Hour Personal Daily Health Monitor】Fitness watch for women men full touch screen IP67 waterproof bluetooth smartwatch for Android iOS Phones with heart rate blood pressure monitor multifunction Andriod smart watch with steps counter sleep monitor sports fitness watch, monitoring blood oxygen saturation allows you to understand your physical condition in real time to track fitness progress ,to know your health status in time.
  • 【More Functions Bluetooth Call Smart Watch】This fitness activity smart watch full screen for iPhone and Android phones includes a bunch of new features including:The bluetooth smart watch can hang up the phone, receive and display WhatsAPP /Text /Facebook /Twitter /Messenger reminder.Support sedentary reminder, alarm clock, stopwatch, timer,weather information,music control, remote camera control compatible with Android 5.0 and above or iOS 9.0 and above smartphones.

Consistent hashing limits remapping; it does not copy data. If a session existed only on a node that was permanently removed, or if Memcached evicted it, hashing cannot reconstruct that session.

Leave session locking enabled

Set memcached.sess_locking = On, which is also the documented default in current references. Locking matters when two requests use the same session ID at the same time, such as parallel AJAX calls. One request obtains the lock, reads and updates the session, writes it back, and releases the lock before another request proceeds. Without coordination, the later write can overwrite changes made by the earlier request.

The extension exposes these lock controls:

  • memcached.sess_lock_wait_min
  • memcached.sess_lock_wait_max
  • memcached.sess_lock_retries
  • memcached.sess_lock_expire

Do not tune them by guesswork. Measure the longest normal session-writing request and the amount of parallel traffic sharing one session, then adjust waits, retry count, and lock expiry. A lock expiry that is shorter than a legitimate request can permit a second writer to enter while the first is still running; an excessively long expiry can make abandoned locks block users.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Using the older memcache extension

The older memcache extension has a different handler name and save-path grammar:

session.save_handler = memcache
session.save_path = "tcp://cache-1.internal:11211, tcp://cache-2.internal:11211, tcp://cache-3.internal:11211"

The PHP memcache reference documents comma-separated server URLs such as tcp://host1:11211, tcp://host2:11211. Do not copy memcached.* directives into a memcache configuration; they belong to a different extension.

Area memcached extension memcache extension
Handler value session.save_handler = memcached session.save_handler = memcache
Pool syntax Comma-separated host:port entries Comma-separated URLs such as tcp://host:11211
Consistent hashing memcached.sess_consistent_hash; type can be ketama or ketama_weighted where available The extension exposes a consistent hash strategy
Locking controls Session locking and wait, retry, and expiry directives are documented Directive set and defaults differ; use the installed extension’s reference
Failover controls Session replicas and failed-server removal are available memcache.allow_failover, memcache.max_failover_attempts, and memcache.session_redundancy are exposed

Choose one extension deliberately, confirm which one is loaded by the PHP runtime serving web requests, and use only its directives. A command-line PHP binary and a web-server PHP process can load different configuration files, so verify the effective web configuration rather than assuming the CLI environment is representative.

Rank #3
New Bee Guitar Cable 10ft Electric Instrument Bass AMP Cord
  • [Low Noise High Fidelity] New bee guitar cord with 22AWG oxygen-free-copper center conductors provides enhanced signal transfer, the PVC insulation material and the high-density stranded copper double shield provide noise rejection for quiet operation
  • [Ideal for Choice] New bee 1/4 straight and right angle metal connectors, ensures a secure connection in any instrument, pedal, or amp jack. L shape great fro on stage guitar stands
  • [Wide Compatible] Suitable for mixer, power amplifier, microphone, effector, decoder, equalizer, electoronic organ, electric guitar, electric bass and other electronic equipments. Widely used in the installation of smart home, karaoke speaker, professional stage audio, etc
  • [Easy Disassemble] Making incidental repairs quick and easy! Very nice, flexible cable
  • [Dont Hesite to Order] 24 hours customer services and professional technology team are standing by

What happens when nodes are added or removed

Planned changes

With consistent hashing enabled, adding a node does not move every existing key. Only keys in the affected hash ranges are assigned to the new topology. Removing a node similarly remaps the ranges that belonged to it. This reduces, but does not eliminate, session misses during a topology change.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Before a planned removal, drain traffic if possible and give users enough time to complete important workflows. A drained node can still hold sessions that have not been copied elsewhere. Removing it without replicas or an application-level recovery path will log out users whose sessions were stored there.

Unplanned loss

Consistent hashing is a placement algorithm, not persistence. It cannot recover an entry after node loss, memory pressure, expiration, or eviction. Treat a cache-node outage as a possible session loss event and decide in advance whether the application should ask users to sign in again, rebuild a cart from durable data, or take another recovery action.

Replicas and failover: useful, but not durable storage

The memcached extension can write session data to additional nodes with memcached.sess_number_of_replicas. The PHP manual calls this “poor man’s HA.” Replication can reduce the chance that one node failure loses a session, but it does not provide strongly consistent, durable storage.

A replica may be stale, and a failed server that later returns may contain old data or no data at all. If a node is removed from service automatically, configure memcached.sess_remove_failed_servers and its failure limit only when you also have a plan for recovery and reintroduction. Otherwise, a transient network fault can create a different problem when the old node comes back and is trusted again.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

For the memcache extension, the corresponding controls include:

Rank #4
BSIMB 15.6" Digital Family Calendar & Chore Chart, No Subscription Fees
  • Digital Family Calendar: BSIMB digital calendar wall touch screen puts an end to your chaotic life. Designed for busy families, the digital calendar keeps you organised and in step with your family. Assign different colours and tasks to each family member to make family scheduling easier and more intuitive.
  • Easy Setup and Auto-Sync: Plug in, connect to WLAN and auto-syn your electric calendar in minutes. Digital wall calendar compatible with Google calendar, iCloud calendar, Outlook calendar, Cozi calendar and Yahoo calendar. Add events directly on the device or through the ecalendar app. Electronic calendar stays current whether you're at work or traveling—no manual updates needed.
  • All-In-One Home Assistant: Smart calendar builds habits and encourage independence with personalised chores. Display daily meal plan to reduce the daily ‘What's for dinner?’ stress. To-do lists keep track of everything you want. Turning chores into valuable achievements with stars and rewards, making life easier and more enjoyable.
  • Manage Anytime Anywhere: BSIMB electronic calendar for family stay connected with the powerful ecalendar app. Access and manage your digital wall calendar anytime, anywhere with free features like stars & rewards, photo screensaver, chore charts, meals plans, to-do lists etc. Electronic planner paid features like Magic Import tailor advanced tools for users with special needs.
  • Stay in Touch with Loved Ones: Share photos or videos from your phone to electronic wall calendar with app, instantly update your life moment, and keep in touch with your family, especially those who are far away; you can also surprise your smart calendar digital wall by sending him a wish card; it's also great for keeping tech-illiterate elders in touch with the youngsters.
  • memcache.allow_failover to permit trying another server after a failure.
  • memcache.max_failover_attempts to limit how many alternatives are attempted.
  • memcache.session_redundancy to control redundant session storage.
  • The consistent hash strategy to reduce remapping when the server list changes.

Failover attempts add latency to a request when a server is unavailable. Set limits that fit your request budget, and monitor both error rates and response time instead of judging failover only by whether a request eventually succeeds.

Binary protocol and proxy compatibility

Protocol mode must match both the extension and any Memcached proxy in front of the servers. The PHP memcached reference states that libmemcached replicas work only when binary mode is enabled. It also documents that certain proxies, including twemproxy, require binary protocol to be disabled.

Set memcached.sess_binary_protocol according to the actual path:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
  • Direct connections with libmemcached replicas: binary mode must be enabled for the replica feature to work.
  • A proxy that accepts only the text protocol: binary mode must be disabled, even if direct-node documentation recommends enabling it.
  • Mixed or changing deployments: verify the requirement for the exact proxy and extension versions before rollout; do not infer it from another environment.

Inspect the effective value with phpinfo() or your runtime’s configuration inspection. A setting in an unused php.ini file does not change the web process.

Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Expiration, eviction, and capacity planning

session.gc_maxlifetime expresses how long PHP considers an inactive session eligible for collection. Memcached also has its own memory limit and eviction behavior. The cache must have enough free capacity and an eviction policy that can retain active session entries for the lifetime your application promises.

Increasing session.gc_maxlifetime without increasing cache capacity can make the configuration look correct while users are still logged out early because Memcached evicts entries under pressure. Monitor memory usage, evictions, item age, and session-miss rates. A low miss rate during a quiet period does not prove that the pool will retain sessions during a traffic spike.

Memcached is an in-memory cache. The PHP handler settings described here do not turn it into a durable database. If losing a session would cause unacceptable financial, legal, or operational harm, store the authoritative state in a durable shared system and use the session as a retrievable convenience, or choose a durable session-store design instead.

What’s actually slowing this PC down?

Pick the symptom - the matching free tool is one click away.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Roll out the configuration safely

  1. Inventory the runtime. Record the PHP version, loaded session extension, extension version, and the configuration file used by the web process.
  2. Prepare the pool. Confirm DNS or addresses, ports, firewall rules, and authentication or network isolation required by your Memcached deployment.
  3. Apply identical baseline settings. Set the same handler, server list, cookie behavior, session lifetime, hashing mode, lock setting, and protocol mode on every worker.
  4. Test one worker first. Create a session, make a request through that worker, then retrieve the same session through another worker or a second application instance.
  5. Test concurrency. Send parallel requests with one session ID and verify that updates are not silently lost. Include a request that takes longer than usual so lock timing is exercised.
  6. Test node failure. Remove or isolate one cache node in a staging environment. Record whether sessions are preserved, which requests become slower, and how the application handles a miss.
  7. Test recovery. Bring the node back and verify whether old values, empty values, or stale replicas are observed. Confirm that your removal and re-addition procedure does not reintroduce bad data.
  8. Roll out gradually. Shift a small percentage of traffic, watch session-miss, login, error, latency, lock-wait, and Memcached-eviction metrics, then expand the rollout.

Troubleshooting common failures

Users receive a new session on every request

  • Check that the browser sends the same cookie name, domain, path, secure flag, and SameSite behavior to each application host.
  • Confirm that all workers use the same session.save_handler and that the extension is actually loaded by the web runtime.
  • Verify that every worker can resolve and connect to every listed Memcached endpoint.
  • Look for immediate eviction or a lifetime shorter than expected.

Sessions disappear after a node change

Confirm that consistent hashing was enabled before the change and that the missing keys were not located solely on the removed node. Hashing reduces remapping but cannot preserve data that has no surviving copy. If replicas were enabled, check whether binary protocol mode matched the requirement and whether the replica was stale.

Parallel requests overwrite each other

Check memcached.sess_locking and the effective lock wait, retry, and expiry values. If locking is disabled, re-enable it for ordinary PHP sessions. If requests routinely exceed the lock expiry, measure their duration and adjust the expiry rather than simply increasing retries.

Requests become slow during an outage

Inspect failover attempts and connection timeouts. A large failover count can turn one unavailable node into a long request delay. Reduce attempts only after confirming that the remaining pool can meet availability requirements, and make sure the application has a defined behavior when no session copy can be read.

Replicas do not work through a proxy

Check the binary protocol setting first. Libmemcached replicas require binary mode, while some proxies require it to be disabled. The proxy’s supported protocol and the extension’s effective memcached.sess_binary_protocol value must agree.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Operational checklist

  • Every worker has the same handler and complete server pool.
  • Session cookie settings are consistent across all application hosts.
  • Consistent hashing is enabled and its supported type is known.
  • Session locking remains on, with lock tuning based on measured request duration.
  • Replica and failed-server-removal behavior has a documented recovery procedure.
  • Binary protocol mode is compatible with the extension, replicas, and any proxy.
  • session.gc_maxlifetime fits available memory and observed eviction behavior.
  • Monitoring covers session misses, login spikes, lock waits, latency, node health, memory, and evictions.
  • The application can tolerate a missing session or can reconstruct critical state from durable storage.

Recommended design decision

For a new deployment, use the memcached extension with an identical multi-node pool on every worker, explicit consistent hashing, session locking, and a tested node-failure procedure. Add replicas only when their protocol and stale-data consequences are understood. If a session must survive cache loss, do not rely on Memcached alone: keep the important state in a durable shared store and treat the PHP session as a cacheable access layer.

Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.

Leave a Reply

Your email address will not be published. Required fields are marked *

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

More from the Wire

  1. World desk4 min
    How to Spot an AI Voice Scam Before Sending MoneyDon’t rely on how a caller sounds. Pause, call back through a known number, and verify the emergency with another trusted person before sending money.
  2. Mountain View desk4 min
    Google’s SynthID Detector: How to Check AI-Generated Images, Video and AudioGoogle’s SynthID Detector looks for an embedded watermark in supported images, video and audio. Here is what its results do—and do not—show.
  3. Redmond desk20 min
    How to create a link to File or Folder in Windows 11Windows 11 gives you several ways to point to a file or folder without moving or duplicating it. You can create a desktop shortcut,…
Recommended PC Tool
Recommended PC Tool
Windows Errors? Fix Them Before They SpreadFree repair scan
Outdated Drivers Are Slowing You DownFree scan - exact matches

Two free Windows tools

One Free Minute Could Fix That PC

Before you go - each of these free tools takes about a minute and tackles what quietly slows a Windows PC down.

Special offer. View Outbyte info, uninstall instructions, EULA, and Privacy Policy.