SlideShare a Scribd company logo
1 of 31
Download to read offline
HEAD FIRST INTO SYMFONY
CACHE, REDIS & REDIS CLUSTER
André Rømcke (@andrerom)
VP Technical Services & Support @ eZ Systems (@ezsystems)
November 22nd 2019 - Amsterdam - SymfonyCon
So what is this talk about?
How Symfony 4.3/4.4 ended up
with new Adapters:
FilesystemTagAware &
RedisTagAware
Agenda:

1. Where eZ fits in

2. Some THEORY:

- Symfony Cache

- Cache tagging

- Redis & Redis Cluster

- Memcached vs Redis

5. New Adapters 

6. Demo time

7. BONUS & Edge cases
Who?
๏André Rømcke | @andrerom
๏Economics, Consulting, Engineering, Lead, VP, now doing Services & Support
๏Tried to contribute to Symfony, FOS, Composer, PHP-FIG, Docker Compose
๏eZ Systems AS | ez.no
๏75+ people across 7+ countries. Partners & community in many many more
๏eZ Platform | ezplatform.com
๏Open Source CMS, feature rich, very extendable, flexible Full & Headless
๏On Symfony since 2012
๏Commercial with additional features: eZ Platform Enterprise & eZ Commerce
Symfony Cache in eZ Platform
๏Moved over from Stash in 2017
๏Heavily relies on Cache tagging feature
๏Contributed improvements on performance issues with Redis/Redis Cluster/…
๏… and for 4.3 /4.4: optimized TagAware adapters for Redis and FileSystem
Quick recap:
Symfony Cache
Recap: Symfony Cache Component
๏PSR-6 compliant Cache component
๏Aims to be fast: Among others supports multi get calls to Redis and Memcached
๏Is progressively being used in several places in Symfony Framework, e.g.:
๏PropertyInfo
๏Serializer
๏Validator
๏(…)
๏.. maybe HTTP Cache at some point
Recap: Symfony Cache Adapters
๏Adapters:
๏APCu
๏Array
๏Chain
๏Doctrine
๏FileSystem
๏Opcache based: PhpFile + PhpArray
๏Proxy (PSR-6) + Psr16
๏Redis
๏Memcached
๏And “TagAware”..
Cache labeling:
Tags?
Tags?
๏Data/Entities often has secondary indexes, e.g:
๏entity type id
๏placement id
๏variant type, …
๏Operations in your application sometimes affect those => Affecting bulk of entities
๏By tagging cache you can directly invalidate:
๏E.g. key: ez-content-66 tags: content-66, type-2, location-44 (…)
TagAware: Secondary index for invalidation
/**
* Interface for invalidating cached items using tags.
*
* @author Nicolas Grekas <p@tchwork.com>
*/
interface TagAwareAdapterInterface extends AdapterInterface
{
/**
* Invalidates cached items using tags.
*
* @param string[] $tags An array of tags to invalidate
*
* @return bool True on success
*
* @throws InvalidArgumentException When $tags is not valid
*/
public function invalidateTags(array $tags);
}
TagAwareAdapter
๏Wraps your normal adapter, stores item Tags in separate key
๏Does a separate lookup for expiry timestamp for tags => “2-RTT”
Topics around:
Redis & Redis Cluster
Redis: Datatypes
๏ Strings
๏ Lists
๏ Sets
๏ SortedSets
๏ Hashes
๏ Bitmaps
๏ HyperLogLogs
๏ Streams (As of Redis 5.0)
Redis: Commands
๏There are 227 commands and counting
๏There are generic key, cluster, connection, Pub/Sub, Scripting, Transaction commands
๏And Datatypes allows for specific operations/commands:
๏E.g. “String”: GET, SET, APPEND, BITPOS, DECR, …
๏"SET”:
๏SADD, SREM, SPOP
๏SDIFF, SINTER, SUNION, SMOVE
๏SMEMBERS, SSCAN
๏…
Redis: Eviction
maxmemory-policy:
๏noeviction
๏volatile-random
๏volatile-ttl
๏volatile-lru
๏volatile-lfu (As of Redis 4.0)
๏allkeys-random
๏allkeys-lru
๏allkeys-lfu (As of Redis 4.0)
Redis Cluster: processe
๏Allows you to scale up Redis by running several instances
๏Multi process on same server and/or across servers
๏Coordinates cache across “cache slots", deals with replication, …
๏Unlike Memcached, several operations has limitations on Cluster
Redis Cluster: limitations
๏Does not support “pipline”: capability to perform several operations in one call
๏PHPRedis mainly supports multi operations on MGET and MSET with cluster
๏Examples of affected operations:
๏RENAME won’t work if the new key ends up in another “Cache Slot”
๏EVAL (Lua Script) likewise can only be given keys that maps to same node
ERR	CROSSSLOT	Keys	in	request	don't	hash	to	the	same	slot
FYI on strength and weaknesses:
Memcached vs Redis
Memcached vs Redis: Overview
๏Vivamus commodo ipsum in hendrerit iaculis.
๏Donec congue erat nibh, ac luctus erat accumsan tempor.
๏Mauris bibendum ac eros eu tempor. Duis libero libero, luctus quis posuere quis, porta vel
turpis.
๏Sed augue dolor, laoreet eget turpis eget, laoreet vehicula neque. Donec sit amet dolor vel
lorem ultrices facilisis ac sit amet velit.
๏Aenean nisi nisi, aliquet in pulvinar mollis, vulputate vitae nulla. Donec non ligula ac diam
volutpat dapibus.
๏Aliquam eleifend turpis id ligula accumsan luctus. Donec sem justo, scelerisque eget
condimentum ut, semper eget nulla.
๏Vivamus ultricies massa lectus, id varius orci sodales quis.
Memcached Redis
Multi operations (get, set, ..) V V
Datatypes String
String, List, Set, Hash, Sorted Set, …
Streams
Control over eviction X V
Persistance X V
Pipeline / Lua X V
Some limitations on Redis Cluster
Multiserver V V
Using e.g. Redis Cluster OR Redis Sentinel
Multithreaded V X
But multi process with Redis Cluster *
* Redis 6 is adding partly threading with background thread handling slow operations
New Adapters in Symfony 4.3/4.4:
FilesystemTagAware & RedisTagAware
Tags storage
๏Moves tags to be a “relation” to cache key, instead of expiry time
๏Avoids the lookup tags on getItem(s), instead does it on invalidation
➡ 1-RTT for lookups
๏FilesystemTagAwareAdapter: Uses a file for tag “relations”
๏RedisTagAwareAdapter: Uses “Set” for tag “relation” => w/o expiry
Why the efforts on 1-RTT lookups?
๏AWS ElasticCache Redis instances has latency of around 0.2-0.5ms
๏E.g. Simple page with 20 articles shown:
๏~40 lookups x latency = 5-20 ms
๏E.g. News site landing page with 1000 articles listed:
๏~2000 lookups x latency = 0.4 - 1 seconds
In Symfony Cache:
๏Pipeline used instead of MGET => Allows parallel lookups with Redis Cluster
๏Remove need for cache versioning lookups on Redis cluster
๏TagAwareAdapter micro ttl cache for tag lookups
Lookup optimizations done over the last year
On Application side (eZ Platform):
๏Changs take better advantage of Multi Get
๏Introduce optimized RedisTagAwareAdapter
๏Introduced Application specific in-memory cache
Lookup optimizations done over the last year
End result example:
๏Had 17.000 lookups in Symfony Cache on our Admin dashboard
๏Due to Symfony Cache logic this was ~40-60k lookups on Redis Cluster
๏30 seconds in worst case, just waiting for Redis Cluster
๏After all fixes it went down to 63 lookups in Symfony Cache
Lookup optimizations done over the last year
Demo time:
Lets adapt symfony/demo to make it cached
Demo code: https://github.com/andrerom/sfcon-amsterdam-2019-redis-cache-demo
Bonus and Edge cases:
Some things to be aware of
Bonus: Edge cases in Caching
๏Race conditions
๏When caching entities: Transactions
๏Async / Stale cache
Bonus: Adapter recommendations
๏RedisTagAwareAdapter
Requirement: maxmemory-policy: volatile-ttl / volatile-lru / volatile-lfu (Redis 4.0+)
Pro: 1-RTT
Con: Consumes more memory, risk of running out of evictable memory
๏RedisAdapter + TagAwareAdapter:
Pro: Uses less memory then RedisTagAwareAdapter + all can be freed
Con: 2-RTT
๏MemcachedAdapter + TagAwareAdapter:
Pro: Uses less memory due to simpler data structure + all can be freed
Cable off handling more traffic
Con: 2-RTT
Bonus: Simulating RedisTagAware in bash
๏Save:
redis-cli set mykey data
redis-cli sadd type-article:tags mykey anotherkey
๏Read:
redis-cli mget mykey anotherkey
๏Invalidation:
tmp=$(cat /dev/urandom | tr -dc 'a-zA-Z0-9' | fold -w 32 | head -n 1)
redis-cli rename type-article:tags {type-article:tags}-$tmp
members=`redis-cli smembers {type-article:tags}-$tmp`
redis-cli del {type-article:tags}-$tmp $members
TIP:
To run these commands:
docker	run	--name	myredis	-p	6379:6379	-d	redis	
docker	exec	-ti	myredis	bash
After “exit”, you can clean up using:
docker	rm	-f	myredis
Fin..
Questions?
Other talks: http://www.slideshare.net/andreromcke
Twitter: @andrerom
eZ Platform: https://ezplatform.com/
Redis: https://redis.io/
Memcached: https://memcached.org
Demo code: https://github.com/andrerom/sfcon-amsterdam-2019-redis-cache-demo

