SlideShare a Scribd company logo
1 of 30
Download to read offline
Give Your Site A Boost
With Memcache


Ben Ramsey ■ DC PHP Conference ■ 3 June 2008
Software Architect
          at Schematic
          Atlanta PHP Leader
          Co-author of Zend
          PHP 5 Certification
          Study Guide
          Chatter on #phpc



Give Your Site A Boost With Memcache
Ben Ramsey ■ DC PHP Conference ■ 3 June 2008
“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.”
      — Wikipedia


Give Your Site A Boost With Memcache
Ben Ramsey ■ DC PHP Conference ■ 3 June 2008
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



Give Your Site A Boost With Memcache
Ben Ramsey ■ DC PHP Conference ■ 3 June 2008
Caching options
             Flat file caching
             Caching data in the database
             MySQL 4.x query caching
             Shared memory (APC)
             RAM disk
             memcached



Give Your Site A Boost With Memcache
Ben Ramsey ■ DC PHP Conference ■ 3 June 2008
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/value pairs

Give Your Site A Boost With Memcache
Ben Ramsey ■ DC PHP Conference ■ 3 June 2008
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 fragmented and allocations are
             guaranteed O(1)


Give Your Site A Boost With Memcache
Ben Ramsey ■ DC PHP Conference ■ 3 June 2008
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 value from the memcached server on
           which it was stored
        5. Values time out after the specified TTL
Give Your Site A Boost With Memcache
Ben Ramsey ■ DC PHP Conference ■ 3 June 2008
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




Give Your Site A Boost With Memcache
Ben Ramsey ■ DC PHP Conference ■ 3 June 2008
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




Give Your Site A Boost With Memcache
Ben Ramsey ■ DC PHP Conference ■ 3 June 2008
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




Give Your Site A Boost With Memcache
Ben Ramsey ■ DC PHP Conference ■ 3 June 2008
www 3
               memcached
                                                           memcached
       www 1




                                           memcached

                                                 www 2




Give Your Site A Boost With Memcache
Ben Ramsey ■ DC PHP Conference ■ 3 June 2008
Deterministic failover
             Memcached does not provide this
             It is up to you to implement it
             If you can’t find the data in memcache,
             eat the look-up cost and retrieve from
             your data source again, storing it back to
             the cache




Give Your Site A Boost With Memcache
Ben Ramsey ■ DC PHP Conference ■ 3 June 2008
www 3
               memcached
                                                                   memcached
       www 1


                                                                    Data
                                                                inaccessible!



                                           memcached

                                                 www 2
                                                         Recreate data;
                                                         Store back to
                                                          memcache

Give Your Site A Boost With Memcache
Ben Ramsey ■ DC PHP Conference ■ 3 June 2008
The memcached protocol API
             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

Give Your Site A Boost With Memcache
Ben Ramsey ■ DC PHP Conference ■ 3 June 2008
$> 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.
   $>


Give Your Site A Boost With Memcache
Ben Ramsey ■ DC PHP Conference ■ 3 June 2008
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
             http://www.splinedancer.com/memcached-win32/




Give Your Site A Boost With Memcache
Ben Ramsey ■ DC PHP Conference ■ 3 June 2008
Memcached clients
             Perl, Python, Ruby, Java, C#
             C (libmemcached)
             PostgreSQL (access memcached from
             procs and triggers)
             MySQL (adds memcache_engine storage
             engine)
             PHP (pecl/memcache)


Give Your Site A Boost With Memcache
Ben Ramsey ■ DC PHP Conference ■ 3 June 2008
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



Give Your Site A Boost With Memcache
Ben Ramsey ■ DC PHP Conference ■ 3 June 2008
Give Your Site A Boost With Memcache
Ben Ramsey ■ DC PHP Conference ■ 3 June 2008
Features of pecl/memcache
             memcache.allow_failover
             memcache.hash_strategy
             memcache.hash_function
             memcache.protocol
             memcache.redundancy
             memcache.session_redundancy



