SlideShare a Scribd company logo
1 of 34
Download to read offline
Give Your Site A Boost With Memcache
Ben Ramsey
September 25, 2009
Why cache?
             2
To make it faster.
                     3
“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. In
other words, a cache is a temporary storage area
where frequently accessed data can be stored for
rapid access.”                                          4

— Wikipedia
Why cache?
 You want to reduce the number of retrieval
 queries made to the database
 You want to reduce the number of external
 requests (retrieving data from other web
 services)
 You want to cut down on filesystem access
                                              5
Caching options
 Flat file caching
 Caching data in the database
 MySQL 4.x query caching
 Shared memory (APC)
 RAM disk
                                6
 memcached
What is memcached?
 Distributed Memory Object Caching System
 Caching daemon
 Developed by Danga Interactive for
 LiveJournal.com
 Uses RAM for storage
 Acts as a dictionary of stored data with key/   7

 value pairs
Is memcached fast?
 Stored in memory (RAM), not on disk
 Uses non-blocking network I/O (TCP/IP)
 Uses libevent to scale to any number of open
 connections
 Uses its own slab allocator and hash table to
 ensure virtual memory never gets externally     8
 fragmented and allocations are guaranteed
 O(1)
General usage
1.Set up a pool of memcached servers
2.Assign values to keys that are stored in the
  cluster
3.The memcache client hashes the key to a
  particular machine in the cluster
4.Subsequent requests for that key retrieve the   9
  value from the memcached server on which it
  was stored
5.Values time out after the specified TTL
Memcached principles
 Itʼs a non-blocking server
 It is not a database
 It does not provide redundancy
 It doesn't handle failover
 It does not provide authentication
                                      10
Memcached principles
 Data is not replicated across the cluster
 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    11
Storing data in the pool
 Advantage is in scalability
 To fully see the advantage, use a “pool”
 memcached itself doesn't know about the pool
 The pool is created by and managed from the
 client library
                                                12
www 3
   memcached

www 1                          memcached




                                           13


               memcached

                     www 2
Deterministic failover
 When one server goes down, the system fails
 over to another server in the pool
 Memcached does not provide this
 Some memcache clients provide failover
 If you canʼt find the data in memcache, eat the
 look-up cost and retrieve from your data         14
 source again, storing it back to the cache
www 3
   memcached

www 1                                  memcached



                                  Data inaccessible!

                                                       15


               memcached

                     www 2   Recreate data;
                             Store back to
                              memcache
The memcached protocol API
 Storage commands:
 set, add, replace, append, prepend, cas

 Retrieval command: get, gets
 Deletion command: delete
 Increment/decrement: incr, decr
                                           16
 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.                      17
END
quit
Connection closed by foreign host.
$>
Setting it up
 http://danga.com/memcached/
 $> ./configure; make; make install
 $> memcached -d -m 2048 -p 11211

 Done!
 Windows port of v1.2.4 at
                                                18
 http://www.splinedancer.com/memcached-win32/
Memcached clients
 Perl, Python, Ruby, Java, C#
 C (libmemcached)
 PostgreSQL (access memcached from procs
 and triggers)
 MySQL (adds memcache_engine storage
 engine)                                   19

 PHP (pecl/memcache or pecl/memcached)
pecl/memcache
 The PHP client for connecting to memcached
 and managing a pool of memcached servers
 http://pecl.php.net/package/memcache
 $> pecl install memcache

 Stable: 2.2.3
 Beta: 3.0.1                                  20
21
Features of pecl/memcache
 memcache.allow_failover
 memcache.hash_strategy
 memcache.hash_function
 memcache.protocol
 memcache.redundancy
                               22
 memcache.session_redundancy
pecl/memcache interface
 MemcachePool::connect()
 MemcachePool::addServer()
 MemcachePool::setServerParams()
 MemcachePool::get()
 MemcachePool::add()
                                   23
 MemcachePool::set()
 MemcachePool::replace()
 MemcachePool::cas()
pecl/memcache interface
 MemcachePool::append()
 MemcachePool::prepend()
 MemcachePool::delete()
 MemcachePool::increment()
 MemcachePool::decrement()
                                      24
 MemcachePool::setFailureCallback()
