SlideShare ist ein Scribd-Unternehmen logo
1 von 47
Downloaden Sie, um offline zu lesen
Caching with
Memcached & APC
                Ben Ramsey
        TEK·X • May 21, 2010
Hi, I’m Ben.
benramsey.com
@ramsey
joind.in/1599
What is a cache?
“A cache is a collection of data
duplicating original values stored
elsewhere or computed earlier, where
the original data is expensive to fetch
(owing to longer access time) or to
compute, compared to the cost of
reading the cache.”
                            –Wikipedia
“A cache is a temporary storage area
where frequently accessed data can
be stored for rapid access.”
Why use a cache?
• To reduce the number or retrieval queries
  made to a database
• To reduce the number of requests made
  to external services
• To reduce the time spent computing data
• To reduce filesystem access
Types of caches
• File system
• Database
• Shared memory
• RAM disk
• Object cache (memcached and APC)
• Opcode cache (APC)
Memcached
What is memcached?

   • Distributed memory object caching
   • Acts as a simple key/value dictionary
   • Runs as a daemon
   • Has a simple protocol for client access
     over TCP and UDP
   • Can be run in a pool, but individual
     daemons are not aware of the pool
   • Clients/applications manage the pool
   • Not an opcode cache
Who uses memcached?


   • Facebook
   • Digg
   • Youtube
   • Wikipedia
   • Us (Moontoast)
   • Many others...
Memcached principles



   • Fast asynchronous network I/O
   • Not a persistent data store
   • It does not provide redundancy
   • Data is not replicated across the cluster
   • It doesn’t handle failover
Memcached principles


   • Daemons are not aware of each other
   • It does not provide authentication
   • Works great on a small and local-area
     network
   • A single value cannot contain more than
     1MB of data
   • Keys are strings limited to 250 characters
Basic concepts and usage

   1. Set up a pool of memcached servers
   2. Assign values to keys that are stored in
      the cluster
   3. The client hashes the key to a particular
      machine in the cluster
   4. Subsequent requests for that key retrieve
      the value from the memcached server on
      which it was stored
   5. Values time out after the specified TTL
memcached


www

                      www

              memcached




memcached

        www
memcached


www

                      www

              memcached




memcached

        www
A very simple protocol


   • Storage commands:
     set, add, replace, append, prepend, cas

   • Retrieval command: get, gets
   • Deletion command: delete
   • Increment/decrement: incr, decr
   • Other commands:
     stats, flush_all, version, verbosity,
     quit
$> telnet localhost 11211
Trying ::1...
Connected to localhost.
Escape character is '^]'.
set foobar 0 0 15
This is a test.
STORED
get foobar
VALUE foobar 0 15
This is a test.
END
quit
Connection closed by foreign host.
$>
Let’s see that with
some code.
$memcache = new Memcached();
$memcache->addServers(array(
    array('10.35.24.1', '11211'),
    array('10.35.24.2', '11211'),
    array('10.35.24.3', '11211'),
));
$book = $memcache->get('0764596349');

if ($book === false)
{
  if ($memcache->getResultCode()
      == Memcached::RES_NOTFOUND)
  {
    $book = Book::getByIsbn('0764596349');
    $memcache->set($book->getCacheKey(), $book);
  }
}
Memcached limits



   • Key size has a 250 byte limit
   • Value can not be larger than 1 MB
   • Memory limits for 32bit/64bit systems
   • Replication not built-in; dependent on the
     client
pecl/memcached
pecl/memcached basics



   • PHP extension based on the
     libmemcached C client library
   • Andrei Zmievski authored the extension
   • Now at a stable version 1.0.2
   • http://php.net/memcached
Settings and configuration



   • Memcached::OPT_COMPRESSION
   • Memcached::OPT_DISTRIBUTION
   • Memcached::OPT_LIBKETAMA_COMPATIBLE
   • Memcached::OPT_BINARY_PROTOCOL
   • Memcached::OPT_NO_BLOCK
Memcached methods

   •   add()             •   getResultMessage()

   •   addServer()       •   getServerList()

   •   append()          •   getStats()

   •   cas()             •   increment()

   •   decrement()       •   prepend()

   •   delete()          •   replace()

   •   get()             •   set()

   •   getMulti()        •   setMulti()

   •   getResultCode()   •   ... and more!
Alternative PHP
Cache (APC)
apc


www

                    www

              apc




  apc

        www
What is APC?

   • Opcode cache
   • Provides object caching (also referred to
     in places as “APC user variables”)
   • Gives information about file upload
     progress
   • Stores to local, shared memory
   • Not distributed
   • http://php.net/apc
Basic concepts and usage


   • For opcode caching, just install the
     extension and turn it on: apc.enabled=1
   • For memory allocation, change
     apc.shm_size; by default, it’s 30 MB

   • To speed things up even more, turn off
     apc.stat (set to 0)

   • “Set and forget” … but it also does object
     storage
