Configuration
Our system has:
- PHP 8.2
- AWS Memcached library with OpenSSL
- AWS Fargate ECS deployment
- AWS Elasticache
Problem
The initial login for users appears to write and read from memcached. However, upon opening a second tab, our users are getting logged out.
Our Memcached connection configuration is:
// AWS ElastiCache setup
$this->_memcached = new Memcached('persistent-id');
// Set options before adding server
$this->_memcached->setOption(Memcached::OPT_CLIENT_MODE, Memcached::DYNAMIC_CLIENT_MODE);
$this->_memcached->setOption(Memcached::OPT_BINARY_PROTOCOL, true);
$this->_memcached->setOption(Memcached::OPT_TCP_NODELAY, true);
$this->_memcached->setOption(Memcached::OPT_NO_BLOCK, true);
$this->_memcached->setOption(Memcached::OPT_LIBKETAMA_COMPATIBLE, true);
$this->_memcached->setOption(Memcached::OPT_DISTRIBUTION, Memcached::DISTRIBUTION_CONSISTENT);
// Set TLS option before adding server
if (!$this->_memcached->setOption(Memcached::OPT_USE_TLS, true)) {
error_log("Failed to set TLS option: " . $this->_memcached->getLastErrorMessage());
return false;
}
// Configure TLS context
$tls_config = new MemcachedTLSContextConfig();
$tls_config->hostname = '*.cache.amazonaws'; // More general hostname pattern
$tls_config->skip_cert_verify = false;
$tls_config->skip_hostname_verify = false;
// Set TLS context before adding server
try {
$this->_memcached->createAndSetTLSContext((array)$tls_config);
} catch (Exception $e) {
error_log("Failed to set TLS context: " . $e->getMessage());
return false;
}
// Use TLS port (21211) for AWS ElastiCache with TLS
if (!$this->_memcached->addServer($this->_host, 21211)) {
error_log("Failed to add server: " . $this->_memcached->getLastErrorMessage());
return false;
}
In my php.ini, memcached is configured with the following options:
memcached.sess_locking = 1
memcached.sess_lock_wait_min = 150
memcached.sess_lock_wait_max = 150
memcached.sess_lock_retries = 200
memcached.sess_lock_expire = 0
memcached.sess_persistent = 1
memcached.sess_prefix = "memc.sess.key."
memcached.sess_consistent_hash = 1
The AWS Documentation does not make any recommendations for a way to configure the memcached library. Our Docker configuration is pulling their extension and enabling it through the following configuration:
# Install and configure Amazon ElastiCache Cluster Client
RUN curl -L $PHP_VERSION/$MEMCACHED_URL | tar -C /tmp -zx \
&& mv /tmp/amazon-elasticache-cluster-client.so /usr/lib/php/20220829/amazon-elasticache-cluster-client.so \
&& rm -rf /tmp/Readme.markdown \
&& echo "extension=amazon-elasticache-cluster-client.so" >> /etc/php${PHP_VERSION}/php.ini
This appears to enable the amazon elasticache cluster client correctly, as we are not downloading memcached through any other mean and it works as intended on local (connecting to our self-hosted docker/memcached container).