SlideShare uma empresa Scribd logo
1 de 24
Cache is King!
(Or How I Learned To Stop Worrying
and Love the RAM)
Cache is King
• What is Memcaching?
• How Does it Work?
• Setup Overview.
• How To Namespace the Right Way.
• Avoiding Cache Rushing.
• What Should I Cache?
Agenda
Cache is King
• a big ol' hash table
• RAM not disc
• alleviates database (and other io) loads to
speed up load times
• stores data objects as key->value pairs
• open source (BSD license)
• distributed
What is Memcaching?
Cache is King
• A database
• Redundant
• Locking
• A backup
• Highly available
• Limitless in size
• Namespaced (more later)
What Memcaching is NOT?
Cache is King
• 2 hashes
• client hashes key against server list to find
server
• client then sends request to server
• server does hash key lookup against slabs of
keys
• Serve returns object
How Does it Work?
Cache is King
• When setting a value you can avoid the 250
byte limit imposed for keys by md5-hashing
them.
• If your max page size is 1MB are you limited to
1 MB size chunks? Kinda – but there is
compression available.
• You can increase or decrease page size and/or
growth factor, but there is a performance hit.
Storage
Cache is King
• Default minimum chunk size is 48 bytes
• Default growth factor is 1.25
• 48 bytes required for storage overhead
• Each slab is a 1mb page containing same size
chunks
• Non-contiguous – there is space wasted
Chunks and Slabs and Growth Factors
Cache is King
• Need to store a 1001 byte piece (953 + 48).
• Multiply by growth factor until chunk size is
greater than 1001 bytes
88 x 1.25^11 = 1025
• Look for the slab of 1025 byte pieces.
• Create a new slab if it does not exist
• Store the value in a chunk (note 24 bytes wasted)
• 250 byte limit to key (so use md5 to set and get)
Example
Cache is King
• There is no room left for our 1025-byte chunk
AND we have initialized enough slabs already
to fill the memcached space – what now?
• LRU (least recently used) within 1025b slabs
• LRU is not global.
• Evict the LRU 1025-byte chunk
Eviction
Cache is King
• Memcached is not language specific
• Memcached runs as a service on the OS
• PHP has a library to connect to it
• Grab an API (or write your own) to wrap the
functionality in PHP for your needs.
In Practice
Cache is King
get
add
replace
delete
What functions do I need to wrap?
Cache is King
•NOT natively supported
•BUT completely do-able
Namespaces
Cache is King
• Do not store an array of keys as a
representation of a namespace.
• Does not scale well
• You MUST iterate through all in order
to expire namespace
Namespaces the Wrong Way
Cache is King
• Requires at least 1 additional round trip to
the hash table (using namespace, key and
value)
– store a key->value pair of namespace and key
– then store a key->value pair of key and value
• Assign an ID for a namespace (or retrieve
the existing one if it already exists)
Namespaces the Right Way
Cache is King
• Setting involves:
– Get namespace->id (generate and set with no expire if
new namespace)
– Set key->id (no expire)
– then set the key->value (with expire)
• Getting involves:
– Get id by namespace (namespace->id)
– if not exists then “miss”
– If success then get the key->id
– key->value (may still “miss”)
Namespaces the Right Way
Cache is King
• Deleting (expiring) involves:
– “increment” value of namespace->id
– Since we have stored the data as COMPRESSED
rather than INT it will invalidate this chunk
– Now simply trying to get something by key and
namespace will “miss” because the first get for
namespace fails
– Note the subsequent key->value pairs are not
deleted – they merely become inaccessible, will
turn LRU and eventually get evicted.
Namespaces the Right Way
Cache is King
• 2 process (A and B) want the same thing that is expired
• A "misses" so it goes off to get it from the database
• B then "misses" so it also goes off to get it (A isn't done)
• A and B are both hitting the DB for the same thing
• A and B both intend to "replace" to cache when they return
• If you are doing millions of page hits a day = big troubles!
• NOT optimal! - indeed can be a bottleneck on common
and/or expensive values
Cache Rush
Cache is King
• Store your value as an array or object with a "real" expire
included, then cache with extra time added on.
• The item will be retrieved regardless 'cuz you stored it with
extra time
• A can add time to the internal expiry and do a cache
replace before going to process data
• B checks cache - hey it's not expired (‘cuz A added time!)
• A comes back and does another replace with
– new data
– new internal expiry
– new cache expiry
Cache Rush Solution
Cache is King
• start with low-hanging fruit
– Big Static Html pages
– objects that change seldom (long expiry dates –
more likely to update before expired)
– objects that change more often (careful with
expiration dates now – much more important)
What Should I Cache?
Cache is King
• Now the big stuff
– dynamic html (i.e. with user content) cached as
static with placeholders for dynamic content
– Static html fragments cached short term for the
dynamic content
– finally - user specific data that is expensive, but
used often (store as fragments or objects then
replace placeholders in cached html)
What Should I Cache?
Cache is King
• David Engel
• davidengel.dev@gmail.com
• http://winnipegphp.com
• http://www.meetup.com/Winnipeg-PHP/
• http://www.linkedin.com/groups/PHP-
Winnipeg-3874131
Closing
Cache is King
# yum install memcached
# chkconfig memcached on
# /etc/init.d/memcached start
OR
# service memcached start
# setenforce 0
# setsebool -P httpd_can_network_memcache 1
# setenforce 1
CentOS Notes
Cache is King
# yum install php-pecl-memcache
# vi /etc/sysconfig/memcached
PORT="11211“
USER="memcached“
MAXCONN="1024“
CACHESIZE="512“
OPTIONS=""
CentOS Notes
Cache is King
# pkg_add -i memcached-1.4.13
# pkg_add -i pecl-memcache-3.0.6p1
# ln -sf /etc/php-5.3.sample/memcache.ini 
/etc/php-5.3/memcache.ini
# vi /etc/rc.local
# Start memcached
if [ -x /usr/local/bin/memcached ]; then
echo -n ' memcached'
/usr/local/bin/memcached -m 1024M -d -u _memcached –P /var/run/memcached.pid
fi
OpenBSD Notes

Mais conteúdo relacionado

Mais procurados

Денис Резник "Моя база данных не справляется с нагрузкой. Что делать?"
Денис Резник "Моя база данных не справляется с нагрузкой. Что делать?"Денис Резник "Моя база данных не справляется с нагрузкой. Что делать?"
Денис Резник "Моя база данных не справляется с нагрузкой. Что делать?"Fwdays
 
Postgres & Redis Sitting in a Tree- Rimas Silkaitis, Heroku
Postgres & Redis Sitting in a Tree- Rimas Silkaitis, HerokuPostgres & Redis Sitting in a Tree- Rimas Silkaitis, Heroku
Postgres & Redis Sitting in a Tree- Rimas Silkaitis, HerokuRedis Labs
 
Ruby and Distributed Storage Systems
Ruby and Distributed Storage SystemsRuby and Distributed Storage Systems
Ruby and Distributed Storage SystemsSATOSHI TAGOMORI
 
The OSSCube MySQL High Availability Tutorial
The OSSCube MySQL High Availability TutorialThe OSSCube MySQL High Availability Tutorial
The OSSCube MySQL High Availability TutorialOSSCube
 
Hadoop Meetup Jan 2019 - TonY: TensorFlow on YARN and Beyond
Hadoop Meetup Jan 2019 - TonY: TensorFlow on YARN and BeyondHadoop Meetup Jan 2019 - TonY: TensorFlow on YARN and Beyond
Hadoop Meetup Jan 2019 - TonY: TensorFlow on YARN and BeyondErik Krogen
 
Reverse proxy & web cache with NGINX, HAProxy and Varnish
Reverse proxy & web cache with NGINX, HAProxy and VarnishReverse proxy & web cache with NGINX, HAProxy and Varnish
Reverse proxy & web cache with NGINX, HAProxy and VarnishEl Mahdi Benzekri
 
JavaOne2016 - Microservices: Terabytes in Microseconds [CON4516]
JavaOne2016 - Microservices: Terabytes in Microseconds [CON4516]JavaOne2016 - Microservices: Terabytes in Microseconds [CON4516]
JavaOne2016 - Microservices: Terabytes in Microseconds [CON4516]Malin Weiss
 
NoSQL Infrastructure - Late 2013
NoSQL Infrastructure - Late 2013NoSQL Infrastructure - Late 2013
NoSQL Infrastructure - Late 2013Server Density
 
Introduction to Redis
Introduction to RedisIntroduction to Redis
Introduction to RedisArnab Mitra
 
NGINX High-performance Caching
NGINX High-performance CachingNGINX High-performance Caching
NGINX High-performance CachingNGINX, Inc.
 
Introduction to memcached
Introduction to memcachedIntroduction to memcached
Introduction to memcachedJurriaan Persyn
 
Hadoop Meetup Jan 2019 - Dynamometer and a Case Study in NameNode GC
Hadoop Meetup Jan 2019 - Dynamometer and a Case Study in NameNode GCHadoop Meetup Jan 2019 - Dynamometer and a Case Study in NameNode GC
Hadoop Meetup Jan 2019 - Dynamometer and a Case Study in NameNode GCErik Krogen
 
Mongodb - Scaling write performance
Mongodb - Scaling write performanceMongodb - Scaling write performance
Mongodb - Scaling write performanceDaum DNA
 
How to migrate your existing MongoDB and Cassandra Apps to Azure Cosmos DB
How to migrate your existing MongoDB and Cassandra Apps to Azure Cosmos DBHow to migrate your existing MongoDB and Cassandra Apps to Azure Cosmos DB
How to migrate your existing MongoDB and Cassandra Apps to Azure Cosmos DBMicrosoft Tech Community
 
Cassandra vs. Redis
Cassandra vs. RedisCassandra vs. Redis
Cassandra vs. RedisTim Lossen
 
Background Tasks in Node - Evan Tahler, TaskRabbit
Background Tasks in Node - Evan Tahler, TaskRabbitBackground Tasks in Node - Evan Tahler, TaskRabbit
Background Tasks in Node - Evan Tahler, TaskRabbitRedis Labs
 
Understanding and tuning WiredTiger, the new high performance database engine...
Understanding and tuning WiredTiger, the new high performance database engine...Understanding and tuning WiredTiger, the new high performance database engine...
Understanding and tuning WiredTiger, the new high performance database engine...Ontico
 
Efficient cluster resource management by using Cook and Mesos / Li Jin (Two S...
Efficient cluster resource management by using Cook and Mesos / Li Jin (Two S...Efficient cluster resource management by using Cook and Mesos / Li Jin (Two S...
Efficient cluster resource management by using Cook and Mesos / Li Jin (Two S...Ontico
 

Mais procurados (20)

Денис Резник "Моя база данных не справляется с нагрузкой. Что делать?"
Денис Резник "Моя база данных не справляется с нагрузкой. Что делать?"Денис Резник "Моя база данных не справляется с нагрузкой. Что делать?"
Денис Резник "Моя база данных не справляется с нагрузкой. Что делать?"
 
Postgres & Redis Sitting in a Tree- Rimas Silkaitis, Heroku
Postgres & Redis Sitting in a Tree- Rimas Silkaitis, HerokuPostgres & Redis Sitting in a Tree- Rimas Silkaitis, Heroku
Postgres & Redis Sitting in a Tree- Rimas Silkaitis, Heroku
 
Redis and it's data types
Redis and it's data typesRedis and it's data types
Redis and it's data types
 
Ruby and Distributed Storage Systems
Ruby and Distributed Storage SystemsRuby and Distributed Storage Systems
Ruby and Distributed Storage Systems
 
The OSSCube MySQL High Availability Tutorial
The OSSCube MySQL High Availability TutorialThe OSSCube MySQL High Availability Tutorial
The OSSCube MySQL High Availability Tutorial
 
Hadoop Meetup Jan 2019 - TonY: TensorFlow on YARN and Beyond
Hadoop Meetup Jan 2019 - TonY: TensorFlow on YARN and BeyondHadoop Meetup Jan 2019 - TonY: TensorFlow on YARN and Beyond
Hadoop Meetup Jan 2019 - TonY: TensorFlow on YARN and Beyond
 
Reverse proxy & web cache with NGINX, HAProxy and Varnish
Reverse proxy & web cache with NGINX, HAProxy and VarnishReverse proxy & web cache with NGINX, HAProxy and Varnish
Reverse proxy & web cache with NGINX, HAProxy and Varnish
 
JavaOne2016 - Microservices: Terabytes in Microseconds [CON4516]
JavaOne2016 - Microservices: Terabytes in Microseconds [CON4516]JavaOne2016 - Microservices: Terabytes in Microseconds [CON4516]
JavaOne2016 - Microservices: Terabytes in Microseconds [CON4516]
 
NoSQL Infrastructure - Late 2013
NoSQL Infrastructure - Late 2013NoSQL Infrastructure - Late 2013
NoSQL Infrastructure - Late 2013
 
MongoDB Sharding Fundamentals
MongoDB Sharding Fundamentals MongoDB Sharding Fundamentals
MongoDB Sharding Fundamentals
 
Introduction to Redis
Introduction to RedisIntroduction to Redis
Introduction to Redis
 
NGINX High-performance Caching
NGINX High-performance CachingNGINX High-performance Caching
NGINX High-performance Caching
 
Introduction to memcached
Introduction to memcachedIntroduction to memcached
Introduction to memcached
 
Hadoop Meetup Jan 2019 - Dynamometer and a Case Study in NameNode GC
Hadoop Meetup Jan 2019 - Dynamometer and a Case Study in NameNode GCHadoop Meetup Jan 2019 - Dynamometer and a Case Study in NameNode GC
Hadoop Meetup Jan 2019 - Dynamometer and a Case Study in NameNode GC
 
Mongodb - Scaling write performance
Mongodb - Scaling write performanceMongodb - Scaling write performance
Mongodb - Scaling write performance
 
How to migrate your existing MongoDB and Cassandra Apps to Azure Cosmos DB
How to migrate your existing MongoDB and Cassandra Apps to Azure Cosmos DBHow to migrate your existing MongoDB and Cassandra Apps to Azure Cosmos DB
How to migrate your existing MongoDB and Cassandra Apps to Azure Cosmos DB
 
Cassandra vs. Redis
Cassandra vs. RedisCassandra vs. Redis
Cassandra vs. Redis
 
Background Tasks in Node - Evan Tahler, TaskRabbit
Background Tasks in Node - Evan Tahler, TaskRabbitBackground Tasks in Node - Evan Tahler, TaskRabbit
Background Tasks in Node - Evan Tahler, TaskRabbit
 
Understanding and tuning WiredTiger, the new high performance database engine...
Understanding and tuning WiredTiger, the new high performance database engine...Understanding and tuning WiredTiger, the new high performance database engine...
Understanding and tuning WiredTiger, the new high performance database engine...
 
Efficient cluster resource management by using Cook and Mesos / Li Jin (Two S...
Efficient cluster resource management by using Cook and Mesos / Li Jin (Two S...Efficient cluster resource management by using Cook and Mesos / Li Jin (Two S...
Efficient cluster resource management by using Cook and Mesos / Li Jin (Two S...
 

Destaque

PHP7 - Scalar Type Hints & Return Types
PHP7 - Scalar Type Hints & Return TypesPHP7 - Scalar Type Hints & Return Types
PHP7 - Scalar Type Hints & Return TypesEric Poe
 
Php 5.4: New Language Features You Will Find Useful
Php 5.4: New Language Features You Will Find UsefulPhp 5.4: New Language Features You Will Find Useful
Php 5.4: New Language Features You Will Find UsefulDavid Engel
 
Last Month in PHP - December 2015
Last Month in PHP - December 2015Last Month in PHP - December 2015
Last Month in PHP - December 2015Eric Poe
 
Harder, Better, Faster, Stronger
Harder, Better, Faster, StrongerHarder, Better, Faster, Stronger
Harder, Better, Faster, StrongerDavid Engel
 

Destaque (6)

PHP7 - Scalar Type Hints & Return Types
PHP7 - Scalar Type Hints & Return TypesPHP7 - Scalar Type Hints & Return Types
PHP7 - Scalar Type Hints & Return Types
 
Php 5.4: New Language Features You Will Find Useful
Php 5.4: New Language Features You Will Find UsefulPhp 5.4: New Language Features You Will Find Useful
Php 5.4: New Language Features You Will Find Useful
 
Key features PHP 5.3 - 5.6
Key features PHP 5.3 - 5.6Key features PHP 5.3 - 5.6
Key features PHP 5.3 - 5.6
 
Last Month in PHP - December 2015
Last Month in PHP - December 2015Last Month in PHP - December 2015
Last Month in PHP - December 2015
 
Harder, Better, Faster, Stronger
Harder, Better, Faster, StrongerHarder, Better, Faster, Stronger
Harder, Better, Faster, Stronger
 
Composer
ComposerComposer
Composer
 

Semelhante a Cache is King!

A Case Study of NoSQL Adoption: What Drove Wordnik Non-Relational?
A Case Study of NoSQL Adoption: What Drove Wordnik Non-Relational?A Case Study of NoSQL Adoption: What Drove Wordnik Non-Relational?
A Case Study of NoSQL Adoption: What Drove Wordnik Non-Relational?DATAVERSITY
 
Memcached Code Camp 2009
Memcached Code Camp 2009Memcached Code Camp 2009
Memcached Code Camp 2009NorthScale
 
JavaOne2016 - Microservices: Terabytes in Microseconds [CON4516]
JavaOne2016 - Microservices: Terabytes in Microseconds [CON4516]JavaOne2016 - Microservices: Terabytes in Microseconds [CON4516]
JavaOne2016 - Microservices: Terabytes in Microseconds [CON4516]Speedment, Inc.
 
SQL Server 2014 In-Memory OLTP
SQL Server 2014 In-Memory OLTPSQL Server 2014 In-Memory OLTP
SQL Server 2014 In-Memory OLTPTony Rogerson
 
What Every Developer Should Know About Database Scalability
What Every Developer Should Know About Database ScalabilityWhat Every Developer Should Know About Database Scalability
What Every Developer Should Know About Database Scalabilityjbellis
 
[B5]memcached scalability-bag lru-deview-100
[B5]memcached scalability-bag lru-deview-100[B5]memcached scalability-bag lru-deview-100
[B5]memcached scalability-bag lru-deview-100NAVER D2
 
Where Django Caching Bust at the Seams
Where Django Caching Bust at the SeamsWhere Django Caching Bust at the Seams
Where Django Caching Bust at the SeamsConcentric Sky
 
HBase: Extreme Makeover
HBase: Extreme MakeoverHBase: Extreme Makeover
HBase: Extreme MakeoverHBaseCon
 
Responding rapidly when you have 100+ GB data sets in Java
Responding rapidly when you have 100+ GB data sets in JavaResponding rapidly when you have 100+ GB data sets in Java
Responding rapidly when you have 100+ GB data sets in JavaPeter Lawrey
 
Caching: A Guided Tour - 10/12/2010
Caching: A Guided Tour - 10/12/2010Caching: A Guided Tour - 10/12/2010
Caching: A Guided Tour - 10/12/2010Jason Ragsdale
 
Large-scale Web Apps @ Pinterest
Large-scale Web Apps @ PinterestLarge-scale Web Apps @ Pinterest
Large-scale Web Apps @ PinterestHBaseCon
 
Scala at foursquare
Scala at foursquareScala at foursquare
Scala at foursquarejorgeortiz85
 
Your backend architecture is what matters slideshare
Your backend architecture is what matters slideshareYour backend architecture is what matters slideshare
Your backend architecture is what matters slideshareColin Charles
 
High-Performance Storage Services with HailDB and Java
High-Performance Storage Services with HailDB and JavaHigh-Performance Storage Services with HailDB and Java
High-Performance Storage Services with HailDB and Javasunnygleason
 
Scaling with sync_replication using Galera and EC2
Scaling with sync_replication using Galera and EC2Scaling with sync_replication using Galera and EC2
Scaling with sync_replication using Galera and EC2Marco Tusa
 
WebObjects Optimization
WebObjects OptimizationWebObjects Optimization
WebObjects OptimizationWO Community
 
SQL Server 2014 Memory Optimised Tables - Advanced
SQL Server 2014 Memory Optimised Tables - AdvancedSQL Server 2014 Memory Optimised Tables - Advanced
SQL Server 2014 Memory Optimised Tables - AdvancedTony Rogerson
 

Semelhante a Cache is King! (20)

A Case Study of NoSQL Adoption: What Drove Wordnik Non-Relational?
A Case Study of NoSQL Adoption: What Drove Wordnik Non-Relational?A Case Study of NoSQL Adoption: What Drove Wordnik Non-Relational?
A Case Study of NoSQL Adoption: What Drove Wordnik Non-Relational?
 
Java Memory Analysis: Problems and Solutions
Java Memory Analysis: Problems and SolutionsJava Memory Analysis: Problems and Solutions
Java Memory Analysis: Problems and Solutions
 
L6.sp17.pptx
L6.sp17.pptxL6.sp17.pptx
L6.sp17.pptx
 
Memcached Code Camp 2009
Memcached Code Camp 2009Memcached Code Camp 2009
Memcached Code Camp 2009
 
JavaOne2016 - Microservices: Terabytes in Microseconds [CON4516]
JavaOne2016 - Microservices: Terabytes in Microseconds [CON4516]JavaOne2016 - Microservices: Terabytes in Microseconds [CON4516]
JavaOne2016 - Microservices: Terabytes in Microseconds [CON4516]
 
SQL Server 2014 In-Memory OLTP
SQL Server 2014 In-Memory OLTPSQL Server 2014 In-Memory OLTP
SQL Server 2014 In-Memory OLTP
 
What Every Developer Should Know About Database Scalability
What Every Developer Should Know About Database ScalabilityWhat Every Developer Should Know About Database Scalability
What Every Developer Should Know About Database Scalability
 
Hbase Nosql
Hbase NosqlHbase Nosql
Hbase Nosql
 
[B5]memcached scalability-bag lru-deview-100
[B5]memcached scalability-bag lru-deview-100[B5]memcached scalability-bag lru-deview-100
[B5]memcached scalability-bag lru-deview-100
 
Where Django Caching Bust at the Seams
Where Django Caching Bust at the SeamsWhere Django Caching Bust at the Seams
Where Django Caching Bust at the Seams
 
HBase: Extreme Makeover
HBase: Extreme MakeoverHBase: Extreme Makeover
HBase: Extreme Makeover
 
Responding rapidly when you have 100+ GB data sets in Java
Responding rapidly when you have 100+ GB data sets in JavaResponding rapidly when you have 100+ GB data sets in Java
Responding rapidly when you have 100+ GB data sets in Java
 
Caching: A Guided Tour - 10/12/2010
Caching: A Guided Tour - 10/12/2010Caching: A Guided Tour - 10/12/2010
Caching: A Guided Tour - 10/12/2010
 
Large-scale Web Apps @ Pinterest
Large-scale Web Apps @ PinterestLarge-scale Web Apps @ Pinterest
Large-scale Web Apps @ Pinterest
 
Scala at foursquare
Scala at foursquareScala at foursquare
Scala at foursquare
 
Your backend architecture is what matters slideshare
Your backend architecture is what matters slideshareYour backend architecture is what matters slideshare
Your backend architecture is what matters slideshare
 
High-Performance Storage Services with HailDB and Java
High-Performance Storage Services with HailDB and JavaHigh-Performance Storage Services with HailDB and Java
High-Performance Storage Services with HailDB and Java
 
Scaling with sync_replication using Galera and EC2
Scaling with sync_replication using Galera and EC2Scaling with sync_replication using Galera and EC2
Scaling with sync_replication using Galera and EC2
 
WebObjects Optimization
WebObjects OptimizationWebObjects Optimization
WebObjects Optimization
 
SQL Server 2014 Memory Optimised Tables - Advanced
SQL Server 2014 Memory Optimised Tables - AdvancedSQL Server 2014 Memory Optimised Tables - Advanced
SQL Server 2014 Memory Optimised Tables - Advanced
 

Último

Factors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxFactors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxKatpro Technologies
 
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 MenDelhi Call girls
 
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfThe Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfEnterprise Knowledge
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slidevu2urc
 
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure serviceWhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure servicePooja Nehwal
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityPrincipled Technologies
 
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Igalia
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...apidays
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Drew Madelung
 
Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Enterprise Knowledge
 
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...Neo4j
 
Slack Application Development 101 Slides
Slack Application Development 101 SlidesSlack Application Development 101 Slides
Slack Application Development 101 Slidespraypatel2
 
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 SolutionsEnterprise Knowledge
 
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...gurkirankumar98700
 
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 Processorsdebabhi2
 
A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024Results
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationMichael W. Hawkins
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024The Digital Insurer
 
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEarley Information Science
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking MenDelhi Call girls
 

Último (20)

Factors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxFactors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
 
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
 
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfThe Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slide
 
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure serviceWhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivity
 
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
 
Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...
 
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
 
Slack Application Development 101 Slides
Slack Application Development 101 SlidesSlack Application Development 101 Slides
Slack Application Development 101 Slides
 
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
 
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...
 
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
 
A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day Presentation
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024
 
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
 

Cache is King!

  • 1. Cache is King! (Or How I Learned To Stop Worrying and Love the RAM)
  • 2. Cache is King • What is Memcaching? • How Does it Work? • Setup Overview. • How To Namespace the Right Way. • Avoiding Cache Rushing. • What Should I Cache? Agenda
  • 3. Cache is King • a big ol' hash table • RAM not disc • alleviates database (and other io) loads to speed up load times • stores data objects as key->value pairs • open source (BSD license) • distributed What is Memcaching?
  • 4. Cache is King • A database • Redundant • Locking • A backup • Highly available • Limitless in size • Namespaced (more later) What Memcaching is NOT?
  • 5. Cache is King • 2 hashes • client hashes key against server list to find server • client then sends request to server • server does hash key lookup against slabs of keys • Serve returns object How Does it Work?
  • 6. Cache is King • When setting a value you can avoid the 250 byte limit imposed for keys by md5-hashing them. • If your max page size is 1MB are you limited to 1 MB size chunks? Kinda – but there is compression available. • You can increase or decrease page size and/or growth factor, but there is a performance hit. Storage
  • 7. Cache is King • Default minimum chunk size is 48 bytes • Default growth factor is 1.25 • 48 bytes required for storage overhead • Each slab is a 1mb page containing same size chunks • Non-contiguous – there is space wasted Chunks and Slabs and Growth Factors
  • 8. Cache is King • Need to store a 1001 byte piece (953 + 48). • Multiply by growth factor until chunk size is greater than 1001 bytes 88 x 1.25^11 = 1025 • Look for the slab of 1025 byte pieces. • Create a new slab if it does not exist • Store the value in a chunk (note 24 bytes wasted) • 250 byte limit to key (so use md5 to set and get) Example
  • 9. Cache is King • There is no room left for our 1025-byte chunk AND we have initialized enough slabs already to fill the memcached space – what now? • LRU (least recently used) within 1025b slabs • LRU is not global. • Evict the LRU 1025-byte chunk Eviction
  • 10. Cache is King • Memcached is not language specific • Memcached runs as a service on the OS • PHP has a library to connect to it • Grab an API (or write your own) to wrap the functionality in PHP for your needs. In Practice
  • 12. Cache is King •NOT natively supported •BUT completely do-able Namespaces
  • 13. Cache is King • Do not store an array of keys as a representation of a namespace. • Does not scale well • You MUST iterate through all in order to expire namespace Namespaces the Wrong Way
  • 14. Cache is King • Requires at least 1 additional round trip to the hash table (using namespace, key and value) – store a key->value pair of namespace and key – then store a key->value pair of key and value • Assign an ID for a namespace (or retrieve the existing one if it already exists) Namespaces the Right Way
  • 15. Cache is King • Setting involves: – Get namespace->id (generate and set with no expire if new namespace) – Set key->id (no expire) – then set the key->value (with expire) • Getting involves: – Get id by namespace (namespace->id) – if not exists then “miss” – If success then get the key->id – key->value (may still “miss”) Namespaces the Right Way
  • 16. Cache is King • Deleting (expiring) involves: – “increment” value of namespace->id – Since we have stored the data as COMPRESSED rather than INT it will invalidate this chunk – Now simply trying to get something by key and namespace will “miss” because the first get for namespace fails – Note the subsequent key->value pairs are not deleted – they merely become inaccessible, will turn LRU and eventually get evicted. Namespaces the Right Way
  • 17. Cache is King • 2 process (A and B) want the same thing that is expired • A "misses" so it goes off to get it from the database • B then "misses" so it also goes off to get it (A isn't done) • A and B are both hitting the DB for the same thing • A and B both intend to "replace" to cache when they return • If you are doing millions of page hits a day = big troubles! • NOT optimal! - indeed can be a bottleneck on common and/or expensive values Cache Rush
  • 18. Cache is King • Store your value as an array or object with a "real" expire included, then cache with extra time added on. • The item will be retrieved regardless 'cuz you stored it with extra time • A can add time to the internal expiry and do a cache replace before going to process data • B checks cache - hey it's not expired (‘cuz A added time!) • A comes back and does another replace with – new data – new internal expiry – new cache expiry Cache Rush Solution
  • 19. Cache is King • start with low-hanging fruit – Big Static Html pages – objects that change seldom (long expiry dates – more likely to update before expired) – objects that change more often (careful with expiration dates now – much more important) What Should I Cache?
  • 20. Cache is King • Now the big stuff – dynamic html (i.e. with user content) cached as static with placeholders for dynamic content – Static html fragments cached short term for the dynamic content – finally - user specific data that is expensive, but used often (store as fragments or objects then replace placeholders in cached html) What Should I Cache?
  • 21. Cache is King • David Engel • davidengel.dev@gmail.com • http://winnipegphp.com • http://www.meetup.com/Winnipeg-PHP/ • http://www.linkedin.com/groups/PHP- Winnipeg-3874131 Closing
  • 22. Cache is King # yum install memcached # chkconfig memcached on # /etc/init.d/memcached start OR # service memcached start # setenforce 0 # setsebool -P httpd_can_network_memcache 1 # setenforce 1 CentOS Notes
  • 23. Cache is King # yum install php-pecl-memcache # vi /etc/sysconfig/memcached PORT="11211“ USER="memcached“ MAXCONN="1024“ CACHESIZE="512“ OPTIONS="" CentOS Notes
  • 24. Cache is King # pkg_add -i memcached-1.4.13 # pkg_add -i pecl-memcache-3.0.6p1 # ln -sf /etc/php-5.3.sample/memcache.ini /etc/php-5.3/memcache.ini # vi /etc/rc.local # Start memcached if [ -x /usr/local/bin/memcached ]; then echo -n ' memcached' /usr/local/bin/memcached -m 1024M -d -u _memcached –P /var/run/memcached.pid fi OpenBSD Notes