Give Your Site A Boost With Memcache
Ben Ramsey ■ DC PHP Conference ■ 3 June 2008
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”
             Use something to uniquely identify keys,
             e.g. a method signature or an SQL
             statement

Give Your Site A Boost With Memcache
Ben Ramsey ■ DC PHP Conference ■ 3 June 2008
Object serialization
             Objects are serialized before being stored
             to memcache:
             get key
             VALUE key 1 59
             O:8:quot;stdClassquot;:2:{s:3:quot;fooquot;;s:3:quot;barquot;;s:3:quot;bazquot;;s:3:quot;quzquot;;}
             END

             Extension unserializes them before
             returning the object
             Only objects that can be serialized safely
             can be stored to memcache, i.e.
             problems with DOM, SimpleXML, etc.
Give Your Site A Boost With Memcache
Ben Ramsey ■ DC PHP Conference ■ 3 June 2008
Redundancy and failover
             memcache.redundancy &
             memcache.session_redundancy
             Implement redundancy at the userland
             level?
             Again, memcache is not a database




Give Your Site A Boost With Memcache
Ben Ramsey ■ DC PHP Conference ■ 3 June 2008
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
             Add all of your servers upon object
             instantiation
Give Your Site A Boost With Memcache
Ben Ramsey ■ DC PHP Conference ■ 3 June 2008
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




Give Your Site A Boost With Memcache
Ben Ramsey ■ DC PHP Conference ■ 3 June 2008
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




Give Your Site A Boost With Memcache
Ben Ramsey ■ DC PHP Conference ■ 3 June 2008
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 = quot;tcp://192.168.1.10:11211,tcp://
             192.168.1.11:11211,tcp://192.168.1.12:11211quot;

             Store sessions to both the database and
             memcache
             Write your own session handler that
             stores to the database and memcache

Give Your Site A Boost With Memcache
Ben Ramsey ■ DC PHP Conference ■ 3 June 2008
www 3
               memcached
                                                            memcached
       www 1


                                                            Session
                                                         inaccessible!


    Need to                                memcached
  recreate the
    session!                                     www 2




Give Your Site A Boost With Memcache
Ben Ramsey ■ DC PHP Conference ■ 3 June 2008
For more information...
             http://danga.com/memcached/
             http://pecl.php.net/package/memcache
             http://www.socialtext.net/memcached/


             My blog: http://benramsey.com/




Give Your Site A Boost With Memcache
Ben Ramsey ■ DC PHP Conference ■ 3 June 2008

More Related Content

More from Ben 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 (6)

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

Decarbonising Buildings: Making a net-zero built environment a reality
Decarbonising Buildings: Making a net-zero built environment a realityDecarbonising Buildings: Making a net-zero built environment a reality
Decarbonising Buildings: Making a net-zero built environment a realityIES VE
 
Unleashing Real-time Insights with ClickHouse_ Navigating the Landscape in 20...
Unleashing Real-time Insights with ClickHouse_ Navigating the Landscape in 20...Unleashing Real-time Insights with ClickHouse_ Navigating the Landscape in 20...
Unleashing Real-time Insights with ClickHouse_ Navigating the Landscape in 20...Alkin Tezuysal
 
Generative AI - Gitex v1Generative AI - Gitex v1.pptx
Generative AI - Gitex v1Generative AI - Gitex v1.pptxGenerative AI - Gitex v1Generative AI - Gitex v1.pptx
Generative AI - Gitex v1Generative AI - Gitex v1.pptxfnnc6jmgwh
 
Glenn Lazarus- Why Your Observability Strategy Needs Security Observability
Glenn Lazarus- Why Your Observability Strategy Needs Security ObservabilityGlenn Lazarus- Why Your Observability Strategy Needs Security Observability
Glenn Lazarus- Why Your Observability Strategy Needs Security Observabilityitnewsafrica
 
MuleSoft Online Meetup Group - B2B Crash Course: Release SparkNotes
MuleSoft Online Meetup Group - B2B Crash Course: Release SparkNotesMuleSoft Online Meetup Group - B2B Crash Course: Release SparkNotes
MuleSoft Online Meetup Group - B2B Crash Course: Release SparkNotesManik S Magar
 