Key hashing
 Keys longer than 250 characters are
 truncated without warning
 Good practice to hash your key (with MD5 or
 SHA) at the userland level to ensure long
 keys donʼt get truncated
 Keys are “global”
                                                 25
 Use something to uniquely identify keys, e.g.
 a method signature or an SQL statement
Object serialization
 Objects are serialized before being stored to
 memcache:
 get key
 VALUE key 1 59
 O:8:"stdClass":2:{s:3:"foo";s:3:"bar";s:
 3:"baz";s:3:"quz";}
 END

 Extension unserializes them before returning     26
 the object
 Only objects that can be serialized safely can
 be stored to memcache, i.e. problems with
 DOM, SimpleXML, etc.
Redundancy and failover
 memcache.redundancy &
 memcache.session_redundancy
 Implement redundancy at the userland level?
 Again, memcache is not a database


                                               27
Extending MemcachePool
 Implement global values vs. page-specific
 values
 Ensure a single instance of the
 MemcachePool object
 Do complex key hashing, if you so choose
 Set a default expiration for all your data   28

 Add all of your servers upon object
 instantiation
Database techniques
 Create a wrapper for mysql_query() that
 checks the cache first and returns an array of
 database results
 Extend PDO to store results to the cache and
 get them when you execute a statement

                                                 29
Database techniques
 For large datasets, run a scheduled query
 once an hour and store it to the cache
 Please note: memcached can store arrays,
 objects, etc., but it cannot store a resource,
 which some database functions (e.g.
 mysql_query()) return
                                                  30
Session storage
 As of 2.1.1, you can set the session save
 handler as “memcache” and all will work
 automagically
 session.save_handler = memcache
 session.save_path = "tcp://
 192.168.1.10:11211,tcp://
 192.168.1.11:11211,tcp://192.168.1.12:11211"

 Store sessions to both the database and         31

 memcache
 Write your own session handler that stores to
 the database and memcache
www 3
    memcached

 www 1                           memcached



                                 Session
                              inaccessible!
                                              32

  Need to
                memcached
recreate the
  session!            www 2
For more information...
http://danga.com/memcached/
http://pecl.php.net/package/memcache
http://pecl.php.net/package/memcached
http://www.socialtext.net/memcached/


                                        33
Thank You
Slides available for download at benramsey.com.
Ben Ramsey
                                                  34
Senior Software Architect
Schematic
http://www.schematic.com/

More Related Content

What's hot

vSphere vStorage: Troubleshooting Performance
vSphere vStorage: Troubleshooting PerformancevSphere vStorage: Troubleshooting Performance
vSphere vStorage: Troubleshooting PerformanceProfessionalVMware
 
PostgreSQL Hangout Replication Features v9.4
PostgreSQL Hangout Replication Features v9.4PostgreSQL Hangout Replication Features v9.4
PostgreSQL Hangout Replication Features v9.4Ashnikbiz
 
Improve ColdFusion Performance by tuning the Connector and using ColdFusion-T...
Improve ColdFusion Performance by tuning the Connector and using ColdFusion-T...Improve ColdFusion Performance by tuning the Connector and using ColdFusion-T...
Improve ColdFusion Performance by tuning the Connector and using ColdFusion-T...ColdFusionConference
 
Distributed Caching Essential Lessons (Ts 1402)
Distributed Caching   Essential Lessons (Ts 1402)Distributed Caching   Essential Lessons (Ts 1402)
Distributed Caching Essential Lessons (Ts 1402)Yury Kaliaha
 
Distributed Caching Using the JCACHE API and ehcache, Including a Case Study ...
Distributed Caching Using the JCACHE API and ehcache, Including a Case Study ...Distributed Caching Using the JCACHE API and ehcache, Including a Case Study ...
Distributed Caching Using the JCACHE API and ehcache, Including a Case Study ...elliando dias
 
Improving PHP Application Performance with APC
Improving PHP Application Performance with APCImproving PHP Application Performance with APC
Improving PHP Application Performance with APCvortexau
 
Moxi - Memcached Proxy
Moxi - Memcached ProxyMoxi - Memcached Proxy
Moxi - Memcached ProxyNorthScale
 
Ehcache Architecture, Features And Usage Patterns
Ehcache Architecture, Features And Usage PatternsEhcache Architecture, Features And Usage Patterns
Ehcache Architecture, Features And Usage PatternsEduardo Pelegri-Llopart
 
MySQL Backup and Security Best Practices
MySQL Backup and Security Best PracticesMySQL Backup and Security Best Practices
MySQL Backup and Security Best PracticesLenz Grimmer
 
PHP Performance with APC + Memcached
PHP Performance with APC + MemcachedPHP Performance with APC + Memcached
PHP Performance with APC + MemcachedFord AntiTrust
 
Best Practices of HA and Replication of PostgreSQL in Virtualized Environments
Best Practices of HA and Replication of PostgreSQL in Virtualized EnvironmentsBest Practices of HA and Replication of PostgreSQL in Virtualized Environments
Best Practices of HA and Replication of PostgreSQL in Virtualized EnvironmentsJignesh Shah
 
Solving_the_C20K_problem_PHP_Performance_and_Scalability-phpquebec_2009
Solving_the_C20K_problem_PHP_Performance_and_Scalability-phpquebec_2009Solving_the_C20K_problem_PHP_Performance_and_Scalability-phpquebec_2009
Solving_the_C20K_problem_PHP_Performance_and_Scalability-phpquebec_2009Hiroshi Ono
 
Chef conf-2015-chef-patterns-at-bloomberg-scale
Chef conf-2015-chef-patterns-at-bloomberg-scaleChef conf-2015-chef-patterns-at-bloomberg-scale
Chef conf-2015-chef-patterns-at-bloomberg-scaleBiju Nair
 
Online MySQL Backups with Percona XtraBackup
Online MySQL Backups with Percona XtraBackupOnline MySQL Backups with Percona XtraBackup
Online MySQL Backups with Percona XtraBackupKenny Gryp
 
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
 
Kafka at half the price with JBOD setup
Kafka at half the price with JBOD setupKafka at half the price with JBOD setup
Kafka at half the price with JBOD setupDong Lin
 

What's hot (18)

vSphere vStorage: Troubleshooting Performance
vSphere vStorage: Troubleshooting PerformancevSphere vStorage: Troubleshooting Performance
vSphere vStorage: Troubleshooting Performance
 
PostgreSQL Hangout Replication Features v9.4
PostgreSQL Hangout Replication Features v9.4PostgreSQL Hangout Replication Features v9.4
PostgreSQL Hangout Replication Features v9.4
 
Improve ColdFusion Performance by tuning the Connector and using ColdFusion-T...
Improve ColdFusion Performance by tuning the Connector and using ColdFusion-T...Improve ColdFusion Performance by tuning the Connector and using ColdFusion-T...
Improve ColdFusion Performance by tuning the Connector and using ColdFusion-T...
 
Mike Resseler - Deduplication in windows server 2012 r2
Mike Resseler - Deduplication in windows server 2012 r2Mike Resseler - Deduplication in windows server 2012 r2
Mike Resseler - Deduplication in windows server 2012 r2
 
Distributed Caching Essential Lessons (Ts 1402)
Distributed Caching   Essential Lessons (Ts 1402)Distributed Caching   Essential Lessons (Ts 1402)
Distributed Caching Essential Lessons (Ts 1402)
 
JBoss AS 7
JBoss AS 7JBoss AS 7
JBoss AS 7
 
Distributed Caching Using the JCACHE API and ehcache, Including a Case Study ...
Distributed Caching Using the JCACHE API and ehcache, Including a Case Study ...Distributed Caching Using the JCACHE API and ehcache, Including a Case Study ...
Distributed Caching Using the JCACHE API and ehcache, Including a Case Study ...
 
Improving PHP Application Performance with APC
Improving PHP Application Performance with APCImproving PHP Application Performance with APC
Improving PHP Application Performance with APC
 
Moxi - Memcached Proxy
Moxi - Memcached ProxyMoxi - Memcached Proxy
Moxi - Memcached Proxy
 
Ehcache Architecture, Features And Usage Patterns
Ehcache Architecture, Features And Usage PatternsEhcache Architecture, Features And Usage Patterns
Ehcache Architecture, Features And Usage Patterns
 
MySQL Backup and Security Best Practices
MySQL Backup and Security Best PracticesMySQL Backup and Security Best Practices
MySQL Backup and Security Best Practices
 
PHP Performance with APC + Memcached
PHP Performance with APC + MemcachedPHP Performance with APC + Memcached
PHP Performance with APC + Memcached
 
Best Practices of HA and Replication of PostgreSQL in Virtualized Environments
Best Practices of HA and Replication of PostgreSQL in Virtualized EnvironmentsBest Practices of HA and Replication of PostgreSQL in Virtualized Environments
Best Practices of HA and Replication of PostgreSQL in Virtualized Environments
 
Solving_the_C20K_problem_PHP_Performance_and_Scalability-phpquebec_2009
Solving_the_C20K_problem_PHP_Performance_and_Scalability-phpquebec_2009Solving_the_C20K_problem_PHP_Performance_and_Scalability-phpquebec_2009
Solving_the_C20K_problem_PHP_Performance_and_Scalability-phpquebec_2009
 
Chef conf-2015-chef-patterns-at-bloomberg-scale
Chef conf-2015-chef-patterns-at-bloomberg-scaleChef conf-2015-chef-patterns-at-bloomberg-scale
Chef conf-2015-chef-patterns-at-bloomberg-scale
 
Online MySQL Backups with Percona XtraBackup
Online MySQL Backups with Percona XtraBackupOnline MySQL Backups with Percona XtraBackup
Online MySQL Backups with Percona XtraBackup
 
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!
 
Kafka at half the price with JBOD setup
Kafka at half the price with JBOD setupKafka at half the price with JBOD setup
Kafka at half the price with JBOD setup
 

Similar to Boost Site Speed With Memcache

Memcached B box presentation
Memcached B box presentationMemcached B box presentation
Memcached B box presentationNagesh Chinkeri
 
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
 
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 @ 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 2011Wim Godden
 
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
 
A memcached implementation in Java
A memcached implementation in JavaA memcached implementation in Java
A memcached implementation in Javaelliando dias
 
Session Handling Using Memcache
Session Handling Using MemcacheSession Handling Using Memcache
Session Handling Using MemcacheAnand Ghaywankar
 
Improving Website Performance with Memecached Webinar | Achieve Internet
Improving Website Performance with Memecached Webinar | Achieve InternetImproving Website Performance with Memecached Webinar | Achieve Internet
Improving Website Performance with Memecached Webinar | Achieve InternetAchieve Internet
 
Jug Lugano - Scale over the limits
Jug Lugano - Scale over the limitsJug Lugano - Scale over the limits
Jug Lugano - Scale over the limitsDavide Carnevali
 
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
 
Dutch php conference_apc_mem2010
Dutch php conference_apc_mem2010Dutch php conference_apc_mem2010
Dutch php conference_apc_mem2010isnull
 
Drupal, Memcache and Solr on Windows
Drupal, Memcache and Solr on WindowsDrupal, Memcache and Solr on Windows
Drupal, Memcache and Solr on WindowsAlessandro Pilotti
 
Scalling web applications using memcache
Scalling web applications using memcacheScalling web applications using memcache
Scalling web applications using memcacheSudar Muthu
 
Caching objects-in-memory
Caching objects-in-memoryCaching objects-in-memory
Caching objects-in-memoryMauro Cassani
 
SQL Server Exploitation, Escalation, Pilfering - AppSec USA 2012
SQL Server Exploitation, Escalation, Pilfering - AppSec USA 2012SQL Server Exploitation, Escalation, Pilfering - AppSec USA 2012
SQL Server Exploitation, Escalation, Pilfering - AppSec USA 2012Scott Sutherland
 
Performance Optimization using Caching | Swatantra Kumar
Performance Optimization using Caching | Swatantra KumarPerformance Optimization using Caching | Swatantra Kumar
Performance Optimization using Caching | Swatantra KumarSwatantra Kumar
 
Caching for Cash: Caching
Caching for Cash: CachingCaching for Cash: Caching
Caching for Cash: CachingScott MacVicar
 
Mysql wp memcached
Mysql wp memcachedMysql wp memcached
Mysql wp memcachedkbour23
 

Similar to Boost Site Speed With Memcache (20)

Memcached B box presentation
Memcached B box presentationMemcached B box presentation
Memcached B box presentation
 
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
 
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 @ 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
 
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
 