Settings and configuration

   •   apc.shm_size – Determines how much
       memory is allocated to APC
   •   apc.stat – Determines whether APC will
       check if a file has been modified on every
       request
   •   apc.ttl – Leaving at zero means APC
       could potentially fill up with stale entries
       while newer ones won’t be cached; if
       greater than zero, APC will attempt to
       remove expired entries
How does opcode
caching work?
example.com/                          index.php




                public/index.php
                library/Zend/Application.php
                library/Zend/Loader/Autoloader.php
                library/Zend/Loader.php
                library/Zend/Config/Ini.php
                library/Zend/Config.php
                application/Bootstrap.php
                library/Zend/Application/Bootstrap/Bootstrap.php
APC             library/Zend/Application/Bootstrap/BootstrapAbstract.php
                library/Zend/Application/Bootstrap/Bootstrapper.php
                library/Zend/Application/Bootstrap/
                ResourceBootstrapper.php
                library/Zend/Application/Module/Autoloader.php
                library/Zend/Loader/Autoloader/Resource.php
                library/Zend/Loader/Autoloader/Interface.php
                library/Zend/Loader/PluginLoader.php
                ... 48 more files ...
example.com/                          index.php




                public/index.php
                library/Zend/Application.php
                library/Zend/Loader/Autoloader.php
                library/Zend/Loader.php
                library/Zend/Config/Ini.php
                library/Zend/Config.php
                application/Bootstrap.php
                library/Zend/Application/Bootstrap/Bootstrap.php
APC             library/Zend/Application/Bootstrap/BootstrapAbstract.php
                library/Zend/Application/Bootstrap/Bootstrapper.php
                library/Zend/Application/Bootstrap/
                ResourceBootstrapper.php
                library/Zend/Application/Module/Autoloader.php
                library/Zend/Loader/Autoloader/Resource.php
                library/Zend/Loader/Autoloader/Interface.php
                library/Zend/Loader/PluginLoader.php
                ... 48 more files ...
/welcome



           Magic!
                    language    key    translation
                      en       HELLO      Hello
                       fr      HELLO    Bonjour
                       es      HELLO      Hola
 en.php               de       HELLO      Hallo
                       nl      HELLO      Hallo
                       fi      HELLO      Hei
                      ga       HELLO    Dia duit
                       pt      HELLO      Olá
                       ...      ...        ...
                       ...      ...        ...
                       ...      ...        ...



    background                 data
      process                  base
Even better:
store the array to
APC with apc_store()!
APC object storage
if (($book = apc_fetch('0764596349')) === false)
{
  $book = Book::getByIsbn('0764596349');
  apc_store($book->getCacheKey(), $book);
}
APC functions

 •   apc_cache_info()         •   apc_load_constants()

 •   apc_clear_cache()        •   apc_add()

 •   apc_sma_info()           •   apc_inc()

 •   apc_store()              •   apc_dec()

 •   apc_fetch()              •   apc_cas()

 •   apc_delete()             •   apc_bin_dump()

 •   apc_delete_file()        •   apc_bin_load()

 •   apc_compile_file()       •   apc_bin_dumpfile()

 •   apc_define_constants()   •   apc_bin_loadfile()
Advanced APC



   • apc_compile_file()
   • apc_bin_dump()
   • apc_bin_load()
   • apc_bin_dumpfile()
   • apc_bin_loadfile()
Memcached
vs. APC
When should you use memcached?




   • When requests aren’t guaranteed to
     always go to the same machine
   • Data is specific or targeted to a user
   • User sessions
When should you use APC?


   • Application settings
   • Configuration
   • Data that is the same for each user
   • Requests are guaranteed to go to the
     same machine (i.e. sticky sessions)
   • File upload progress & sessions (if using
     sticky sessions)
Why not use both?



   • Create a caching adapter for a uniform
     caching interface and decide where to
     store at the app level or even
     dynamically at runtime
   • Use APC for things it’s good at and
     memcached for things it’s good at
Questions?
Thank you!
Ben Ramsey
benramsey.com
@ramsey
joind.in/1599

Weitere ähnliche Inhalte

Was ist angesagt?

Using memcache to improve php performance
Using memcache to improve php performanceUsing memcache to improve php performance
Using memcache to improve php performanceSudar Muthu
 
High Concurrency Architecture and Laravel Performance Tuning
High Concurrency Architecture and Laravel Performance TuningHigh Concurrency Architecture and Laravel Performance Tuning
High Concurrency Architecture and Laravel Performance TuningAlbert Chen
 
Integrated Cache on Netscaler
Integrated Cache on NetscalerIntegrated Cache on Netscaler
Integrated Cache on NetscalerMark Hillick
 
Accelerate your ColdFusion Applications using Caching
Accelerate your ColdFusion Applications using CachingAccelerate your ColdFusion Applications using Caching
Accelerate your ColdFusion Applications using CachingColdFusionConference
 
Building your own CDN using Amazon EC2
Building your own CDN using Amazon EC2Building your own CDN using Amazon EC2
Building your own CDN using Amazon EC2SergeyChernyshev
 
