Skip to content

Instantly share code, notes, and snippets.

@saro0h
Last active March 14, 2016 00:32
Show Gist options
  • Save saro0h/266c9c3516e13a4c2358 to your computer and use it in GitHub Desktop.
Save saro0h/266c9c3516e13a4c2358 to your computer and use it in GitHub Desktop.
Set some caching strategies with Symfony2

Without any strategy of cache

=> see commit: http://bit.ly/1wqwvbe

capture d ecran 2014-10-19 a 21 37 04



With the strategy of cache Cache-Control (private cache for client browser) with a max-age of 2 minutes (120 seconds)

  • At the first refresh: capture d ecran 2014-10-19 a 21 56 02 Notice the "private" mention.

  • Calling the page again (don't do a force refresh, otherwise, your browser will bypass its cache): capture d ecran 2014-10-19 a 21 56 35 Notice that the server is not hit at all.

=> see commit: http://bit.ly/1prET40



With the strategy of cache Cache-Control (public cache for Reverse Proxy / Gateway cache) with a s-maxage of 1 minute (60 seconds)

  • At the first refresh: capture d ecran 2014-10-19 a 22 10 31

  • Calling the page again (60 seconds after the first call): capture d ecran 2014-10-19 a 22 13 13

=> see commit: http://bit.ly/1vQHz2C



With an esi

  • At the first refresh: capture d ecran 2014-10-19 a 22 29 37 We can see that both the page / and the fragment have a stale cache.

  • At the second refresh (less than 20 seconds after the first one): capture d ecran 2014-10-19 a 22 30 02 We can see that both the page / and the fragment have a fresh cache (no need to regenerate the response).

  • A the third refresh (35 seconds after the first refresh): capture d ecran 2014-10-19 a 22 35 17 We can see that only the cached fragment is stale, time to regenerate a new response.

Nota Bene: You can take a look at the Symfony Profiler to notice the second request for the ESI (_fragmentxxxx capture d ecran 2014-10-19 a 22 32 39).

=> see commit: http://bit.ly/1wial91

Now you can have fun with all of that !



You may have notice that you can access the fragment directly from its url. Not that good uh?

Let's secure it with this, in the file security.yml :

  access_control:
    - { path: ^/_fragment, roles: IS_AUTHENTICATED_ANONYMOUSLY, ip: 127.0.0.1 }
    - { path: ^/_fragment, roles: ROLE_ESI }

Basically, if the client ip is 127.0.0.1 (the ip of your reverse proxy cache), the fragment is accessible, that way your RPC can get the missing fragment to replace the <esi:include src="xxx"> properly, otherwise, it is accessible by the user having the role ROLE_ESI (which nobody has so it's not accessible).

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment