Search code examples
symfonysulu

Sulu cache always misses


I'm attempting to set up caching Sulu CMS pages. Locally I have set the environment to prod (tried with dev but switched to prod in case this was the problem), but with cache debug turned on.

config/packages/sulu_http_cache.yaml looks like this:

sulu_http_cache:
    proxy_client:
        symfony:
            enabled: true
        debug:
            enabled: true

config/packages/prod/cache.yaml looks like this

framework:
    cache:
        app: cache.adapter.filesystem
        system: cache.adapter.system

The cache directories exist in my /var directory, but they are empty

All responses have the following headers:

enter image description here


Solution

  • If your cache always misses it is a hint that you are accessing a session inside your request. The following in Symfony will automatically start a session e.g.:

    • using a csrf token (csrf_token)
    • configure unlazy firewall on the route (check your security_website.yaml)
    • accessing flash message or other things like that (app.flashes)
    • accessing session itself (app.session)
    • accessing current user (app.user)

    As a session access indicates that the "response" is user specific and not the same for every visitor symfony will set the response to private and so it always a cache miss.

    Edit your code that you are not longer accessing a session and that the Cache-Control Header responses with "public" that the HttpCache Component will cache this response.

    As mention by you the symfony auto behaviour can be disabled by using:

    $response->headers->set(AbstractSessionListener::NO_AUTO_CACHE_CONTROL_HEADER, 1); 
    

    I personally would avoid this as it could cache security specific data or example write a cached username out in your html which you don't want.

    Another way would use the UserContext Based Caching this means that for example every Role has its own Cache for example. A documentation about this can be found:

    This is mostly used when your application has security on the website, and only specific roles can view specific routes.