Integrating multiple CDN providers at Etsy - Velocity Europe (London) 2013
Integrating multiple CDN providers at Etsy - Velocity Europe (London) 2013Integrating multiple CDN providers at Etsy - Velocity Europe (London) 2013
Integrating multiple CDN providers at Etsy - Velocity Europe (London) 2013Marcus Barczak
 
Zend_Cache: how to improve the performance of PHP applications
Zend_Cache: how to improve the performance of PHP applicationsZend_Cache: how to improve the performance of PHP applications
Zend_Cache: how to improve the performance of PHP applicationsEnrico Zimuel
 
Tuning the Performance of Your ColdFusion Environment to Racecar Specs!
Tuning the Performance of Your ColdFusion Environment to Racecar Specs!Tuning the Performance of Your ColdFusion Environment to Racecar Specs!
Tuning the Performance of Your ColdFusion Environment to Racecar Specs!Hostway|HOSTING
 
Introduction to memcached
Introduction to memcachedIntroduction to memcached
Introduction to memcachedJurriaan Persyn
 
Caching with Varnish
Caching with VarnishCaching with Varnish
Caching with Varnishschoefmax
 
How to scale PHP applications
How to scale PHP applicationsHow to scale PHP applications
How to scale PHP applicationsEnrico Zimuel
 
Memcached B box presentation
Memcached B box presentationMemcached B box presentation
Memcached B box presentationNagesh Chinkeri
 
Usenix LISA 2012 - Choosing a Proxy
Usenix LISA 2012 - Choosing a ProxyUsenix LISA 2012 - Choosing a Proxy
Usenix LISA 2012 - Choosing a ProxyLeif Hedstrom
 

Was ist angesagt? (19)

Caching
CachingCaching
Caching
 
Cassandra as Memcache
Cassandra as MemcacheCassandra as Memcache
Cassandra as Memcache
 
Using memcache to improve php performance
Using memcache to improve php performanceUsing memcache to improve php performance
Using memcache to improve php performance
 
Velocity 2010 - ATS
Velocity 2010 - ATSVelocity 2010 - ATS
Velocity 2010 - ATS
 
High Concurrency Architecture and Laravel Performance Tuning
High Concurrency Architecture and Laravel Performance TuningHigh Concurrency Architecture and Laravel Performance Tuning
High Concurrency Architecture and Laravel Performance Tuning
 
Integrated Cache on Netscaler
Integrated Cache on NetscalerIntegrated Cache on Netscaler
Integrated Cache on Netscaler
 
Accelerate your ColdFusion Applications using Caching
Accelerate your ColdFusion Applications using CachingAccelerate your ColdFusion Applications using Caching
Accelerate your ColdFusion Applications using Caching
 
Usenix lisa 2011
Usenix lisa 2011Usenix lisa 2011
Usenix lisa 2011
 
Building your own CDN using Amazon EC2
Building your own CDN using Amazon EC2Building your own CDN using Amazon EC2
Building your own CDN using Amazon EC2
 
Memcache
MemcacheMemcache
Memcache
 
Top ten-list
Top ten-listTop ten-list
Top ten-list
 
Integrating multiple CDN providers at Etsy - Velocity Europe (London) 2013
Integrating multiple CDN providers at Etsy - Velocity Europe (London) 2013Integrating multiple CDN providers at Etsy - Velocity Europe (London) 2013
Integrating multiple CDN providers at Etsy - Velocity Europe (London) 2013
 
Zend_Cache: how to improve the performance of PHP applications
Zend_Cache: how to improve the performance of PHP applicationsZend_Cache: how to improve the performance of PHP applications
Zend_Cache: how to improve the performance of PHP applications
 
Tuning the Performance of Your ColdFusion Environment to Racecar Specs!
Tuning the Performance of Your ColdFusion Environment to Racecar Specs!Tuning the Performance of Your ColdFusion Environment to Racecar Specs!
Tuning the Performance of Your ColdFusion Environment to Racecar Specs!
 
Introduction to memcached
Introduction to memcachedIntroduction to memcached
Introduction to memcached
 
Caching with Varnish
Caching with VarnishCaching with Varnish
Caching with Varnish
 
How to scale PHP applications
How to scale PHP applicationsHow to scale PHP applications
How to scale PHP applications
 
Memcached B box presentation
Memcached B box presentationMemcached B box presentation
Memcached B box presentation
 
Usenix LISA 2012 - Choosing a Proxy
Usenix LISA 2012 - Choosing a ProxyUsenix LISA 2012 - Choosing a Proxy
Usenix LISA 2012 - Choosing a Proxy
 

Andere mochten auch

Accelerating Application Performance with Amazon ElastiCache (DAT207) | AWS r...
Accelerating Application Performance with Amazon ElastiCache (DAT207) | AWS r...Accelerating Application Performance with Amazon ElastiCache (DAT207) | AWS r...
Accelerating Application Performance with Amazon ElastiCache (DAT207) | AWS r...Amazon Web Services
 
Cache in Chromium: Disk Cache
Cache in Chromium: Disk CacheCache in Chromium: Disk Cache
Cache in Chromium: Disk CacheChang W. Doh
 
Redis memcached pdf
Redis memcached pdfRedis memcached pdf
Redis memcached pdfErin O'Neill
 
Deep Dive into Amazon ElastiCache Architecture and Design Patterns (DAT307) |...
Deep Dive into Amazon ElastiCache Architecture and Design Patterns (DAT307) |...Deep Dive into Amazon ElastiCache Architecture and Design Patterns (DAT307) |...
Deep Dive into Amazon ElastiCache Architecture and Design Patterns (DAT307) |...Amazon Web Services
 
AWS Webinar-Introducing Amazon ElastiCache for Redis
AWS Webinar-Introducing Amazon ElastiCache for RedisAWS Webinar-Introducing Amazon ElastiCache for Redis
AWS Webinar-Introducing Amazon ElastiCache for RedisAmazon Web Services
 
AWS re:Invent 2016: How Fulfillment by Amazon (FBA) and Scopely Improved Resu...
AWS re:Invent 2016: How Fulfillment by Amazon (FBA) and Scopely Improved Resu...AWS re:Invent 2016: How Fulfillment by Amazon (FBA) and Scopely Improved Resu...
AWS re:Invent 2016: How Fulfillment by Amazon (FBA) and Scopely Improved Resu...Amazon Web Services
 

Andere mochten auch (9)

Accelerating Application Performance with Amazon ElastiCache (DAT207) | AWS r...
Accelerating Application Performance with Amazon ElastiCache (DAT207) | AWS r...Accelerating Application Performance with Amazon ElastiCache (DAT207) | AWS r...
Accelerating Application Performance with Amazon ElastiCache (DAT207) | AWS r...
 
Cache in Chromium: Disk Cache
Cache in Chromium: Disk CacheCache in Chromium: Disk Cache
Cache in Chromium: Disk Cache
 
Redis memcached pdf
Redis memcached pdfRedis memcached pdf
Redis memcached pdf
 
Deep Dive into Amazon ElastiCache Architecture and Design Patterns (DAT307) |...
Deep Dive into Amazon ElastiCache Architecture and Design Patterns (DAT307) |...Deep Dive into Amazon ElastiCache Architecture and Design Patterns (DAT307) |...
Deep Dive into Amazon ElastiCache Architecture and Design Patterns (DAT307) |...
 
Types of art
Types of artTypes of art
Types of art
 
Art styles
Art stylesArt styles
Art styles
 
AWS Webinar-Introducing Amazon ElastiCache for Redis
AWS Webinar-Introducing Amazon ElastiCache for RedisAWS Webinar-Introducing Amazon ElastiCache for Redis
AWS Webinar-Introducing Amazon ElastiCache for Redis
 
AWS re:Invent 2016: How Fulfillment by Amazon (FBA) and Scopely Improved Resu...
AWS re:Invent 2016: How Fulfillment by Amazon (FBA) and Scopely Improved Resu...AWS re:Invent 2016: How Fulfillment by Amazon (FBA) and Scopely Improved Resu...
AWS re:Invent 2016: How Fulfillment by Amazon (FBA) and Scopely Improved Resu...
 
Types of Art Media
Types of Art MediaTypes of Art Media
Types of Art Media
 

Ähnlich wie Caching with Memcached and APC

Site Performance - From Pinto to Ferrari
Site Performance - From Pinto to FerrariSite Performance - From Pinto to Ferrari
Site Performance - From Pinto to FerrariJoseph Scott
 
php & performance
 php & performance php & performance
php & performancesimon8410
 
PHP & Performance
PHP & PerformancePHP & Performance
PHP & Performance毅 吕
 
Bottom to Top Stack Optimization with LAMP
Bottom to Top Stack Optimization with LAMPBottom to Top Stack Optimization with LAMP
Bottom to Top Stack Optimization with LAMPkatzgrau
 
Bottom to Top Stack Optimization - CICON2011
Bottom to Top Stack Optimization - CICON2011Bottom to Top Stack Optimization - CICON2011
Bottom to Top Stack Optimization - CICON2011CodeIgniter Conference
 
Performance tuning with zend framework
Performance tuning with zend frameworkPerformance tuning with zend framework
Performance tuning with zend frameworkAlan Seiden
 
phptek13 - Caching and tuning fun tutorial
phptek13 - Caching and tuning fun tutorialphptek13 - Caching and tuning fun tutorial
phptek13 - Caching and tuning fun tutorialWim Godden
 
Caching and tuning fun for high scalability @ phpBenelux 2011
Caching and tuning fun for high scalability @ phpBenelux 2011Caching and tuning fun for high scalability @ phpBenelux 2011
Caching and tuning fun for high scalability @ phpBenelux 2011Wim Godden
 
