SlideShare una empresa de Scribd logo
1 de 31
Descargar para leer sin conexión
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

Más contenido relacionado

La actualidad más candente

How to use flash drives with Apache Hadoop 3.x: Real world use cases and proo...
How to use flash drives with Apache Hadoop 3.x: Real world use cases and proo...How to use flash drives with Apache Hadoop 3.x: Real world use cases and proo...
How to use flash drives with Apache Hadoop 3.x: Real world use cases and proo...
DataWorks Summit
 

La actualidad más candente (20)

Redis vs Infinispan | DevNation Tech Talk
Redis vs Infinispan | DevNation Tech TalkRedis vs Infinispan | DevNation Tech Talk
Redis vs Infinispan | DevNation Tech Talk
 
Dynomite @ Redis Conference 2016
Dynomite @ Redis Conference 2016Dynomite @ Redis Conference 2016
Dynomite @ Redis Conference 2016
 
Pegasus In Depth (2018/10)
Pegasus In Depth (2018/10)Pegasus In Depth (2018/10)
Pegasus In Depth (2018/10)
 
The Art of Java Type Patterns
The Art of Java Type PatternsThe Art of Java Type Patterns
The Art of Java Type Patterns
 
Percona server for MySQL 제품 소개
Percona server for MySQL 제품 소개Percona server for MySQL 제품 소개
Percona server for MySQL 제품 소개
 
Kafka on ZFS: Better Living Through Filesystems
Kafka on ZFS: Better Living Through Filesystems Kafka on ZFS: Better Living Through Filesystems
Kafka on ZFS: Better Living Through Filesystems
 
Performance Profiling in Rust
Performance Profiling in RustPerformance Profiling in Rust
Performance Profiling in Rust
 
Infrastructure at Scale: Apache Kafka, Twitter Storm & Elastic Search (ARC303...
Infrastructure at Scale: Apache Kafka, Twitter Storm & Elastic Search (ARC303...Infrastructure at Scale: Apache Kafka, Twitter Storm & Elastic Search (ARC303...
Infrastructure at Scale: Apache Kafka, Twitter Storm & Elastic Search (ARC303...
 
Helm 3
Helm 3Helm 3
Helm 3
 
Kubernetes #6 advanced scheduling
Kubernetes #6   advanced schedulingKubernetes #6   advanced scheduling
Kubernetes #6 advanced scheduling
 
Kubernetes
KubernetesKubernetes
Kubernetes
 
End-to-end Streaming Between gRPC Services Via Kafka with John Fallows
End-to-end Streaming Between gRPC Services Via Kafka with John FallowsEnd-to-end Streaming Between gRPC Services Via Kafka with John Fallows
End-to-end Streaming Between gRPC Services Via Kafka with John Fallows
 
Building and running cloud native cassandra
Building and running cloud native cassandraBuilding and running cloud native cassandra
Building and running cloud native cassandra
 
Redis cluster
Redis clusterRedis cluster
Redis cluster
 
Anatomy of a Container: Namespaces, cgroups & Some Filesystem Magic - LinuxCon
Anatomy of a Container: Namespaces, cgroups & Some Filesystem Magic - LinuxConAnatomy of a Container: Namespaces, cgroups & Some Filesystem Magic - LinuxCon
Anatomy of a Container: Namespaces, cgroups & Some Filesystem Magic - LinuxCon
 
An intro to Kubernetes operators
An intro to Kubernetes operatorsAn intro to Kubernetes operators
An intro to Kubernetes operators
 
How to use flash drives with Apache Hadoop 3.x: Real world use cases and proo...
How to use flash drives with Apache Hadoop 3.x: Real world use cases and proo...How to use flash drives with Apache Hadoop 3.x: Real world use cases and proo...
How to use flash drives with Apache Hadoop 3.x: Real world use cases and proo...
 
Kubernetes and service mesh application
Kubernetes  and service mesh applicationKubernetes  and service mesh application
Kubernetes and service mesh application
 
Docker 101 - Nov 2016
Docker 101 - Nov 2016Docker 101 - Nov 2016
Docker 101 - Nov 2016
 
HBase HUG Presentation: Avoiding Full GCs with MemStore-Local Allocation Buffers
HBase HUG Presentation: Avoiding Full GCs with MemStore-Local Allocation BuffersHBase HUG Presentation: Avoiding Full GCs with MemStore-Local Allocation Buffers
HBase HUG Presentation: Avoiding Full GCs with MemStore-Local Allocation Buffers
 

Similar a 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 a 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
 

Más de 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
 

Más de 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
 

Último

CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Service
giselly40
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI Solutions
Enterprise Knowledge
 

Último (20)

Tech Trends Report 2024 Future Today Institute.pdf
Tech Trends Report 2024 Future Today Institute.pdfTech Trends Report 2024 Future Today Institute.pdf
Tech Trends Report 2024 Future Today Institute.pdf
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf
 
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
 
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
 
GenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdfGenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdf
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdf
 
Evaluating the top large language models.pdf
Evaluating the top large language models.pdfEvaluating the top large language models.pdf
Evaluating the top large language models.pdf
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreter
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonets
 
CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Service
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed texts
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day Presentation
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organization
 
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
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI Solutions
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processors
 
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
 

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