A memcached implementation in Java
A memcached implementation in JavaA memcached implementation in Java
A memcached implementation in Java
 
Session Handling Using Memcache
Session Handling Using MemcacheSession Handling Using Memcache
Session Handling Using Memcache
 
Improving Website Performance with Memecached Webinar | Achieve Internet
Improving Website Performance with Memecached Webinar | Achieve InternetImproving Website Performance with Memecached Webinar | Achieve Internet
Improving Website Performance with Memecached Webinar | Achieve Internet
 
Jug Lugano - Scale over the limits
Jug Lugano - Scale over the limitsJug Lugano - Scale over the limits
Jug Lugano - Scale over the limits
 
Drupal7 MEMCACHE
Drupal7 MEMCACHE Drupal7 MEMCACHE
Drupal7 MEMCACHE
 
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
 
Dutch php conference_apc_mem2010
Dutch php conference_apc_mem2010Dutch php conference_apc_mem2010
Dutch php conference_apc_mem2010
 
Drupal, Memcache and Solr on Windows
Drupal, Memcache and Solr on WindowsDrupal, Memcache and Solr on Windows
Drupal, Memcache and Solr on Windows
 
Scalling web applications using memcache
Scalling web applications using memcacheScalling web applications using memcache
Scalling web applications using memcache
 
Caching objects-in-memory
Caching objects-in-memoryCaching objects-in-memory
Caching objects-in-memory
 
SQL Server Exploitation, Escalation, Pilfering - AppSec USA 2012
SQL Server Exploitation, Escalation, Pilfering - AppSec USA 2012SQL Server Exploitation, Escalation, Pilfering - AppSec USA 2012
SQL Server Exploitation, Escalation, Pilfering - AppSec USA 2012
 
Performance Optimization using Caching | Swatantra Kumar
Performance Optimization using Caching | Swatantra KumarPerformance Optimization using Caching | Swatantra Kumar
Performance Optimization using Caching | Swatantra Kumar
 
Caching for Cash: Caching
Caching for Cash: CachingCaching for Cash: Caching
Caching for Cash: Caching
 
Mysql wp memcached
Mysql wp memcachedMysql wp memcached
Mysql wp memcached
 
Mysql wp memcached
Mysql wp memcachedMysql wp memcached
Mysql wp memcached
 

More from 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
 
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
 

More from Ben Ramsey (12)

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

Recently uploaded

Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...shyamraj55
 
Benefits Of Flutter Compared To Other Frameworks
Benefits Of Flutter Compared To Other FrameworksBenefits Of Flutter Compared To Other Frameworks
Benefits Of Flutter Compared To Other FrameworksSoftradix Technologies
 
Maximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptxMaximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptxOnBoard
 
Install Stable Diffusion in windows machine
Install Stable Diffusion in windows machineInstall Stable Diffusion in windows machine
Install Stable Diffusion in windows machinePadma Pradeep
 
The Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxThe Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxMalak Abu Hammad
 
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
 
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 3652toLead Limited
 
Pigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food ManufacturingPigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food ManufacturingPigging Solutions
 
Making_way_through_DLL_hollowing_inspite_of_CFG_by_Debjeet Banerjee.pptx
Making_way_through_DLL_hollowing_inspite_of_CFG_by_Debjeet Banerjee.pptxMaking_way_through_DLL_hollowing_inspite_of_CFG_by_Debjeet Banerjee.pptx
Making_way_through_DLL_hollowing_inspite_of_CFG_by_Debjeet Banerjee.pptxnull - The Open Security Community
 
Slack Application Development 101 Slides
Slack Application Development 101 SlidesSlack Application Development 101 Slides
Slack Application Development 101 Slidespraypatel2
 
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024BookNet Canada
 
Snow Chain-Integrated Tire for a Safe Drive on Winter Roads
Snow Chain-Integrated Tire for a Safe Drive on Winter RoadsSnow Chain-Integrated Tire for a Safe Drive on Winter Roads
Snow Chain-Integrated Tire for a Safe Drive on Winter RoadsHyundai Motor Group
 
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | DelhiFULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhisoniya singh
 
Breaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountBreaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountPuma Security, LLC
 
SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024Scott Keck-Warren
 