CHI - YAPC NA 2012
CHI - YAPC NA 2012CHI - YAPC NA 2012
CHI - YAPC NA 2012jonswar
 
Designing enterprise drupal
Designing enterprise drupalDesigning enterprise drupal
Designing enterprise drupalJason Burnett
 
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 scalabilityWim Godden
 
Caching objects-in-memory
Caching objects-in-memoryCaching objects-in-memory
Caching objects-in-memoryMauro Cassani
 
Advanced caching techniques with ehcache, big memory, terracotta, and coldfusion
Advanced caching techniques with ehcache, big memory, terracotta, and coldfusionAdvanced caching techniques with ehcache, big memory, terracotta, and coldfusion
Advanced caching techniques with ehcache, big memory, terracotta, and coldfusionColdFusionConference
 
Zend Con 2008 Slides
Zend Con 2008 SlidesZend Con 2008 Slides
Zend Con 2008 Slidesmkherlakian
 
Zend Server Data Caching
Zend Server Data CachingZend Server Data Caching
Zend Server Data CachingEl Taller Web
 
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 scalabilityWim Godden
 
Improve WordPress performance with caching and deferred execution of code
Improve WordPress performance with caching and deferred execution of codeImprove WordPress performance with caching and deferred execution of code
Improve WordPress performance with caching and deferred execution of codeDanilo Ercoli
 
Tips
TipsTips
Tipsmclee
 

Ähnlich wie Caching with Memcached and APC (20)

Site Performance - From Pinto to Ferrari
Site Performance - From Pinto to FerrariSite Performance - From Pinto to Ferrari
Site Performance - From Pinto to Ferrari
 
php & performance
 php & performance php & performance
php & performance
 
PHP & Performance
PHP & PerformancePHP & Performance
PHP & Performance
 
Bottom to Top Stack Optimization with LAMP
Bottom to Top Stack Optimization with LAMPBottom to Top Stack Optimization with LAMP
Bottom to Top Stack Optimization with LAMP
 
Bottom to Top Stack Optimization - CICON2011
Bottom to Top Stack Optimization - CICON2011Bottom to Top Stack Optimization - CICON2011
Bottom to Top Stack Optimization - CICON2011
 
Performance tuning with zend framework
Performance tuning with zend frameworkPerformance tuning with zend framework
Performance tuning with zend framework
 
phptek13 - Caching and tuning fun tutorial
phptek13 - Caching and tuning fun tutorialphptek13 - Caching and tuning fun tutorial
phptek13 - Caching and tuning fun tutorial
 
Caching and tuning fun for high scalability @ phpBenelux 2011
Caching and tuning fun for high scalability @ phpBenelux 2011Caching and tuning fun for high scalability @ phpBenelux 2011
Caching and tuning fun for high scalability @ phpBenelux 2011
 
Scaling PHP apps
Scaling PHP appsScaling PHP apps
Scaling PHP apps
 
CHI - YAPC NA 2012
CHI - YAPC NA 2012CHI - YAPC NA 2012
CHI - YAPC NA 2012
 
Designing enterprise drupal
Designing enterprise drupalDesigning enterprise drupal
Designing enterprise drupal
 
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
 
Caching objects-in-memory
Caching objects-in-memoryCaching objects-in-memory
Caching objects-in-memory
 
Advanced caching techniques with ehcache, big memory, terracotta, and coldfusion
Advanced caching techniques with ehcache, big memory, terracotta, and coldfusionAdvanced caching techniques with ehcache, big memory, terracotta, and coldfusion
Advanced caching techniques with ehcache, big memory, terracotta, and coldfusion
 
Zend Con 2008 Slides
Zend Con 2008 SlidesZend Con 2008 Slides
Zend Con 2008 Slides
 
Zend Server Data Caching
Zend Server Data CachingZend Server Data Caching
Zend Server Data Caching
 
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
 
Improve WordPress performance with caching and deferred execution of code
Improve WordPress performance with caching and deferred execution of codeImprove WordPress performance with caching and deferred execution of code
Improve WordPress performance with caching and deferred execution of code
 
Mini-Training: To cache or not to cache
Mini-Training: To cache or not to cacheMini-Training: To cache or not to cache
Mini-Training: To cache or not to cache
 
Tips
TipsTips
Tips
 

Mehr von Ben Ramsey

Api Versioning
Api VersioningApi Versioning
Api VersioningBen Ramsey
 
Grokking REST (ZendCon 2010)
Grokking REST (ZendCon 2010)Grokking REST (ZendCon 2010)
Grokking REST (ZendCon 2010)Ben Ramsey
 
Desktop Apps with PHP and Titanium (ZendCon 2010)
Desktop Apps with PHP and Titanium (ZendCon 2010)Desktop Apps with PHP and Titanium (ZendCon 2010)
Desktop Apps with PHP and Titanium (ZendCon 2010)Ben Ramsey
 
Introduction to AtomPub Web Services
Introduction to AtomPub Web ServicesIntroduction to AtomPub Web Services
Introduction to AtomPub Web ServicesBen Ramsey
 
