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)

Kafka Tutorial Advanced Kafka Consumers
Kafka Tutorial Advanced Kafka ConsumersKafka Tutorial Advanced Kafka Consumers
Kafka Tutorial Advanced Kafka Consumers
 
Dynomite @ Redis Conference 2016
Dynomite @ Redis Conference 2016Dynomite @ Redis Conference 2016
Dynomite @ Redis Conference 2016
 
Floating on a RAFT: HBase Durability with Apache Ratis
Floating on a RAFT: HBase Durability with Apache RatisFloating on a RAFT: HBase Durability with Apache Ratis
Floating on a RAFT: HBase Durability with Apache Ratis
 
Rancher Simple User Guide
Rancher Simple User GuideRancher Simple User Guide
Rancher Simple User Guide
 
The Azure Cognitive Services on Spark: Clusters with Embedded Intelligent Ser...
The Azure Cognitive Services on Spark: Clusters with Embedded Intelligent Ser...The Azure Cognitive Services on Spark: Clusters with Embedded Intelligent Ser...
The Azure Cognitive Services on Spark: Clusters with Embedded Intelligent Ser...
 
Introduction to Apache ZooKeeper
Introduction to Apache ZooKeeperIntroduction to Apache ZooKeeper
Introduction to Apache ZooKeeper
 
Nginx A High Performance Load Balancer, Web Server & Reverse Proxy
Nginx A High Performance Load Balancer, Web Server & Reverse ProxyNginx A High Performance Load Balancer, Web Server & Reverse Proxy
Nginx A High Performance Load Balancer, Web Server & Reverse Proxy
 
APACHE KAFKA / Kafka Connect / Kafka Streams
APACHE KAFKA / Kafka Connect / Kafka StreamsAPACHE KAFKA / Kafka Connect / Kafka Streams
APACHE KAFKA / Kafka Connect / Kafka Streams
 
Load Balancing and Scaling with NGINX
Load Balancing and Scaling with NGINXLoad Balancing and Scaling with NGINX
Load Balancing and Scaling with NGINX
 
HBase Low Latency
HBase Low LatencyHBase Low Latency
HBase Low Latency
 
Unlocking the Power of Lakehouse Architectures with Apache Pulsar and Apache ...
Unlocking the Power of Lakehouse Architectures with Apache Pulsar and Apache ...Unlocking the Power of Lakehouse Architectures with Apache Pulsar and Apache ...
Unlocking the Power of Lakehouse Architectures with Apache Pulsar and Apache ...
 
Best Practices for Running PostgreSQL on AWS - DAT314 - re:Invent 2017
Best Practices for Running PostgreSQL on AWS - DAT314 - re:Invent 2017Best Practices for Running PostgreSQL on AWS - DAT314 - re:Invent 2017
Best Practices for Running PostgreSQL on AWS - DAT314 - re:Invent 2017
 
HDFS Erasure Coding in Action
HDFS Erasure Coding in Action HDFS Erasure Coding in Action
HDFS Erasure Coding in Action
 
Producer Performance Tuning for Apache Kafka
Producer Performance Tuning for Apache KafkaProducer Performance Tuning for Apache Kafka
Producer Performance Tuning for Apache Kafka
 
Introduction to Kafka Cruise Control
Introduction to Kafka Cruise ControlIntroduction to Kafka Cruise Control
Introduction to Kafka Cruise Control
 
Cassandra at Instagram 2016 (Dikang Gu, Facebook) | Cassandra Summit 2016
Cassandra at Instagram 2016 (Dikang Gu, Facebook) | Cassandra Summit 2016Cassandra at Instagram 2016 (Dikang Gu, Facebook) | Cassandra Summit 2016
Cassandra at Instagram 2016 (Dikang Gu, Facebook) | Cassandra Summit 2016
 
A visual introduction to Apache Kafka
A visual introduction to Apache KafkaA visual introduction to Apache Kafka
A visual introduction to Apache Kafka
 
Tech Talk: RocksDB Slides by Dhruba Borthakur & Haobo Xu of Facebook
Tech Talk: RocksDB Slides by Dhruba Borthakur & Haobo Xu of FacebookTech Talk: RocksDB Slides by Dhruba Borthakur & Haobo Xu of Facebook
Tech Talk: RocksDB Slides by Dhruba Borthakur & Haobo Xu of Facebook
 
Presto: Optimizing Performance of SQL-on-Anything Engine
Presto: Optimizing Performance of SQL-on-Anything EnginePresto: Optimizing Performance of SQL-on-Anything Engine
Presto: Optimizing Performance of SQL-on-Anything Engine
 
Disaster Recovery Options Running Apache Kafka in Kubernetes with Rema Subra...
 Disaster Recovery Options Running Apache Kafka in Kubernetes with Rema Subra... Disaster Recovery Options Running Apache Kafka in Kubernetes with Rema Subra...
Disaster Recovery Options Running Apache Kafka in Kubernetes with Rema Subra...
 

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

Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Victor Rentea
 

Recently uploaded (20)

Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...
 
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a Fresher
 
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
 
Artificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyArtificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : Uncertainty
 
DBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor PresentationDBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor Presentation
 
DEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 AmsterdamDEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
 
WSO2's API Vision: Unifying Control, Empowering Developers
WSO2's API Vision: Unifying Control, Empowering DevelopersWSO2's API Vision: Unifying Control, Empowering Developers
WSO2's API Vision: Unifying Control, Empowering Developers
 
MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024
 
Exploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with MilvusExploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with Milvus
 
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
 
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
 
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingRepurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
 
MS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectorsMS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectors
 
CNIC Information System with Pakdata Cf In Pakistan
CNIC Information System with Pakdata Cf In PakistanCNIC Information System with Pakdata Cf In Pakistan
CNIC Information System with Pakdata Cf In Pakistan
 
AWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of Terraform
 
Corporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptxCorporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptx
 
Introduction to Multilingual Retrieval Augmented Generation (RAG)
Introduction to Multilingual Retrieval Augmented Generation (RAG)Introduction to Multilingual Retrieval Augmented Generation (RAG)
Introduction to Multilingual Retrieval Augmented Generation (RAG)
 
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
 

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