SIEMENS: RAPUNZEL – A Tale About Knowledge Graph
SIEMENS: RAPUNZEL – A Tale About Knowledge GraphSIEMENS: RAPUNZEL – A Tale About Knowledge Graph
SIEMENS: RAPUNZEL – A Tale About Knowledge GraphNeo4j
 
Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...Alan Dix
 
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 MenDelhi Call girls
 

Recently uploaded (20)

Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
 
Benefits Of Flutter Compared To Other Frameworks
Benefits Of Flutter Compared To Other FrameworksBenefits Of Flutter Compared To Other Frameworks
Benefits Of Flutter Compared To Other Frameworks
 
Maximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptxMaximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptx
 
Install Stable Diffusion in windows machine
Install Stable Diffusion in windows machineInstall Stable Diffusion in windows machine
Install Stable Diffusion in windows machine
 
The Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxThe Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptx
 
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
 
The transition to renewables in India.pdf
The transition to renewables in India.pdfThe transition to renewables in India.pdf
The transition to renewables in India.pdf
 
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
 
Vulnerability_Management_GRC_by Sohang Sengupta.pptx
Vulnerability_Management_GRC_by Sohang Sengupta.pptxVulnerability_Management_GRC_by Sohang Sengupta.pptx
Vulnerability_Management_GRC_by Sohang Sengupta.pptx
 
Pigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food ManufacturingPigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food Manufacturing
 
Making_way_through_DLL_hollowing_inspite_of_CFG_by_Debjeet Banerjee.pptx
Making_way_through_DLL_hollowing_inspite_of_CFG_by_Debjeet Banerjee.pptxMaking_way_through_DLL_hollowing_inspite_of_CFG_by_Debjeet Banerjee.pptx
Making_way_through_DLL_hollowing_inspite_of_CFG_by_Debjeet Banerjee.pptx
 
Slack Application Development 101 Slides
Slack Application Development 101 SlidesSlack Application Development 101 Slides
Slack Application Development 101 Slides
 
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
 
Snow Chain-Integrated Tire for a Safe Drive on Winter Roads
Snow Chain-Integrated Tire for a Safe Drive on Winter RoadsSnow Chain-Integrated Tire for a Safe Drive on Winter Roads
Snow Chain-Integrated Tire for a Safe Drive on Winter Roads
 
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | DelhiFULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
 
Breaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountBreaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path Mount
 
SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024
 
SIEMENS: RAPUNZEL – A Tale About Knowledge Graph
SIEMENS: RAPUNZEL – A Tale About Knowledge GraphSIEMENS: RAPUNZEL – A Tale About Knowledge Graph
SIEMENS: RAPUNZEL – A Tale About Knowledge Graph
 
Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...
 
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
 