More Related Content

What's hot

What's hot (20)

MyRocks Deep Dive
MyRocks Deep DiveMyRocks Deep Dive
MyRocks Deep Dive
 
Troubleshooting Complex Performance issues - Oracle SEG$ contention
Troubleshooting Complex Performance issues - Oracle SEG$ contentionTroubleshooting Complex Performance issues - Oracle SEG$ contention
Troubleshooting Complex Performance issues - Oracle SEG$ contention
 
High Performance, High Reliability Data Loading on ClickHouse
High Performance, High Reliability Data Loading on ClickHouseHigh Performance, High Reliability Data Loading on ClickHouse
High Performance, High Reliability Data Loading on ClickHouse
 
ClickHouse Materialized Views: The Magic Continues
ClickHouse Materialized Views: The Magic ContinuesClickHouse Materialized Views: The Magic Continues
ClickHouse Materialized Views: The Magic Continues
 
Apache Cassandra at the Geek2Geek Berlin
Apache Cassandra at the Geek2Geek BerlinApache Cassandra at the Geek2Geek Berlin
Apache Cassandra at the Geek2Geek Berlin
 
Problems with PostgreSQL on Multi-core Systems with MultiTerabyte Data
Problems with PostgreSQL on Multi-core Systems with MultiTerabyte DataProblems with PostgreSQL on Multi-core Systems with MultiTerabyte Data
Problems with PostgreSQL on Multi-core Systems with MultiTerabyte Data
 
