Step 31: Using Redis to Store Sessions

Using Redis to Store Sessions

Depending on the website traffic and/or its infrastructure, you might want to use Redis to manage user sessions instead of PostgreSQL.

When we talked about branching the project’s code to move session from the filesystem to the database, we listed all the needed step to add a new service.

Here is how you can add Redis to your project in one patch:

patch_file

  1. --- a/.symfony.cloud.yaml
  2. +++ b/.symfony.cloud.yaml
  3. @@ -4,6 +4,7 @@ type: php:7.4
  4. runtime:
  5. extensions:
  6. + - redis
  7. - blackfire
  8. - xsl
  9. - pdo_pgsql
  10. @@ -26,6 +27,7 @@ disk: 512
  11. relationships:
  12. database: "db:postgresql"
  13. + redis: "rediscache:redis"
  14. web:
  15. locations:
  16. --- a/.symfony/services.yaml
  17. +++ b/.symfony/services.yaml
  18. @@ -15,3 +15,6 @@ varnish:
  19. files:
  20. type: network-storage:1.0
  21. disk: 256
  22. +
  23. +rediscache:
  24. + type: redis:5.0
  25. --- a/config/packages/framework.yaml
  26. +++ b/config/packages/framework.yaml
  27. @@ -7,7 +7,7 @@ framework:
  28. # Enables session support. Note that the session will ONLY be started if you read or write from it.
  29. # Remove or comment this section to explicitly disable session support.
  30. session:
  31. - handler_id: '%env(DATABASE_URL)%'
  32. + handler_id: '%env(REDIS_URL)%'
  33. cookie_secure: auto
  34. cookie_samesite: lax
  35. --- a/docker-compose.yaml
  36. +++ b/docker-compose.yaml
  37. @@ -17,3 +17,7 @@ services:
  38. image: blackfire/blackfire
  39. env_file: .env.local
  40. ports: [8707]
  41. +
  42. + redis:
  43. + image: redis:5-alpine
  44. + ports: [6379]

Isn’t it beautiful?

“Reboot” Docker to start the Redis service:

  1. $ docker-compose stop
  2. $ docker-compose up -d

Test locally by browsing the website; everything should still work as before.

Commit and deploy as usual:

  1. $ symfony deploy

Going Further


This work, including the code samples, is licensed under a Creative Commons BY-NC-SA 4.0 license.