Boost Site Speed With Memcache

  • 1. Give Your Site A Boost With Memcache Ben Ramsey September 25, 2009
  • 3. To make it faster. 3
  • 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. In other words, a cache is a temporary storage area where frequently accessed data can be stored for rapid access.” 4 — Wikipedia
  • 5. Why cache? You want to reduce the number of retrieval queries made to the database You want to reduce the number of external requests (retrieving data from other web services) You want to cut down on filesystem access 5
  • 6. Caching options Flat file caching Caching data in the database MySQL 4.x query caching Shared memory (APC) RAM disk 6 memcached
  • 7. What is memcached? Distributed Memory Object Caching System Caching daemon Developed by Danga Interactive for LiveJournal.com Uses RAM for storage Acts as a dictionary of stored data with key/ 7 value pairs
  • 8. Is memcached fast? Stored in memory (RAM), not on disk Uses non-blocking network I/O (TCP/IP) Uses libevent to scale to any number of open connections Uses its own slab allocator and hash table to ensure virtual memory never gets externally 8 fragmented and allocations are guaranteed O(1)
  • 9. General usage 1.Set up a pool of memcached servers 2.Assign values to keys that are stored in the cluster 3.The memcache client hashes the key to a particular machine in the cluster 4.Subsequent requests for that key retrieve the 9 value from the memcached server on which it was stored 5.Values time out after the specified TTL
  • 10. Memcached principles Itʼs a non-blocking server It is not a database It does not provide redundancy It doesn't handle failover It does not provide authentication 10
  • 11. Memcached principles Data is not replicated across the cluster 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 11
  • 12. Storing data in the pool Advantage is in scalability To fully see the advantage, use a “pool” memcached itself doesn't know about the pool The pool is created by and managed from the client library 12
  • 13. www 3 memcached www 1 memcached 13 memcached www 2
  • 14. Deterministic failover When one server goes down, the system fails over to another server in the pool Memcached does not provide this Some memcache clients provide failover If you canʼt find the data in memcache, eat the look-up cost and retrieve from your data 14 source again, storing it back to the cache
  • 15. www 3 memcached www 1 memcached Data inaccessible! 15 memcached www 2 Recreate data; Store back to memcache
  • 16. The memcached protocol API Storage commands: set, add, replace, append, prepend, cas Retrieval command: get, gets Deletion command: delete Increment/decrement: incr, decr 16 Other commands: stats, flush_all, version, verbosity, quit
  • 17. $> 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. 17 END quit Connection closed by foreign host. $>
  • 18. Setting it up http://danga.com/memcached/ $> ./configure; make; make install $> memcached -d -m 2048 -p 11211 Done! Windows port of v1.2.4 at 18 http://www.splinedancer.com/memcached-win32/
  • 19. Memcached clients Perl, Python, Ruby, Java, C# C (libmemcached) PostgreSQL (access memcached from procs and triggers) MySQL (adds memcache_engine storage engine) 19 PHP (pecl/memcache or pecl/memcached)
  • 20. pecl/memcache The PHP client for connecting to memcached and managing a pool of memcached servers http://pecl.php.net/package/memcache $> pecl install memcache Stable: 2.2.3 Beta: 3.0.1 20
  • 21. 21
  • 22. Features of pecl/memcache memcache.allow_failover memcache.hash_strategy memcache.hash_function memcache.protocol memcache.redundancy 22 memcache.session_redundancy
  • 23. pecl/memcache interface MemcachePool::connect() MemcachePool::addServer() MemcachePool::setServerParams() MemcachePool::get() MemcachePool::add() 23 MemcachePool::set() MemcachePool::replace() MemcachePool::cas()
  • 24. pecl/memcache interface MemcachePool::append() MemcachePool::prepend() MemcachePool::delete() MemcachePool::increment() MemcachePool::decrement() 24 MemcachePool::setFailureCallback()
  • 25. Key hashing Keys longer than 250 characters are truncated without warning Good practice to hash your key (with MD5 or SHA) at the userland level to ensure long keys donʼt get truncated Keys are “global” 25 Use something to uniquely identify keys, e.g. a method signature or an SQL statement
  • 26. Object serialization Objects are serialized before being stored to memcache: get key VALUE key 1 59 O:8:"stdClass":2:{s:3:"foo";s:3:"bar";s: 3:"baz";s:3:"quz";} END Extension unserializes them before returning 26 the object Only objects that can be serialized safely can be stored to memcache, i.e. problems with DOM, SimpleXML, etc.
  • 27. Redundancy and failover memcache.redundancy & memcache.session_redundancy Implement redundancy at the userland level? Again, memcache is not a database 27
  • 28. Extending MemcachePool Implement global values vs. page-specific values Ensure a single instance of the MemcachePool object Do complex key hashing, if you so choose Set a default expiration for all your data 28 Add all of your servers upon object instantiation
  • 29. Database techniques Create a wrapper for mysql_query() that checks the cache first and returns an array of database results Extend PDO to store results to the cache and get them when you execute a statement 29
  • 30. Database techniques For large datasets, run a scheduled query once an hour and store it to the cache Please note: memcached can store arrays, objects, etc., but it cannot store a resource, which some database functions (e.g. mysql_query()) return 30
  • 31. Session storage As of 2.1.1, you can set the session save handler as “memcache” and all will work automagically session.save_handler = memcache session.save_path = "tcp:// 192.168.1.10:11211,tcp:// 192.168.1.11:11211,tcp://192.168.1.12:11211" Store sessions to both the database and 31 memcache Write your own session handler that stores to the database and memcache
  • 32. www 3 memcached www 1 memcached Session inaccessible! 32 Need to memcached recreate the session! www 2
  • 34. Thank You Slides available for download at benramsey.com. Ben Ramsey 34 Senior Software Architect Schematic http://www.schematic.com/