Back to Top

Where to save sessions in Magento 2?

Updated 22 May 2023

In this blog, we will understand where to save sessions in Magento 2.

In Magento 2, sessions can be stored in various locations, such as files, databases, Redis, and Memcached.

Now, we will check each session locations and configurations to save sessions in Magento 2 along with its Pros & Cons.

1> File system:

The session files are typically stored in the /var/session directory. This is the default location where Magento saves session data for each customer. The session files are created with an .sess extension and contain unique names corresponding to the customer’s session ID, user authentication data, and shopping cart information.

Searching for an experienced
Magento 2 Company ?
Find out More

We can find the session storage location in the app/etc/env.php file of your Magento 2 installation. Look for the following configuration entry:

'session' => [
    'save' => 'files',
    'save_path' => '<path_to_session_directory>',
],

The <path_to_session_directory> will specify the location where session files are stored. By default, it is set to var/session.

It’s important to ensure that the var/session directory is writable by the web server user. We may need to adjust file permissions or ownership if necessary.

If we want to change the session storage location, we can modify the 'save_path' value to a different directory on your server.

Pros:

  1. Performance: File-based session storage can offer better performance compared to database storage in some scenarios. File operations are typically faster and less resource-intensive than database queries.
  2. Simplicity: Configuring file storage for sessions is straightforward, and it does not require additional dependencies or server configurations beyond the file system itself.
  3. Separation of Concerns: Storing sessions as files keeps them separate from other database data, reducing the load on the database server. This separation can lead to better performance and scalability.
  4. Ease of Maintenance: Managing session files is relatively simple. They can be easily cleaned up or purged based on expiration rules or other criteria. This simplifies maintenance tasks and can prevent the session storage from growing too large.

Cons:

  1. File System Limitations: The file system has inherent limitations, such as maximum file count and storage capacity. If you have a high number of concurrent user sessions, the file system might become a bottleneck, impacting performance and scalability.
  2. Session Persistence: With file storage, if the server restarts or encounters issues, session data can be lost. In such cases, users might experience session resets, leading to potential disruptions or a degraded user experience.
  3. File System Backup and Recovery: Including session files in our backup and recovery processes becomes necessary to prevent session data loss. Regular backups ensure that session information can be restored in case of failures.
  4. Limited Centralized Management: Unlike database storage, file-based session storage lacks centralized management capabilities. Analyzing user behavior or performing session-related operations might require additional effort or custom solutions.

Note that: when using file storage for sessions, session data is stored on the local server. This means that if we have multiple web servers or a distributed environment, session data will not be shared across servers. In such cases, you might consider using a different session storage mechanism, such as database storage or a shared session storage solution.

2> Database:

Regarding the database, Magento 2 stores its data in a MySQL database by default. The database configuration details, including the host, username, password, and database name, are specified in the app/etc/env.php file. The session data is stored in the session table of our Magento database.

This option is more scalable than the file system option and is suitable for high-traffic websites. The session storage in the database is better for security but adds additional load to the database.

To configure Magento 2 to store sessions in the database, you need to follow these steps:

1) Open the app/etc/env.php file in a text editor.

2) Look for the 'session' section within the 'db' configuration section. If it doesn’t exist, you can add it manually. It should look like this:

'session' => [
    'save' => 'db',
    'db_connection' => 'default',
    'table' => 'session',
    'cache_limiter' => 'nocache',
    'cookie_lifetime' => 86400,
    'cookie_httponly' => 1,
    'cookie_path' => '/',
    'cookie_domain' => '',
],

We can customize the configuration options according to the requirements.

Pros:

  1. Scalability: Storing sessions in the database allows for easier scalability. We can leverage our database infrastructure to handle increased traffic and concurrent user sessions.
  2. Consistency: With database storage, session data remains intact even if the server restarts or encounters issues. This ensures session persistence and a smoother user experience.
  3. Security: Storing sessions in the database can provide an additional layer of security. Database servers often have robust security measures, access controls, and backup systems in place.
  4. Centralized Management: By using the database for session storage, you have a centralized location for managing session data. This can be beneficial when analyzing user behavior or performing session-related operations.

Cons:

  1. Database Load: Storing sessions in the database increases the load on your database server. Depending on the number of active user sessions, this can impact database performance and potentially require additional resources.
  2. Database Size: The session a table in the database will grow in size as new session records are added. It’s crucial to implement proper session garbage collection to remove expired or inactive sessions and prevent the table from becoming excessively large.
  3. Complexity: Configuring session storage in the database adds complexity to your Magento setup. We need to ensure that the database connection is correctly configured and that the database server can handle the increased load.
  4. Backup and Recovery: When using database storage for sessions, it’s important to include the session table in our database backup and recovery processes to ensure session data is not lost in case of failures.

3> Redis

Redis is an in-memory key-value store that offers high performance, making them ideal for large-scale applications with high traffic volumes.

Ensure that Redis is installed and running on the server. We may need to install the Redis server and PHP Redis extension if they are not already installed.

We can set Redis sessions with the following command:

php bin/magento setup:config:set --session-save=redis --session-save-redis-host=/home/<username>/domains/<domain-name>/var/run/redis.sock --session-save-redis-db=2