Kuma Meshes Part I - The basics - A tutorial
Kuma Meshes Part I - The basics - A tutorialKuma Meshes Part I - The basics - A tutorial
Kuma Meshes Part I - The basics - A tutorialJoão Esperancinha
 
Microsoft 365 Copilot: How to boost your productivity with AI – Part one: Ado...
Microsoft 365 Copilot: How to boost your productivity with AI – Part one: Ado...Microsoft 365 Copilot: How to boost your productivity with AI – Part one: Ado...
Microsoft 365 Copilot: How to boost your productivity with AI – Part one: Ado...Nikki Chapple
 
Email Marketing Automation for Bonterra Impact Management (fka Social Solutio...
Email Marketing Automation for Bonterra Impact Management (fka Social Solutio...Email Marketing Automation for Bonterra Impact Management (fka Social Solutio...
Email Marketing Automation for Bonterra Impact Management (fka Social Solutio...Jeffrey Haguewood
 
QCon London: Mastering long-running processes in modern architectures
QCon London: Mastering long-running processes in modern architecturesQCon London: Mastering long-running processes in modern architectures
QCon London: Mastering long-running processes in modern architecturesBernd Ruecker
 
So einfach geht modernes Roaming fuer Notes und Nomad.pdf
So einfach geht modernes Roaming fuer Notes und Nomad.pdfSo einfach geht modernes Roaming fuer Notes und Nomad.pdf
So einfach geht modernes Roaming fuer Notes und Nomad.pdfpanagenda
 
React Native vs Ionic - The Best Mobile App Framework
React Native vs Ionic - The Best Mobile App FrameworkReact Native vs Ionic - The Best Mobile App Framework
React Native vs Ionic - The Best Mobile App FrameworkPixlogix Infotech
 
Transcript: New from BookNet Canada for 2024: BNC SalesData and LibraryData -...
Transcript: New from BookNet Canada for 2024: BNC SalesData and LibraryData -...Transcript: New from BookNet Canada for 2024: BNC SalesData and LibraryData -...
Transcript: New from BookNet Canada for 2024: BNC SalesData and LibraryData -...BookNet Canada
 
Zeshan Sattar- Assessing the skill requirements and industry expectations for...
Zeshan Sattar- Assessing the skill requirements and industry expectations for...Zeshan Sattar- Assessing the skill requirements and industry expectations for...
Zeshan Sattar- Assessing the skill requirements and industry expectations for...itnewsafrica
 
JET Technology Labs White Paper for Virtualized Security and Encryption Techn...
JET Technology Labs White Paper for Virtualized Security and Encryption Techn...JET Technology Labs White Paper for Virtualized Security and Encryption Techn...
JET Technology Labs White Paper for Virtualized Security and Encryption Techn...amber724300
 
Testing tools and AI - ideas what to try with some tool examples
Testing tools and AI - ideas what to try with some tool examplesTesting tools and AI - ideas what to try with some tool examples
Testing tools and AI - ideas what to try with some tool examplesKari Kakkonen
 
Varsha Sewlal- Cyber Attacks on Critical Critical Infrastructure
Varsha Sewlal- Cyber Attacks on Critical Critical InfrastructureVarsha Sewlal- Cyber Attacks on Critical Critical Infrastructure
Varsha Sewlal- Cyber Attacks on Critical Critical Infrastructureitnewsafrica
 
Connecting the Dots for Information Discovery.pdf
Connecting the Dots for Information Discovery.pdfConnecting the Dots for Information Discovery.pdf
Connecting the Dots for Information Discovery.pdfNeo4j
 
Landscape Catalogue 2024 Australia-1.pdf
Landscape Catalogue 2024 Australia-1.pdfLandscape Catalogue 2024 Australia-1.pdf
Landscape Catalogue 2024 Australia-1.pdfAarwolf Industries LLC
 
UiPath Community: Communication Mining from Zero to Hero
UiPath Community: Communication Mining from Zero to HeroUiPath Community: Communication Mining from Zero to Hero
UiPath Community: Communication Mining from Zero to HeroUiPathCommunity
 
React JS; all concepts. Contains React Features, JSX, functional & Class comp...
React JS; all concepts. Contains React Features, JSX, functional & Class comp...React JS; all concepts. Contains React Features, JSX, functional & Class comp...
React JS; all concepts. Contains React Features, JSX, functional & Class comp...Karmanjay Verma
 

Recently uploaded (20)

Decarbonising Buildings: Making a net-zero built environment a reality
Decarbonising Buildings: Making a net-zero built environment a realityDecarbonising Buildings: Making a net-zero built environment a reality
Decarbonising Buildings: Making a net-zero built environment a reality
 
Unleashing Real-time Insights with ClickHouse_ Navigating the Landscape in 20...
Unleashing Real-time Insights with ClickHouse_ Navigating the Landscape in 20...Unleashing Real-time Insights with ClickHouse_ Navigating the Landscape in 20...
Unleashing Real-time Insights with ClickHouse_ Navigating the Landscape in 20...
 
Generative AI - Gitex v1Generative AI - Gitex v1.pptx
Generative AI - Gitex v1Generative AI - Gitex v1.pptxGenerative AI - Gitex v1Generative AI - Gitex v1.pptx
Generative AI - Gitex v1Generative AI - Gitex v1.pptx
 
Glenn Lazarus- Why Your Observability Strategy Needs Security Observability
Glenn Lazarus- Why Your Observability Strategy Needs Security ObservabilityGlenn Lazarus- Why Your Observability Strategy Needs Security Observability
Glenn Lazarus- Why Your Observability Strategy Needs Security Observability
 
MuleSoft Online Meetup Group - B2B Crash Course: Release SparkNotes
MuleSoft Online Meetup Group - B2B Crash Course: Release SparkNotesMuleSoft Online Meetup Group - B2B Crash Course: Release SparkNotes
MuleSoft Online Meetup Group - B2B Crash Course: Release SparkNotes
 
Kuma Meshes Part I - The basics - A tutorial
Kuma Meshes Part I - The basics - A tutorialKuma Meshes Part I - The basics - A tutorial
Kuma Meshes Part I - The basics - A tutorial
 
Microsoft 365 Copilot: How to boost your productivity with AI – Part one: Ado...
Microsoft 365 Copilot: How to boost your productivity with AI – Part one: Ado...Microsoft 365 Copilot: How to boost your productivity with AI – Part one: Ado...
Microsoft 365 Copilot: How to boost your productivity with AI – Part one: Ado...
 
Email Marketing Automation for Bonterra Impact Management (fka Social Solutio...
Email Marketing Automation for Bonterra Impact Management (fka Social Solutio...Email Marketing Automation for Bonterra Impact Management (fka Social Solutio...
Email Marketing Automation for Bonterra Impact Management (fka Social Solutio...
 
QCon London: Mastering long-running processes in modern architectures
QCon London: Mastering long-running processes in modern architecturesQCon London: Mastering long-running processes in modern architectures
QCon London: Mastering long-running processes in modern architectures
 
So einfach geht modernes Roaming fuer Notes und Nomad.pdf
So einfach geht modernes Roaming fuer Notes und Nomad.pdfSo einfach geht modernes Roaming fuer Notes und Nomad.pdf
So einfach geht modernes Roaming fuer Notes und Nomad.pdf
 
React Native vs Ionic - The Best Mobile App Framework
React Native vs Ionic - The Best Mobile App FrameworkReact Native vs Ionic - The Best Mobile App Framework
React Native vs Ionic - The Best Mobile App Framework
 
Transcript: New from BookNet Canada for 2024: BNC SalesData and LibraryData -...
Transcript: New from BookNet Canada for 2024: BNC SalesData and LibraryData -...Transcript: New from BookNet Canada for 2024: BNC SalesData and LibraryData -...
Transcript: New from BookNet Canada for 2024: BNC SalesData and LibraryData -...
 
Zeshan Sattar- Assessing the skill requirements and industry expectations for...
Zeshan Sattar- Assessing the skill requirements and industry expectations for...Zeshan Sattar- Assessing the skill requirements and industry expectations for...
Zeshan Sattar- Assessing the skill requirements and industry expectations for...
 
JET Technology Labs White Paper for Virtualized Security and Encryption Techn...
JET Technology Labs White Paper for Virtualized Security and Encryption Techn...JET Technology Labs White Paper for Virtualized Security and Encryption Techn...
JET Technology Labs White Paper for Virtualized Security and Encryption Techn...
 
Testing tools and AI - ideas what to try with some tool examples
Testing tools and AI - ideas what to try with some tool examplesTesting tools and AI - ideas what to try with some tool examples
Testing tools and AI - ideas what to try with some tool examples
 
Varsha Sewlal- Cyber Attacks on Critical Critical Infrastructure
Varsha Sewlal- Cyber Attacks on Critical Critical InfrastructureVarsha Sewlal- Cyber Attacks on Critical Critical Infrastructure
Varsha Sewlal- Cyber Attacks on Critical Critical Infrastructure
 
Connecting the Dots for Information Discovery.pdf
Connecting the Dots for Information Discovery.pdfConnecting the Dots for Information Discovery.pdf
Connecting the Dots for Information Discovery.pdf
 
Landscape Catalogue 2024 Australia-1.pdf
Landscape Catalogue 2024 Australia-1.pdfLandscape Catalogue 2024 Australia-1.pdf
Landscape Catalogue 2024 Australia-1.pdf
 
UiPath Community: Communication Mining from Zero to Hero
UiPath Community: Communication Mining from Zero to HeroUiPath Community: Communication Mining from Zero to Hero
UiPath Community: Communication Mining from Zero to Hero
 
React JS; all concepts. Contains React Features, JSX, functional & Class comp...
React JS; all concepts. Contains React Features, JSX, functional & Class comp...React JS; all concepts. Contains React Features, JSX, functional & Class comp...
React JS; all concepts. Contains React Features, JSX, functional & Class comp...
 

Give Your Site A Boost With Memcache

  • 1. Give Your Site A Boost With Memcache Ben Ramsey ■ DC PHP Conference ■ 3 June 2008
  • 2. Software Architect at Schematic Atlanta PHP Leader Co-author of Zend PHP 5 Certification Study Guide Chatter on #phpc Give Your Site A Boost With Memcache Ben Ramsey ■ DC PHP Conference ■ 3 June 2008
  • 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.” — Wikipedia Give Your Site A Boost With Memcache Ben Ramsey ■ DC PHP Conference ■ 3 June 2008
  • 4. 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 Give Your Site A Boost With Memcache Ben Ramsey ■ DC PHP Conference ■ 3 June 2008
  • 5. Caching options Flat file caching Caching data in the database MySQL 4.x query caching Shared memory (APC) RAM disk memcached Give Your Site A Boost With Memcache Ben Ramsey ■ DC PHP Conference ■ 3 June 2008
  • 6. 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/value pairs Give Your Site A Boost With Memcache Ben Ramsey ■ DC PHP Conference ■ 3 June 2008
  • 7. 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 fragmented and allocations are guaranteed O(1) Give Your Site A Boost With Memcache Ben Ramsey ■ DC PHP Conference ■ 3 June 2008
  • 8. 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 value from the memcached server on which it was stored 5. Values time out after the specified TTL Give Your Site A Boost With Memcache Ben Ramsey ■ DC PHP Conference ■ 3 June 2008
  • 9. 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 Give Your Site A Boost With Memcache Ben Ramsey ■ DC PHP Conference ■ 3 June 2008
  • 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 Give Your Site A Boost With Memcache Ben Ramsey ■ DC PHP Conference ■ 3 June 2008
  • 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 Give Your Site A Boost With Memcache Ben Ramsey ■ DC PHP Conference ■ 3 June 2008
  • 12. www 3 memcached memcached www 1 memcached www 2 Give Your Site A Boost With Memcache Ben Ramsey ■ DC PHP Conference ■ 3 June 2008
  • 13. Deterministic failover Memcached does not provide this It is up to you to implement it If you can’t find the data in memcache, eat the look-up cost and retrieve from your data source again, storing it back to the cache Give Your Site A Boost With Memcache Ben Ramsey ■ DC PHP Conference ■ 3 June 2008
  • 14. www 3 memcached memcached www 1 Data inaccessible! memcached www 2 Recreate data; Store back to memcache Give Your Site A Boost With Memcache Ben Ramsey ■ DC PHP Conference ■ 3 June 2008
  • 15. The memcached protocol API 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 Give Your Site A Boost With Memcache Ben Ramsey ■ DC PHP Conference ■ 3 June 2008
  • 16. $> 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. $> Give Your Site A Boost With Memcache Ben Ramsey ■ DC PHP Conference ■ 3 June 2008
  • 17. 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 http://www.splinedancer.com/memcached-win32/ Give Your Site A Boost With Memcache Ben Ramsey ■ DC PHP Conference ■ 3 June 2008
  • 18. Memcached clients Perl, Python, Ruby, Java, C# C (libmemcached) PostgreSQL (access memcached from procs and triggers) MySQL (adds memcache_engine storage engine) PHP (pecl/memcache) Give Your Site A Boost With Memcache Ben Ramsey ■ DC PHP Conference ■ 3 June 2008
  • 19. 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 Give Your Site A Boost With Memcache Ben Ramsey ■ DC PHP Conference ■ 3 June 2008
  • 20. Give Your Site A Boost With Memcache Ben Ramsey ■ DC PHP Conference ■ 3 June 2008
  • 21. Features of pecl/memcache memcache.allow_failover memcache.hash_strategy memcache.hash_function memcache.protocol memcache.redundancy memcache.session_redundancy Give Your Site A Boost With Memcache Ben Ramsey ■ DC PHP Conference ■ 3 June 2008
  • 22. 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” Use something to uniquely identify keys, e.g. a method signature or an SQL statement Give Your Site A Boost With Memcache Ben Ramsey ■ DC PHP Conference ■ 3 June 2008
  • 23. Object serialization Objects are serialized before being stored to memcache: get key VALUE key 1 59 O:8:quot;stdClassquot;:2:{s:3:quot;fooquot;;s:3:quot;barquot;;s:3:quot;bazquot;;s:3:quot;quzquot;;} END Extension unserializes them before returning the object Only objects that can be serialized safely can be stored to memcache, i.e. problems with DOM, SimpleXML, etc. Give Your Site A Boost With Memcache Ben Ramsey ■ DC PHP Conference ■ 3 June 2008
  • 24. Redundancy and failover memcache.redundancy & memcache.session_redundancy Implement redundancy at the userland level? Again, memcache is not a database Give Your Site A Boost With Memcache Ben Ramsey ■ DC PHP Conference ■ 3 June 2008
  • 25. 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 Add all of your servers upon object instantiation Give Your Site A Boost With Memcache Ben Ramsey ■ DC PHP Conference ■ 3 June 2008
  • 26. 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 Give Your Site A Boost With Memcache Ben Ramsey ■ DC PHP Conference ■ 3 June 2008
  • 27. 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 Give Your Site A Boost With Memcache Ben Ramsey ■ DC PHP Conference ■ 3 June 2008
  • 28. 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 = quot;tcp://192.168.1.10:11211,tcp:// 192.168.1.11:11211,tcp://192.168.1.12:11211quot; Store sessions to both the database and memcache Write your own session handler that stores to the database and memcache Give Your Site A Boost With Memcache Ben Ramsey ■ DC PHP Conference ■ 3 June 2008
  • 29. www 3 memcached memcached www 1 Session inaccessible! Need to memcached recreate the session! www 2 Give Your Site A Boost With Memcache Ben Ramsey ■ DC PHP Conference ■ 3 June 2008
  • 30. For more information... http://danga.com/memcached/ http://pecl.php.net/package/memcache http://www.socialtext.net/memcached/ My blog: http://benramsey.com/ Give Your Site A Boost With Memcache Ben Ramsey ■ DC PHP Conference ■ 3 June 2008