Altinity Quickstart for ClickHouse
Altinity Quickstart for ClickHouseAltinity Quickstart for ClickHouse
Altinity Quickstart for ClickHouse
 
High Availability for Oracle SE2
High Availability for Oracle SE2High Availability for Oracle SE2
High Availability for Oracle SE2
 
The Missing Manual for Leveled Compaction Strategy (Wei Deng & Ryan Svihla, D...
The Missing Manual for Leveled Compaction Strategy (Wei Deng & Ryan Svihla, D...The Missing Manual for Leveled Compaction Strategy (Wei Deng & Ryan Svihla, D...
The Missing Manual for Leveled Compaction Strategy (Wei Deng & Ryan Svihla, D...
 
Deep Dive on ClickHouse Sharding and Replication-2202-09-22.pdf
Deep Dive on ClickHouse Sharding and Replication-2202-09-22.pdfDeep Dive on ClickHouse Sharding and Replication-2202-09-22.pdf
Deep Dive on ClickHouse Sharding and Replication-2202-09-22.pdf
 
MySQL Buffer Management
MySQL Buffer ManagementMySQL Buffer Management
MySQL Buffer Management
 
Load Balancing MySQL with HAProxy - Slides
Load Balancing MySQL with HAProxy - SlidesLoad Balancing MySQL with HAProxy - Slides
Load Balancing MySQL with HAProxy - Slides
 
Galera Replication Demystified: How Does It Work?
Galera Replication Demystified: How Does It Work?Galera Replication Demystified: How Does It Work?
Galera Replication Demystified: How Does It Work?
 
Top 5 Mistakes When Writing Spark Applications
Top 5 Mistakes When Writing Spark ApplicationsTop 5 Mistakes When Writing Spark Applications
Top 5 Mistakes When Writing Spark Applications
 
Pacemaker 操作方法メモ
Pacemaker 操作方法メモPacemaker 操作方法メモ
Pacemaker 操作方法メモ
 
Inside Parquet Format
Inside Parquet FormatInside Parquet Format
Inside Parquet Format
 
[TDC2016] Apache Cassandra Estratégias de Modelagem de Dados
[TDC2016]  Apache Cassandra Estratégias de Modelagem de Dados[TDC2016]  Apache Cassandra Estratégias de Modelagem de Dados
[TDC2016] Apache Cassandra Estratégias de Modelagem de Dados
 
行ロックと「LOG: process 12345 still waiting for ShareLock on transaction 710 afte...
行ロックと「LOG:  process 12345 still waiting for ShareLock on transaction 710 afte...行ロックと「LOG:  process 12345 still waiting for ShareLock on transaction 710 afte...
行ロックと「LOG: process 12345 still waiting for ShareLock on transaction 710 afte...
 
統計情報のリセットによるautovacuumへの影響について(第39回PostgreSQLアンカンファレンス@オンライン 発表資料)
統計情報のリセットによるautovacuumへの影響について(第39回PostgreSQLアンカンファレンス@オンライン 発表資料)統計情報のリセットによるautovacuumへの影響について(第39回PostgreSQLアンカンファレンス@オンライン 発表資料)
統計情報のリセットによるautovacuumへの影響について(第39回PostgreSQLアンカンファレンス@オンライン 発表資料)
 
Chasing the optimizer
Chasing the optimizerChasing the optimizer
Chasing the optimizer
 

Similar to SymfonyCon 2019: Head first into Symfony Cache, Redis & Redis Cluster

Смарт-контракты: базовые инструменты для разработки и тестирования. Спикер: Д...
Смарт-контракты: базовые инструменты для разработки и тестирования. Спикер: Д...Смарт-контракты: базовые инструменты для разработки и тестирования. Спикер: Д...
Смарт-контракты: базовые инструменты для разработки и тестирования. Спикер: Д...
Cyber Fund
 
Porting Rails Apps to High Availability Systems
Porting Rails Apps to High Availability SystemsPorting Rails Apps to High Availability Systems
Porting Rails Apps to High Availability Systems
Marcelo Pinheiro
 

Similar to SymfonyCon 2019: Head first into Symfony Cache, Redis & Redis Cluster (20)

SfDay 2019: Head first into Symfony Cache, Redis & Redis Cluster
SfDay 2019: Head first into Symfony Cache, Redis & Redis ClusterSfDay 2019: Head first into Symfony Cache, Redis & Redis Cluster
SfDay 2019: Head first into Symfony Cache, Redis & Redis Cluster
 
How to deploy & optimize eZ Publish (2014)
How to deploy & optimize eZ Publish (2014)How to deploy & optimize eZ Publish (2014)
How to deploy & optimize eZ Publish (2014)
 
EC2 Storage for Docker 150526b
EC2 Storage for Docker   150526bEC2 Storage for Docker   150526b
EC2 Storage for Docker 150526b
 
PHP Benelux 2017 - Caching The Right Way
PHP Benelux 2017 -  Caching The Right WayPHP Benelux 2017 -  Caching The Right Way
PHP Benelux 2017 - Caching The Right Way
 
Apidays Paris 2023 - Forget TypeScript, Choose Rust to build Robust, Fast and...
Apidays Paris 2023 - Forget TypeScript, Choose Rust to build Robust, Fast and...Apidays Paris 2023 - Forget TypeScript, Choose Rust to build Robust, Fast and...
Apidays Paris 2023 - Forget TypeScript, Choose Rust to build Robust, Fast and...
 
Amazon EC2 deepdive and a sprinkel of AWS Compute | AWS Floor28
Amazon EC2 deepdive and a sprinkel of AWS Compute | AWS Floor28Amazon EC2 deepdive and a sprinkel of AWS Compute | AWS Floor28
Amazon EC2 deepdive and a sprinkel of AWS Compute | AWS Floor28
 
Смарт-контракты: базовые инструменты для разработки и тестирования. Спикер: Д...
Смарт-контракты: базовые инструменты для разработки и тестирования. Спикер: Д...Смарт-контракты: базовые инструменты для разработки и тестирования. Спикер: Д...
Смарт-контракты: базовые инструменты для разработки и тестирования. Спикер: Д...
 
RedisConf17 - Doing More With Redis - Ofer Bengal and Yiftach Shoolman
RedisConf17 - Doing More With Redis - Ofer Bengal and Yiftach ShoolmanRedisConf17 - Doing More With Redis - Ofer Bengal and Yiftach Shoolman
RedisConf17 - Doing More With Redis - Ofer Bengal and Yiftach Shoolman
 
Engineering an Encrypted Storage Engine
Engineering an Encrypted Storage EngineEngineering an Encrypted Storage Engine
Engineering an Encrypted Storage Engine
 
Caching and tuning fun for high scalability
Caching and tuning fun for high scalabilityCaching and tuning fun for high scalability
Caching and tuning fun for high scalability
 
Symfony live London 2018 - Take your http caching to the next level with xke...
Symfony live London 2018 -  Take your http caching to the next level with xke...Symfony live London 2018 -  Take your http caching to the next level with xke...
Symfony live London 2018 - Take your http caching to the next level with xke...
 
CoreOS, or How I Learned to Stop Worrying and Love Systemd
CoreOS, or How I Learned to Stop Worrying and Love SystemdCoreOS, or How I Learned to Stop Worrying and Love Systemd
CoreOS, or How I Learned to Stop Worrying and Love Systemd
 
Drupal Efficiency - Coding, Deployment, Scaling
Drupal Efficiency - Coding, Deployment, ScalingDrupal Efficiency - Coding, Deployment, Scaling
Drupal Efficiency - Coding, Deployment, Scaling
 
Developer insight into why applications run amazingly Fast in CF 2018
Developer insight into why applications run amazingly Fast in CF 2018Developer insight into why applications run amazingly Fast in CF 2018
Developer insight into why applications run amazingly Fast in CF 2018
 
Porting Rails Apps to High Availability Systems
Porting Rails Apps to High Availability SystemsPorting Rails Apps to High Availability Systems
Porting Rails Apps to High Availability Systems
 
Caching and tuning fun for high scalability @ FrOSCon 2011
Caching and tuning fun for high scalability @ FrOSCon 2011Caching and tuning fun for high scalability @ FrOSCon 2011
Caching and tuning fun for high scalability @ FrOSCon 2011
 
(DAT407) Amazon ElastiCache: Deep Dive
(DAT407) Amazon ElastiCache: Deep Dive(DAT407) Amazon ElastiCache: Deep Dive
(DAT407) Amazon ElastiCache: Deep Dive
 
The value of reactive
The value of reactiveThe value of reactive
The value of reactive
 
The Value of Reactive
The Value of ReactiveThe Value of Reactive
The Value of Reactive
 
6 tips for improving ruby performance
6 tips for improving ruby performance6 tips for improving ruby performance
6 tips for improving ruby performance
 

More from André Rømcke

eZ Publish 5, Re architecture, pitfalls and opportunities
eZ Publish 5, Re architecture, pitfalls and opportunitieseZ Publish 5, Re architecture, pitfalls and opportunities
eZ Publish 5, Re architecture, pitfalls and opportunities
André Rømcke
 

More from André Rømcke (6)

Look Towards 2.0 and Beyond - eZ Conference 2016
Look Towards 2.0 and Beyond -   eZ Conference 2016Look Towards 2.0 and Beyond -   eZ Conference 2016
Look Towards 2.0 and Beyond - eZ Conference 2016
 
Getting instantly up and running with Docker and Symfony
Getting instantly up and running with Docker and SymfonyGetting instantly up and running with Docker and Symfony
Getting instantly up and running with Docker and Symfony
 
Dockerize your Symfony application - Symfony Live NYC 2014
Dockerize your Symfony application - Symfony Live NYC 2014Dockerize your Symfony application - Symfony Live NYC 2014
Dockerize your Symfony application - Symfony Live NYC 2014
 
PhpTour Lyon 2014 - Transparent caching & context aware http cache
PhpTour Lyon 2014 - Transparent caching & context aware http cachePhpTour Lyon 2014 - Transparent caching & context aware http cache
PhpTour Lyon 2014 - Transparent caching & context aware http cache
 
eZ publish 5[-alpha1] Introduction & Architecture
eZ publish 5[-alpha1] Introduction & ArchitectureeZ publish 5[-alpha1] Introduction & Architecture
eZ publish 5[-alpha1] Introduction & Architecture
 
eZ Publish 5, Re architecture, pitfalls and opportunities
eZ Publish 5, Re architecture, pitfalls and opportunitieseZ Publish 5, Re architecture, pitfalls and opportunities
eZ Publish 5, Re architecture, pitfalls and opportunities
 

Recently uploaded

Recently uploaded (20)

Vector Search @ sw2con for slideshare.pptx
Vector Search @ sw2con for slideshare.pptxVector Search @ sw2con for slideshare.pptx
Vector Search @ sw2con for slideshare.pptx
 
Working together SRE & Platform Engineering
Working together SRE & Platform EngineeringWorking together SRE & Platform Engineering
Working together SRE & Platform Engineering
 
JavaScript Usage Statistics 2024 - The Ultimate Guide
JavaScript Usage Statistics 2024 - The Ultimate GuideJavaScript Usage Statistics 2024 - The Ultimate Guide
JavaScript Usage Statistics 2024 - The Ultimate Guide
 
WebAssembly is Key to Better LLM Performance
WebAssembly is Key to Better LLM PerformanceWebAssembly is Key to Better LLM Performance
WebAssembly is Key to Better LLM Performance
 
Google I/O Extended 2024 Warsaw
Google I/O Extended 2024 WarsawGoogle I/O Extended 2024 Warsaw
Google I/O Extended 2024 Warsaw
 
UiPath manufacturing technology benefits and AI overview
UiPath manufacturing technology benefits and AI overviewUiPath manufacturing technology benefits and AI overview
UiPath manufacturing technology benefits and AI overview
 
Continuing Bonds Through AI: A Hermeneutic Reflection on Thanabots
Continuing Bonds Through AI: A Hermeneutic Reflection on ThanabotsContinuing Bonds Through AI: A Hermeneutic Reflection on Thanabots
Continuing Bonds Through AI: A Hermeneutic Reflection on Thanabots
 
الأمن السيبراني - ما لا يسع للمستخدم جهله
الأمن السيبراني - ما لا يسع للمستخدم جهلهالأمن السيبراني - ما لا يسع للمستخدم جهله
الأمن السيبراني - ما لا يسع للمستخدم جهله
 
ChatGPT and Beyond - Elevating DevOps Productivity
ChatGPT and Beyond - Elevating DevOps ProductivityChatGPT and Beyond - Elevating DevOps Productivity
ChatGPT and Beyond - Elevating DevOps Productivity
 
ADP Passwordless Journey Case Study.pptx
ADP Passwordless Journey Case Study.pptxADP Passwordless Journey Case Study.pptx
ADP Passwordless Journey Case Study.pptx
 
Design Guidelines for Passkeys 2024.pptx
Design Guidelines for Passkeys 2024.pptxDesign Guidelines for Passkeys 2024.pptx
Design Guidelines for Passkeys 2024.pptx
 
Introduction to use of FHIR Documents in ABDM
Introduction to use of FHIR Documents in ABDMIntroduction to use of FHIR Documents in ABDM
Introduction to use of FHIR Documents in ABDM
 
Easier, Faster, and More Powerful – Notes Document Properties Reimagined
Easier, Faster, and More Powerful – Notes Document Properties ReimaginedEasier, Faster, and More Powerful – Notes Document Properties Reimagined
Easier, Faster, and More Powerful – Notes Document Properties Reimagined
 
Introduction to FIDO Authentication and Passkeys.pptx
Introduction to FIDO Authentication and Passkeys.pptxIntroduction to FIDO Authentication and Passkeys.pptx
Introduction to FIDO Authentication and Passkeys.pptx
 
Observability Concepts EVERY Developer Should Know (DevOpsDays Seattle)
Observability Concepts EVERY Developer Should Know (DevOpsDays Seattle)Observability Concepts EVERY Developer Should Know (DevOpsDays Seattle)
Observability Concepts EVERY Developer Should Know (DevOpsDays Seattle)
 
JohnPollard-hybrid-app-RailsConf2024.pptx
JohnPollard-hybrid-app-RailsConf2024.pptxJohnPollard-hybrid-app-RailsConf2024.pptx
JohnPollard-hybrid-app-RailsConf2024.pptx
 
Overview of Hyperledger Foundation
Overview of Hyperledger FoundationOverview of Hyperledger Foundation
Overview of Hyperledger Foundation
 
WebRTC and SIP not just audio and video @ OpenSIPS 2024
WebRTC and SIP not just audio and video @ OpenSIPS 2024WebRTC and SIP not just audio and video @ OpenSIPS 2024
WebRTC and SIP not just audio and video @ OpenSIPS 2024
 
Portal Kombat : extension du réseau de propagande russe
Portal Kombat : extension du réseau de propagande russePortal Kombat : extension du réseau de propagande russe
Portal Kombat : extension du réseau de propagande russe
 
2024 May Patch Tuesday
2024 May Patch Tuesday2024 May Patch Tuesday
2024 May Patch Tuesday
 

SymfonyCon 2019: Head first into Symfony Cache, Redis & Redis Cluster

  • 1. HEAD FIRST INTO SYMFONY CACHE, REDIS & REDIS CLUSTER André Rømcke (@andrerom) VP Technical Services & Support @ eZ Systems (@ezsystems) November 22nd 2019 - Amsterdam - SymfonyCon
  • 2. So what is this talk about? How Symfony 4.3/4.4 ended up with new Adapters: FilesystemTagAware & RedisTagAware Agenda:
 1. Where eZ fits in 2. Some THEORY:
 - Symfony Cache - Cache tagging
 - Redis & Redis Cluster - Memcached vs Redis 5. New Adapters 
 6. Demo time 7. BONUS & Edge cases
  • 3. Who? ๏André Rømcke | @andrerom ๏Economics, Consulting, Engineering, Lead, VP, now doing Services & Support ๏Tried to contribute to Symfony, FOS, Composer, PHP-FIG, Docker Compose ๏eZ Systems AS | ez.no ๏75+ people across 7+ countries. Partners & community in many many more ๏eZ Platform | ezplatform.com ๏Open Source CMS, feature rich, very extendable, flexible Full & Headless ๏On Symfony since 2012 ๏Commercial with additional features: eZ Platform Enterprise & eZ Commerce
  • 4. Symfony Cache in eZ Platform ๏Moved over from Stash in 2017 ๏Heavily relies on Cache tagging feature ๏Contributed improvements on performance issues with Redis/Redis Cluster/… ๏… and for 4.3 /4.4: optimized TagAware adapters for Redis and FileSystem
  • 6. Recap: Symfony Cache Component ๏PSR-6 compliant Cache component ๏Aims to be fast: Among others supports multi get calls to Redis and Memcached ๏Is progressively being used in several places in Symfony Framework, e.g.: ๏PropertyInfo ๏Serializer ๏Validator ๏(…) ๏.. maybe HTTP Cache at some point
  • 7. Recap: Symfony Cache Adapters ๏Adapters: ๏APCu ๏Array ๏Chain ๏Doctrine ๏FileSystem ๏Opcache based: PhpFile + PhpArray ๏Proxy (PSR-6) + Psr16 ๏Redis ๏Memcached ๏And “TagAware”..
  • 9. Tags? ๏Data/Entities often has secondary indexes, e.g: ๏entity type id ๏placement id ๏variant type, … ๏Operations in your application sometimes affect those => Affecting bulk of entities ๏By tagging cache you can directly invalidate: ๏E.g. key: ez-content-66 tags: content-66, type-2, location-44 (…)
  • 10. TagAware: Secondary index for invalidation /** * Interface for invalidating cached items using tags. * * @author Nicolas Grekas <p@tchwork.com> */ interface TagAwareAdapterInterface extends AdapterInterface { /** * Invalidates cached items using tags. * * @param string[] $tags An array of tags to invalidate * * @return bool True on success * * @throws InvalidArgumentException When $tags is not valid */ public function invalidateTags(array $tags); }
  • 11. TagAwareAdapter ๏Wraps your normal adapter, stores item Tags in separate key ๏Does a separate lookup for expiry timestamp for tags => “2-RTT”
  • 12. Topics around: Redis & Redis Cluster
  • 13. Redis: Datatypes ๏ Strings ๏ Lists ๏ Sets ๏ SortedSets ๏ Hashes ๏ Bitmaps ๏ HyperLogLogs ๏ Streams (As of Redis 5.0)
  • 14. Redis: Commands ๏There are 227 commands and counting ๏There are generic key, cluster, connection, Pub/Sub, Scripting, Transaction commands ๏And Datatypes allows for specific operations/commands: ๏E.g. “String”: GET, SET, APPEND, BITPOS, DECR, … ๏"SET”: ๏SADD, SREM, SPOP ๏SDIFF, SINTER, SUNION, SMOVE ๏SMEMBERS, SSCAN ๏…
  • 15. Redis: Eviction maxmemory-policy: ๏noeviction ๏volatile-random ๏volatile-ttl ๏volatile-lru ๏volatile-lfu (As of Redis 4.0) ๏allkeys-random ๏allkeys-lru ๏allkeys-lfu (As of Redis 4.0)
  • 16. Redis Cluster: processe ๏Allows you to scale up Redis by running several instances ๏Multi process on same server and/or across servers ๏Coordinates cache across “cache slots", deals with replication, … ๏Unlike Memcached, several operations has limitations on Cluster
  • 17. Redis Cluster: limitations ๏Does not support “pipline”: capability to perform several operations in one call ๏PHPRedis mainly supports multi operations on MGET and MSET with cluster ๏Examples of affected operations: ๏RENAME won’t work if the new key ends up in another “Cache Slot” ๏EVAL (Lua Script) likewise can only be given keys that maps to same node ERR CROSSSLOT Keys in request don't hash to the same slot
  • 18. FYI on strength and weaknesses: Memcached vs Redis
  • 19. Memcached vs Redis: Overview ๏Vivamus commodo ipsum in hendrerit iaculis. ๏Donec congue erat nibh, ac luctus erat accumsan tempor. ๏Mauris bibendum ac eros eu tempor. Duis libero libero, luctus quis posuere quis, porta vel turpis. ๏Sed augue dolor, laoreet eget turpis eget, laoreet vehicula neque. Donec sit amet dolor vel lorem ultrices facilisis ac sit amet velit. ๏Aenean nisi nisi, aliquet in pulvinar mollis, vulputate vitae nulla. Donec non ligula ac diam volutpat dapibus. ๏Aliquam eleifend turpis id ligula accumsan luctus. Donec sem justo, scelerisque eget condimentum ut, semper eget nulla. ๏Vivamus ultricies massa lectus, id varius orci sodales quis. Memcached Redis Multi operations (get, set, ..) V V Datatypes String String, List, Set, Hash, Sorted Set, … Streams Control over eviction X V Persistance X V Pipeline / Lua X V Some limitations on Redis Cluster Multiserver V V Using e.g. Redis Cluster OR Redis Sentinel Multithreaded V X But multi process with Redis Cluster * * Redis 6 is adding partly threading with background thread handling slow operations
  • 20. New Adapters in Symfony 4.3/4.4: FilesystemTagAware & RedisTagAware
  • 21. Tags storage ๏Moves tags to be a “relation” to cache key, instead of expiry time ๏Avoids the lookup tags on getItem(s), instead does it on invalidation ➡ 1-RTT for lookups ๏FilesystemTagAwareAdapter: Uses a file for tag “relations” ๏RedisTagAwareAdapter: Uses “Set” for tag “relation” => w/o expiry
  • 22. Why the efforts on 1-RTT lookups? ๏AWS ElasticCache Redis instances has latency of around 0.2-0.5ms ๏E.g. Simple page with 20 articles shown: ๏~40 lookups x latency = 5-20 ms ๏E.g. News site landing page with 1000 articles listed: ๏~2000 lookups x latency = 0.4 - 1 seconds
  • 23. In Symfony Cache: ๏Pipeline used instead of MGET => Allows parallel lookups with Redis Cluster ๏Remove need for cache versioning lookups on Redis cluster ๏TagAwareAdapter micro ttl cache for tag lookups Lookup optimizations done over the last year
  • 24. On Application side (eZ Platform): ๏Changs take better advantage of Multi Get ๏Introduce optimized RedisTagAwareAdapter ๏Introduced Application specific in-memory cache Lookup optimizations done over the last year
  • 25. End result example: ๏Had 17.000 lookups in Symfony Cache on our Admin dashboard ๏Due to Symfony Cache logic this was ~40-60k lookups on Redis Cluster ๏30 seconds in worst case, just waiting for Redis Cluster ๏After all fixes it went down to 63 lookups in Symfony Cache Lookup optimizations done over the last year
  • 26. Demo time: Lets adapt symfony/demo to make it cached Demo code: https://github.com/andrerom/sfcon-amsterdam-2019-redis-cache-demo
  • 27. Bonus and Edge cases: Some things to be aware of
  • 28. Bonus: Edge cases in Caching ๏Race conditions ๏When caching entities: Transactions ๏Async / Stale cache
  • 29. Bonus: Adapter recommendations ๏RedisTagAwareAdapter Requirement: maxmemory-policy: volatile-ttl / volatile-lru / volatile-lfu (Redis 4.0+) Pro: 1-RTT Con: Consumes more memory, risk of running out of evictable memory ๏RedisAdapter + TagAwareAdapter: Pro: Uses less memory then RedisTagAwareAdapter + all can be freed Con: 2-RTT ๏MemcachedAdapter + TagAwareAdapter: Pro: Uses less memory due to simpler data structure + all can be freed Cable off handling more traffic Con: 2-RTT
  • 30. Bonus: Simulating RedisTagAware in bash ๏Save: redis-cli set mykey data redis-cli sadd type-article:tags mykey anotherkey ๏Read: redis-cli mget mykey anotherkey ๏Invalidation: tmp=$(cat /dev/urandom | tr -dc 'a-zA-Z0-9' | fold -w 32 | head -n 1) redis-cli rename type-article:tags {type-article:tags}-$tmp members=`redis-cli smembers {type-article:tags}-$tmp` redis-cli del {type-article:tags}-$tmp $members TIP: To run these commands: docker run --name myredis -p 6379:6379 -d redis docker exec -ti myredis bash After “exit”, you can clean up using: docker rm -f myredis
  • 31. Fin.. Questions? Other talks: http://www.slideshare.net/andreromcke Twitter: @andrerom eZ Platform: https://ezplatform.com/ Redis: https://redis.io/ Memcached: https://memcached.org Demo code: https://github.com/andrerom/sfcon-amsterdam-2019-redis-cache-demo