Desktop Apps with PHP and Titanium
Desktop Apps with PHP and TitaniumDesktop Apps with PHP and Titanium
Desktop Apps with PHP and TitaniumBen Ramsey
 
Give Your Site a Boost with Memcache
Give Your Site a Boost with MemcacheGive Your Site a Boost with Memcache
Give Your Site a Boost with MemcacheBen Ramsey
 
Hidden Gems in HTTP
Hidden Gems in HTTPHidden Gems in HTTP
Hidden Gems in HTTPBen Ramsey
 
Grokking the REST Architectural Style
Grokking the REST Architectural StyleGrokking the REST Architectural Style
Grokking the REST Architectural StyleBen Ramsey
 
Making the Most of HTTP In Your Apps
Making the Most of HTTP In Your AppsMaking the Most of HTTP In Your Apps
Making the Most of HTTP In Your AppsBen Ramsey
 
Around the PHP Community
Around the PHP CommunityAround the PHP Community
Around the PHP CommunityBen Ramsey
 
You Look Like You Could Use Some REST!
You Look Like You Could Use Some REST!You Look Like You Could Use Some REST!
You Look Like You Could Use Some REST!Ben Ramsey
 
Distribution and Publication With Atom Web Services
Distribution and Publication With Atom Web ServicesDistribution and Publication With Atom Web Services
Distribution and Publication With Atom Web ServicesBen Ramsey
 
Distribution and Publication With Atom Web Services
Distribution and Publication With Atom Web ServicesDistribution and Publication With Atom Web Services
Distribution and Publication With Atom Web ServicesBen Ramsey
 

Mehr von Ben Ramsey (13)

Api Versioning
Api VersioningApi Versioning
Api Versioning
 
Grokking REST (ZendCon 2010)
Grokking REST (ZendCon 2010)Grokking REST (ZendCon 2010)
Grokking REST (ZendCon 2010)
 
Desktop Apps with PHP and Titanium (ZendCon 2010)
Desktop Apps with PHP and Titanium (ZendCon 2010)Desktop Apps with PHP and Titanium (ZendCon 2010)
Desktop Apps with PHP and Titanium (ZendCon 2010)
 
Introduction to AtomPub Web Services
Introduction to AtomPub Web ServicesIntroduction to AtomPub Web Services
Introduction to AtomPub Web Services
 
Desktop Apps with PHP and Titanium
Desktop Apps with PHP and TitaniumDesktop Apps with PHP and Titanium
Desktop Apps with PHP and Titanium
 
Give Your Site a Boost with Memcache
Give Your Site a Boost with MemcacheGive Your Site a Boost with Memcache
Give Your Site a Boost with Memcache
 
Hidden Gems in HTTP
Hidden Gems in HTTPHidden Gems in HTTP
Hidden Gems in HTTP
 
Grokking the REST Architectural Style
Grokking the REST Architectural StyleGrokking the REST Architectural Style
Grokking the REST Architectural Style
 
Making the Most of HTTP In Your Apps
Making the Most of HTTP In Your AppsMaking the Most of HTTP In Your Apps
Making the Most of HTTP In Your Apps
 
Around the PHP Community
Around the PHP CommunityAround the PHP Community
Around the PHP Community
 
You Look Like You Could Use Some REST!
You Look Like You Could Use Some REST!You Look Like You Could Use Some REST!
You Look Like You Could Use Some REST!
 
Distribution and Publication With Atom Web Services
Distribution and Publication With Atom Web ServicesDistribution and Publication With Atom Web Services
Distribution and Publication With Atom Web Services
 
Distribution and Publication With Atom Web Services
Distribution and Publication With Atom Web ServicesDistribution and Publication With Atom Web Services
Distribution and Publication With Atom Web Services
 

Kürzlich hochgeladen

"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks..."LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...Fwdays
 
TrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data PrivacyTrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data PrivacyTrustArc
 
Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Scott Keck-Warren
 
Advanced Computer Architecture – An Introduction
Advanced Computer Architecture – An IntroductionAdvanced Computer Architecture – An Introduction
Advanced Computer Architecture – An IntroductionDilum Bandara
 
Streamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupStreamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupFlorian Wilhelm
 
Powerpoint exploring the locations used in television show Time Clash
Powerpoint exploring the locations used in television show Time ClashPowerpoint exploring the locations used in television show Time Clash
Powerpoint exploring the locations used in television show Time Clashcharlottematthew16
 
DSPy a system for AI to Write Prompts and Do Fine Tuning
DSPy a system for AI to Write Prompts and Do Fine TuningDSPy a system for AI to Write Prompts and Do Fine Tuning
DSPy a system for AI to Write Prompts and Do Fine TuningLars Bell
 
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024BookNet Canada
 
Unleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubUnleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubKalema Edgar
 
The Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsThe Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsPixlogix Infotech
 
CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):comworks
 
