Skip to content
intermediate Phase 17 · Themes, Libraries & Generated Code

Magento 2 Cache and Session Handling

Cache types, Redis, sessions, and how Magento caches configuration and layout.

45m
0 problems
Topic Progress 0%

Magento Cache Types

Magento 2 has multiple cache types that store different kinds of data to improve performance.

Default cache types:

php bin/magento cache:status
# Output:
# config: 1
# layout: 1
# block_html: 1
# collections: 1
#反射 config: 1
# eav: 1
# full_page: 1
# translate: 1
# compiled_config: 1

Cache type descriptions:

  • config - Configuration XML merged files (di.xml, routes.xml, etc.)
  • layout - Compiled layout XML and block configuration
  • block_html - Rendered block HTML output
  • collections - Database collection results
  • reflection - PHP reflection data for DI
  • db - Database query results
  • eav - EAV entity metadata
  • full_page - Full page HTML output
  • translate - Translation dictionary merge
  • compiled_config - Compiled DI configuration

Cache management commands:

# Flush all caches
php bin/magento cache:flush

# Clean all caches (safe for production)
php bin/magento cache:clean

# Disable specific cache
php bin/magento cache:disable config

# Enable specific cache
php bin/magento cache:enable config

# Check cache status
php bin/magento cache:status

Redis Configuration

Redis is the recommended backend for Magento caching and sessions.

Redis in env.php:

// app/etc/env.php
return [
    'cache' => [
        'frontend' => [
            'default' => [
                'backend' => 'Magento\Framework\Cache\Backend\Redis',
                'backend_options' => [
                    'server' => '127.0.0.1',
                    'port' => '6379',
                    'database' => '0',
                    'compress_data' => '1'
                ]
            ],
            'page_cache' => [
                'backend' => 'Magento\Framework\Cache\Backend\Redis',
                'backend_options' => [
                    'server' => '127.0.0.1',
                    'port' => '6379',
                    'database' => '1',
                    'compress_data' => '0'
                ]
            ]
        ]
    ],
    'session' => [
        'save' => 'redis',
        'redis' => [
            'host' => '127.0.0.1',
            'port' => '6379',
            'database' => '2',
            'password' => '',
            'timeout' => '2.5',
            'persistent_identifier' => '',
            'log_level' => '1',
            'max_concurrency' => '6',
            'break_after_frontend' => '5',
            'break_after_adminhtml' => '30',
            'first_lifetime' => '600',
            'bot_first_lifetime' => '60',
            'bot_lifetime' => '7200',
            'disable_locking' => '0',
            'compression_threshold' => '2048',
            'compression_lib' => 'gzip'
        ]
    ]
];

Redis namespaces:

  • Database 0: General cache
  • Database 1: Full page cache
  • Database 2: Sessions
  • Database 3+: Custom cache pools

Full Page Cache and Varnish

Magento's full-page cache stores complete HTML pages to serve without PHP execution.

Built-in FPC vs Varnish:

  • Built-in FPC: File-based, suitable for small sites
  • Varnish: In-memory, recommended for production

Varnish configuration export:

php bin/magento varnish:export > default.vcl

Varnish VCL excerpt:

vcl 4.0;

backend default {
    .host = "127.0.0.1";
    .port = "8080";
    .first_byte_timeout = 600s;
}

sub vcl_recv {
    if (req.url ~ "^/(media|static)/") {
        return (hash);
    }
    
    if (req.http.Cookie ~ "PHPSESSID=") {
        return (pass);
    }
    
    if (req.url ~ "\.") {
        return (pass);
    }
    
    return (hash);
}

sub vcl_backend_response {
    if (beresp.http.X-Magento-Tags) {
        set beresp.do_gzip = true;
        set beresp.ttl = 86400s;
        set beresp.backend_hint = bereq.backend;
    }
}

Cache invalidation via tags:

// Tag cache entries for targeted invalidation
$cache->save(
    $data,
    $cacheId,
    ['catalog_product_' . $productId, 'category_' . $categoryId]
);

// Invalidate by tag
$cache->clean('catalog_product_' . $productId);

Session Management

Magento 2 supports multiple session storage backends for scalability.

Session backends:

  • files - Default, file-based (not for clustered environments)
  • redis - Recommended for production
  • memcached - Alternative in-memory option

Session configuration in env.php:

'session' => [
    'save' => 'redis',
    'redis' => [
        'host' => '127.0.0.1',
        'port' => '6379',
        'database' => '2',
        'compression' => 'gzip',
        'compression_threshold' => '2048'
    ]
],

Session handlers:

// Custom session handler
class CustomSessionHandler implements \SessionHandlerInterface
{
    public function open($savePath, $sessionName) { /* ... */ }
    public function close() { /* ... */ }
    public function read($sessionId) { /* ... */ }
    public function write($sessionId, $data) { /* ... */ }
    public function destroy($sessionId) { /* ... */ }
    public function gc($maxLifetime) { /* ... */ }
}

Session configuration in di.xml:

<config>
    <type name="Magento\Framework\Session\Config\ConfigStandard">
        <arguments>
            <argument name="sessionMaxLifetime" xsi:type="number">14400</argument>
            <argument name="sessionRememberMe" xsi:type="boolean">true</argument>
        </arguments>
    </type>
</config>

Performance tips:

  • Use Redis for sessions in multi-server setups
  • Set appropriate session lifetime for your business needs
  • Monitor session count for user activity analysis
  • Use persistent connections to Redis for better performance

Quiz

1. Which cache type stores compiled layout XML?

Question 1 options

2. What is the recommended session backend for production?

Question 2 options

3. What command flushes all Magento caches?

Question 3 options

Flashcards

Question

What cache type stores full page HTML output?

Answer

full_page

Question

Which Redis database is typically used for sessions?

Answer

Database 2

Question

What does cache:clean do vs cache:flush?

Answer

clean removes expired entries, flush removes everything

Question

What is the recommended Varnish port for Magento?

Answer

80 (frontend), 8080 (Magento backend)

Revision Notes

Key Takeaways

  • 1. Magento has multiple cache types for different data categories
  • 2. Redis is recommended for both caching and sessions in production
  • 3. Full-page cache can use built-in storage or Varnish
  • 4. Cache tags enable targeted invalidation
  • 5. Session backends: files (default), redis, memcached
  • 6. cache:flush removes everything, cache:clean removes expired

Interview Tips

  • List all Magento cache types and their purposes
  • Explain how to configure Redis for caching and sessions
  • Discuss Varnish integration and cache invalidation
  • Compare cache:clean vs cache:flush
  • Explain why file-based sessions don't work in clustered environments

Cheat Sheet

Cache & Sessions Cheat Sheet

Cache Types:
config, layout, block_html, collections, reflection, db, eav, full_page, translate, compiled_config

Commands:

php bin/magento cache:flush
php bin/magento cache:clean
php bin/magento cache:disable config

Redis Config (env.php):

  • Database 0: General cache
  • Database 1: Full page cache
  • Database 2: Sessions

Varnish:

php bin/magento varnish:export > default.vcl