In the above command, we only provide a limited number of parameters. If parameters are not included, Magento uses the default values. We can find a complete overview of all parameters that we can give to the command here.

The above command puts a similar configuration in the env.php file

Example:

Below is a sample code to configure the Redis session. Here I declared the main variables that are necessary to configure.

'session' => [
    'save' => 'redis',
    'redis' => [
        'host' => '/home/<username>/domains/<domain>/var/run/redis.sock',
        'port' => '0',
        'password' => '',
        'timeout' => '2.5',
        'persistent_identifier' => '',
        'database' => '2',
        'compression_threshold' => '2048',
        'compression_library' => 'gzip',
        'log_level' => '3',
        'max_concurrency' => '6',
        'break_after_frontend' => '5',
        'break_after_adminhtml' => '30',
        'first_lifetime' => '600',
        'bot_first_lifetime' => '60',
        'bot_lifetime' => '7200',
        'disable_locking' => '0',
        'min_lifetime' => '60',
        'max_lifetime' => '2592000'
    ],
],

Configure the Redis connection settings based on the Redis server setup.

Update the 'host', 'port', 'password', and other relevant options in the 'redis' section.

Pros:

  1. Performance: Redis is an in-memory data store, which provides fast read and write access. Storing sessions in Redis can significantly improve session read and write performance compared to file or database storage.
  2. Scalability: Redis is designed to handle large amounts of data and concurrent connections. It can easily scale horizontally by adding Redis nodes to handle increased session load.
  3. Session Sharing: With Redis, we can configure multiple web servers to share session data. This is useful in a clustered or load-balanced environment where requests can be served by different servers.
  4. Advanced Features: Redis offers additional features like data expiration, key-value storage, and support for complex data structures. These features can be leveraged to implement advanced session management functionality.

Cons:

  1. Dependency on Redis: Using Redis for session storage adds a dependency on Redis. We need to ensure that Redis is properly installed, configured, and running on your server.
  2. Complex Setup: Configuring Redis for session storage requires additional setup and configuration beyond the standard file or database storage options. It involves configuring Redis parameters, such as host, port, password, and other options.
  3. Server Resources: Redis consumes server resources, including memory and CPU. You need to allocate sufficient resources to handle session data, especially if we have a large number of active user sessions.
  4. Redis Management: Redis requires proper monitoring and maintenance. This includes monitoring Redis performance, managing persistence options, and periodically cleaning up expired session

4> Memcache

In Magento 2, we can configure session storage in Memcache to leverage its caching capabilities and enhance the performance of session handling.

Here’s how to save sessions in Memcache in Magento 2:

  1. Ensure that Memcache is installed and configured on your server.
  2. Open the app/etc/env.php file in a text editor.
  3. Add the below code to the session section If it doesn’t exist, add it under the 'db' section.
'session' => [
    'save' => 'memcache',
    'save_path' => 'tcp://<memcache_host>:<memcache_port>?persistent=1&weight=2&timeout=10&retry_interval=10'
],

Replace <memcache_host> with the hostname or IP address of your Memcache server, and <memcache_port> with the Memcache server port number.

Pros:

  1. Performance: Memcache is an in-memory caching system that can significantly improve session read/write performance compared to traditional disk-based storage. It reduces the load on the database and improves response times.
  2. Scalability: Memcache allows for seamless horizontal scaling of your Magento environment. We can add multiple Memcache servers and distribute the session data across them, enabling high availability and increased capacity.
  3. Efficiency: Storing sessions in Memcache eliminates the need for disk I/O operations, resulting in faster access to session data and reducing the overall system resource consumption.
  4. Concurrency: Memcache is designed to handle a high number of concurrent connections efficiently, making it suitable for environments with a large number of active user sessions.

Cons:

  1. Data Volatility: Memcache is an in-memory cache, which means session data is stored in volatile memory. In the event of a server restart or failure, session data can be lost. It’s crucial to have appropriate backup and recovery mechanisms in place to prevent data loss.
  2. Limited Storage Capacity: The storage capacity of Memcache is limited by the available memory. If the session data exceeds the available memory, older or less frequently accessed session data may be evicted from the cache.
  3. Dependency on Memcache: Using Memcache for session storage introduces a dependency on the Memcache service. If the Memcache service becomes unavailable, it can disrupt session handling and impact the functionality of your Magento application.
  4. Configuration and Management: Setting up and maintaining a Memcache infrastructure requires additional configuration and monitoring. It’s essential to ensure the Memcache servers are properly configured, monitored, and updated to avoid potential performance or stability issues.

So, We conclude, the best option for save sessions in Magento 2 depends on your website’s traffic and needs.

That’s it !! Now you understood regarding to save sessions in Magento2

You may like other posts:

Get Collections with SearchCriteriaBuilder in Magento 2

Understanding Magento Theme: Customize Theme (Child-Theme-Concept)

That’s it !!

Thanks & Happy Coding!

. . .

Leave a Comment

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


Be the first to comment.

Back to Top

Message Sent!

If you have more details or questions, you can reply to the received confirmation email.

Back to Home