Story boards and shot lists for my a level piece
Story boards and shot lists for my a level pieceStory boards and shot lists for my a level piece
Story boards and shot lists for my a level piececharlottematthew16
 
TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024Lonnie McRorey
 
Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Mattias Andersson
 
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdf
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdfHyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdf
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdfPrecisely
 
Search Engine Optimization SEO PDF for 2024.pdf
Search Engine Optimization SEO PDF for 2024.pdfSearch Engine Optimization SEO PDF for 2024.pdf
Search Engine Optimization SEO PDF for 2024.pdfRankYa
 
SAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptxSAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptxNavinnSomaal
 
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage CostLeverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage CostZilliz
 
Developer Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLDeveloper Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLScyllaDB
 
"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii SoldatenkoFwdays
 

Kürzlich hochgeladen (20)

"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks..."LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
 
TrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data PrivacyTrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data Privacy
 
Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024
 
Advanced Computer Architecture – An Introduction
Advanced Computer Architecture – An IntroductionAdvanced Computer Architecture – An Introduction
Advanced Computer Architecture – An Introduction
 
Streamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupStreamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project Setup
 
Powerpoint exploring the locations used in television show Time Clash
Powerpoint exploring the locations used in television show Time ClashPowerpoint exploring the locations used in television show Time Clash
Powerpoint exploring the locations used in television show Time Clash
 
DSPy a system for AI to Write Prompts and Do Fine Tuning
DSPy a system for AI to Write Prompts and Do Fine TuningDSPy a system for AI to Write Prompts and Do Fine Tuning
DSPy a system for AI to Write Prompts and Do Fine Tuning
 
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
 
Unleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubUnleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding Club
 
The Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsThe Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and Cons
 
CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):
 
Story boards and shot lists for my a level piece
Story boards and shot lists for my a level pieceStory boards and shot lists for my a level piece
Story boards and shot lists for my a level piece
 
TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024
 
Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?
 
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdf
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdfHyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdf
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdf
 
Search Engine Optimization SEO PDF for 2024.pdf
Search Engine Optimization SEO PDF for 2024.pdfSearch Engine Optimization SEO PDF for 2024.pdf
Search Engine Optimization SEO PDF for 2024.pdf
 
SAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptxSAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptx
 
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage CostLeverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
 
Developer Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLDeveloper Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQL
 
"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko
 

Caching with Memcached and APC

  • 1. Caching with Memcached & APC Ben Ramsey TEK·X • May 21, 2010
  • 3. What is a cache?
  • 4. “A cache is a collection of data duplicating original values stored elsewhere or computed earlier, where the original data is expensive to fetch (owing to longer access time) or to compute, compared to the cost of reading the cache.” –Wikipedia
  • 5. “A cache is a temporary storage area where frequently accessed data can be stored for rapid access.”
  • 6. Why use a cache?
  • 7. • To reduce the number or retrieval queries made to a database • To reduce the number of requests made to external services • To reduce the time spent computing data • To reduce filesystem access
  • 9. • File system • Database • Shared memory • RAM disk • Object cache (memcached and APC) • Opcode cache (APC)
  • 11. What is memcached? • Distributed memory object caching • Acts as a simple key/value dictionary • Runs as a daemon • Has a simple protocol for client access over TCP and UDP • Can be run in a pool, but individual daemons are not aware of the pool • Clients/applications manage the pool • Not an opcode cache
  • 12. Who uses memcached? • Facebook • Digg • Youtube • Wikipedia • Us (Moontoast) • Many others...
  • 13. Memcached principles • Fast asynchronous network I/O • Not a persistent data store • It does not provide redundancy • Data is not replicated across the cluster • It doesn’t handle failover
  • 14. Memcached principles • Daemons are not aware of each other • It does not provide authentication • Works great on a small and local-area network • A single value cannot contain more than 1MB of data • Keys are strings limited to 250 characters
  • 15. Basic concepts and usage 1. Set up a pool of memcached servers 2. Assign values to keys that are stored in the cluster 3. The client hashes the key to a particular machine in the cluster 4. Subsequent requests for that key retrieve the value from the memcached server on which it was stored 5. Values time out after the specified TTL
  • 16. memcached www www memcached memcached www
  • 17. memcached www www memcached memcached www
  • 18. A very simple protocol • Storage commands: set, add, replace, append, prepend, cas • Retrieval command: get, gets • Deletion command: delete • Increment/decrement: incr, decr • Other commands: stats, flush_all, version, verbosity, quit
  • 19. $> telnet localhost 11211 Trying ::1... Connected to localhost. Escape character is '^]'. set foobar 0 0 15 This is a test. STORED get foobar VALUE foobar 0 15 This is a test. END quit Connection closed by foreign host. $>
  • 20. Let’s see that with some code.
  • 21. $memcache = new Memcached(); $memcache->addServers(array( array('10.35.24.1', '11211'), array('10.35.24.2', '11211'), array('10.35.24.3', '11211'), ));
  • 22. $book = $memcache->get('0764596349'); if ($book === false) { if ($memcache->getResultCode() == Memcached::RES_NOTFOUND) { $book = Book::getByIsbn('0764596349'); $memcache->set($book->getCacheKey(), $book); } }
  • 23. Memcached limits • Key size has a 250 byte limit • Value can not be larger than 1 MB • Memory limits for 32bit/64bit systems • Replication not built-in; dependent on the client
  • 25. pecl/memcached basics • PHP extension based on the libmemcached C client library • Andrei Zmievski authored the extension • Now at a stable version 1.0.2 • http://php.net/memcached
  • 26. Settings and configuration • Memcached::OPT_COMPRESSION • Memcached::OPT_DISTRIBUTION • Memcached::OPT_LIBKETAMA_COMPATIBLE • Memcached::OPT_BINARY_PROTOCOL • Memcached::OPT_NO_BLOCK
  • 27. Memcached methods • add() • getResultMessage() • addServer() • getServerList() • append() • getStats() • cas() • increment() • decrement() • prepend() • delete() • replace() • get() • set() • getMulti() • setMulti() • getResultCode() • ... and more!
  • 29. apc www www apc apc www
  • 30. What is APC? • Opcode cache • Provides object caching (also referred to in places as “APC user variables”) • Gives information about file upload progress • Stores to local, shared memory • Not distributed • http://php.net/apc
  • 31. Basic concepts and usage • For opcode caching, just install the extension and turn it on: apc.enabled=1 • For memory allocation, change apc.shm_size; by default, it’s 30 MB • To speed things up even more, turn off apc.stat (set to 0) • “Set and forget” … but it also does object storage
  • 32. Settings and configuration • apc.shm_size – Determines how much memory is allocated to APC • apc.stat – Determines whether APC will check if a file has been modified on every request • apc.ttl – Leaving at zero means APC could potentially fill up with stale entries while newer ones won’t be cached; if greater than zero, APC will attempt to remove expired entries
  • 34. example.com/ index.php public/index.php library/Zend/Application.php library/Zend/Loader/Autoloader.php library/Zend/Loader.php library/Zend/Config/Ini.php library/Zend/Config.php application/Bootstrap.php library/Zend/Application/Bootstrap/Bootstrap.php APC library/Zend/Application/Bootstrap/BootstrapAbstract.php library/Zend/Application/Bootstrap/Bootstrapper.php library/Zend/Application/Bootstrap/ ResourceBootstrapper.php library/Zend/Application/Module/Autoloader.php library/Zend/Loader/Autoloader/Resource.php library/Zend/Loader/Autoloader/Interface.php library/Zend/Loader/PluginLoader.php ... 48 more files ...
  • 35. example.com/ index.php public/index.php library/Zend/Application.php library/Zend/Loader/Autoloader.php library/Zend/Loader.php library/Zend/Config/Ini.php library/Zend/Config.php application/Bootstrap.php library/Zend/Application/Bootstrap/Bootstrap.php APC library/Zend/Application/Bootstrap/BootstrapAbstract.php library/Zend/Application/Bootstrap/Bootstrapper.php library/Zend/Application/Bootstrap/ ResourceBootstrapper.php library/Zend/Application/Module/Autoloader.php library/Zend/Loader/Autoloader/Resource.php library/Zend/Loader/Autoloader/Interface.php library/Zend/Loader/PluginLoader.php ... 48 more files ...
  • 36. /welcome Magic! language key translation en HELLO Hello fr HELLO Bonjour es HELLO Hola en.php de HELLO Hallo nl HELLO Hallo fi HELLO Hei ga HELLO Dia duit pt HELLO Olá ... ... ... ... ... ... ... ... ... background data process base
  • 37. Even better: store the array to APC with apc_store()!
  • 39. if (($book = apc_fetch('0764596349')) === false) { $book = Book::getByIsbn('0764596349'); apc_store($book->getCacheKey(), $book); }
  • 40. APC functions • apc_cache_info() • apc_load_constants() • apc_clear_cache() • apc_add() • apc_sma_info() • apc_inc() • apc_store() • apc_dec() • apc_fetch() • apc_cas() • apc_delete() • apc_bin_dump() • apc_delete_file() • apc_bin_load() • apc_compile_file() • apc_bin_dumpfile() • apc_define_constants() • apc_bin_loadfile()
  • 41. Advanced APC • apc_compile_file() • apc_bin_dump() • apc_bin_load() • apc_bin_dumpfile() • apc_bin_loadfile()
  • 43. When should you use memcached? • When requests aren’t guaranteed to always go to the same machine • Data is specific or targeted to a user • User sessions
  • 44. When should you use APC? • Application settings • Configuration • Data that is the same for each user • Requests are guaranteed to go to the same machine (i.e. sticky sessions) • File upload progress & sessions (if using sticky sessions)
  • 45. Why not use both? • Create a caching adapter for a uniform caching interface and decide where to store at the app level or even dynamically at runtime • Use APC for things it’s good at and memcached for things it’s good at