Effectice Caching w/ PHP + Caching
Upcoming SlideShare
Loading in...5
×
 

Effectice Caching w/ PHP + Caching

on

  • 12,579 views

Scaling your Database or other resources your website needs can be...

Scaling your Database or other resources your website needs can be
complicated. Why not reduce their load instead? That is where memcached can
help. Developed by the creators of LiveJournal, memcached is a light weight
application that does one thing extremely well: caching data in memory and
retrieving it very fast.

This presentation will cover the basics of memcached and then explain some
caching theory and best practices for using memcache. Topics to be covered
at:

- What is Memcached?
- How can it help my website?
- Installing
- Configuring & Running
- Basic Workflow
- Best Practices w/ Keys
- What to Cache
- When to Cache
- Expiring Data
- Wrapping Caches with a Class
- Security
- Question & Answer Session

Justin Carmony has worked in web development professionally for the last
five years. With emphasis on PHP, .NET, and Web Services, he has worked on
projects ranging from simple websites to complex communications between
thousands of remote systems. He currently is working as an independent
contractor & private consultant. If you have any questions, comments, or
curiosities you can contact him (justin AT justincarmony DOT com) or read
about his latest endeavors at his blog (www.justincarmony.com/blog).

Statistics

Views

Total Views
12,579
Views on SlideShare
11,023
Embed Views
1,556

Actions

Likes
9
Downloads
181
Comments
0

7 Embeds 1,556

http://www.justincarmony.com 1508
http://www.slideshare.net 31
http://static.slidesharecdn.com 7
http://www.php.rk.edu.pl 6
http://webcache.googleusercontent.com 2
http://stage.justincarmony.com 1
http://translate.googleusercontent.com 1
More...

Accessibility

Categories

Upload Details

Uploaded via as Apple Keynote

Usage Rights

© All Rights Reserved

Report content

Flagged as inappropriate Flag as inappropriate
Flag as inappropriate

Select your reason for flagging this presentation as inappropriate.

Cancel
  • Full Name Full Name Comment goes here.
    Are you sure you want to
    Your message goes here
    Processing…
Post Comment
Edit your comment

Effectice Caching w/ PHP + Caching Effectice Caching w/ PHP + Caching Presentation Transcript

  • EFFECTIVE CACHING WITH PHP & MEMCACHED by Justin Carmony
  • ABOUT ME • Full Time Web Developer & Consultant • Worked with LAMP & .NET Solutions • Blog - http://www.justincarmony.com/blog/ • Current Projects:
  • ABOUT PRESENTATION On-Topic Questions During Presentation Q & A Session After Presentation Feel Free to Email Me Questions: justin@justincarmony.com
  • WHAT IS MEMCACHED?
  • ABOUT MEMCACHED
  • ABOUT MEMCACHED Developed by LiveJournal’s Developers
  • ABOUT MEMCACHED Developed by LiveJournal’s Developers Primary Function: Relieve Database Load (Mainly Reads)
  • ABOUT MEMCACHED Developed by LiveJournal’s Developers Primary Function: Relieve Database Load (Mainly Reads) Can Scale Across Multiple Servers
  • ABOUT MEMCACHED Developed by LiveJournal’s Developers Primary Function: Relieve Database Load (Mainly Reads) Can Scale Across Multiple Servers Giant “Hash Table” or “Array”
  • ABOUT MEMCACHED Developed by LiveJournal’s Developers Primary Function: Relieve Database Load (Mainly Reads) Can Scale Across Multiple Servers Giant “Hash Table” or “Array” Stores Data in Memory - Extremely Fast
  • WHY WE CACHE
  • CONCEPT OF CACHING
  • CONCEPT OF CACHING • Resource that is Struggling Website Resource Application
  • CONCEPT OF CACHING • Resource that is Struggling Website • Introduce Cache to Help Resource Application Cache
  • CONCEPT OF CACHING • Resource that is Struggling Website • Introduce Cache to Help Resource Application • Store “Reliable” Data in Cache Cache
  • CONCEPT OF CACHING • Resource that is Struggling Website • Introduce Cache to Help Resource Application • Store “Reliable” Data in Cache • Check Cache Before Hitting Resource Cache
  • CONCEPT OF CACHING • Resource that is Struggling Website • Introduce Cache to Help Resource Application • Store “Reliable” Data in Cache • Check Cache Before Hitting Resource Cache • Resource Types: DB, Web Service, XML, Files, Etc.
  • THE DATABASE
  • THE DATABASE • Scaling is Complicated
  • THE DATABASE • Scaling is Complicated • Its because what makes databases great: ACID.
  • THE DATABASE • Scaling is Complicated • Its because what makes databases great: ACID. • What about SQL’s Internal Caching?
  • THE DATABASE • Scaling is Complicated • Its because what makes databases great: ACID. • What about SQL’s Internal Caching? • Less Load on DB is Good
  • HOW DOES IT IMPROVE PERFORMANCE?
  • DATING DNA PERFORMANCE BOOST Before After Daily New Registrations 100 500 HTTP Requests Per Second ~ 36 r/s ~150 r/s AVG Database CPU ~ 73% ~32% # Queries Per Second ~ 2,200 ~1,700 AVG Page Load Time 2 - 5 seconds 0.01 - 0.4 seconds * Note - Several Performance Changes Made, Not 100% Due to Memcached
  • LIVE MEMCACHED STATS
  • INSTALLING & RUNNING MEMCACHED
  • INSTALLING • Linux - Aptitude, Yum, RPM, Compile from Source, etc... • Mac OS X - Compile Only • Windows - Downloadable Binaries • Its pretty simple!
  • RUNNING • No Configuration Files • Just a few command line options: memcached -d -m 2048 -l 127.0.0.1 -p 11211
  • BASIC CACHE FLOW
  • CONNECT <?php // Create New Memcache Instance $memcache = new Memcache(); // Add Memcache Server to Connection Pool $memcache->addServer('127.0.0.1', 11211); // ... continue code ...
  • GET & SET DATA // Try to Get the $my_name = $memcache->get('my_name'); if($my_name === false) { $my_name = 'Justin Carmony'; $memcache->set('my_name', $my_name, false, 60); } echo $my_name; // output: Justin Carmony
  • “DELETING” DATA // Lets say we don't like Justin anymore... $memcache->delete('my_name'); $value = $memcache->get('my_name'); // returns false
  • CACHING THEORY ( WHERE, WHAT, WHEN, & HOW)
  • WHERE TO CACHE
  • IDENTIFYING WHAT TO CACHE
  • IDENTIFYING WHAT TO CACHE ‣ High Demand
  • IDENTIFYING WHAT TO CACHE ‣ High Demand ‣ Expensive
  • IDENTIFYING WHAT TO CACHE ‣ High Demand ‣ Expensive ‣ Large in Size
  • IDENTIFYING WHAT TO CACHE ‣ High Demand ‣ Expensive ‣ Large in Size ‣ Common
  • IDENTIFYING WHAT TO CACHE ‣ High Demand ‣ Expensive ‣ Large in Size ‣ Common The Best Cacheable Data with Highest Performance ROI Fits Multiple Characteristics
  • TIPS FOR FINDING CACHEABLE DATA
  • TIPS FOR FINDING CACHEABLE DATA ‣ Monitor Queries
  • TIPS FOR FINDING CACHEABLE DATA ‣ Monitor Queries ‣ Output Queries
  • TIPS FOR FINDING CACHEABLE DATA ‣ Monitor Queries ‣ Output Queries ‣ Monitor Page Loads
  • TIPS FOR FINDING CACHEABLE DATA ‣ Monitor Queries ‣ Output Queries ‣ Monitor Page Loads ‣ Monitor Web Analytics
  • TIPS FOR FINDING CACHEABLE DATA ‣ Monitor Queries ‣ Output Queries ‣ Monitor Page Loads ‣ Monitor Web Analytics ‣ Brainstorming
  • WHAT TO CACHE
  • OUTPUT CACHING Capture Output Buffer When to Use Output Caching: - Page Has High Load - Expensive to Generate - Easier to Cache over Data
  • OUTPUT CACHING Capture Output Buffer When to Use Output Caching: - Page Has High Load - Expensive to Generate - Easier to Cache over Data
  • OUTPUT BUFFER EXAMPLE // Output Buffer Cache $output = $memcache->get('my_html'); if(!$output) { ob_start(); // Start Capture ?> <div id="main">Hello World!</div> <!-- Insert Some Crazy HTML Code --> <?php $output = ob_get_contents(); ob_end_clean(); $memcache->set('my_html', $output, false, 15 * 60); } echo $output;
  • DATA CACHING Create a Class to Cache Use Factory Methods to Retrieve Use When Use: - Data Used Frequently - Displayed Different - Easier from Cache than other Sources
  • WHEN TO EXPIRE
  • TIMEOUT EXPIRATION Settings a Lower Timeout Great for Summaries Okay to be Kinda Out of Date “Quick & Dirty” Optimizations Output + Timeout Common
  • EVENT EXPIRATION Data is Infrequently Updated Data is Time Critical - Cannot Be Out of Date Data + Event Common
  • HOW TO CACHE
  • IT’S ALL ABOUT YOUR KEYS Keys MUST Be Unique Prefix Cache Types (i.e. prflinfo_ for ProfileInfo) SHA256 / MD5 Identifiers Example: ProfileInfo for User ID 1337: prflinfo_e48e13207341b6bffb7fb1622282247b
  • WRAP YOUR CACHE W/ CLASS Pick a Cacheable Piece of Information Create a Class For That Cache Create Methods For: ‣ Generate Key Name ‣ Get & Set ‣ Destroy / Delete
  • class ProfileInformation { public $user_id = null; public $first_name = null; public $email_address = null; public $profile_img = null; public $city = null; public $state = null; public $age = null; private function __construct($user_id) { $this->user_id = $user_id; $sql = "SELECT * FROM users WHERE user_id = '$user_id'"; $p_data = DBI::fetchObject($sql); $this->first_name = $p_data->first_name; $this->email_address = $p_data->email_address; $this->age = xDate::GetAge($p_data->birthdate); // .. Set More Information .. } // .. more .. }
  • class ProfileInformation { // .. more .. static public function GetProfile($user_id) { // Try to get it from the cache $profile = null; $profile = self::GetCache($user_id); if(!$profile) { $profile = new ProfileInformation($user_id); self::SetCache($user_id, $profile); } return $profile; } // ... more ... }
  • class ProfileInformation { // .. more .. static protected function GetCacheName($user_id) { return 'profile_'.hash('sha256',"user_".$user_id."_".$user_id); } // ... more ... }
  • class ProfileInformation { // .. more .. static protected function GetCache($user_id) { $name = self::GetCacheName($user_id); $profile = null; $memcache = MemcacheCluster::GetInstance(); $profile = $memcache->get($name); if(!$profile) { return null; } return $profile; } // ... more ... }
  • class ProfileInformation { // .. more .. static protected function SetCache($user_id, $data) { $name = self::GetCacheName($user_id); $memcache = MemcacheCluster::GetInstance(); $profile = $memcache->set($name, $data, false, 24 * 60 * 60); } public static function DestroyCache($user_id) { $name = self::GetCacheName($user_id); $memcache = MemcacheCluster::GetInstance(); $profile = $memcache->delete($name); } // End Of Class }
  • require_once 'ProfileInformation.class.php'; $user_id = 1337; // Incorrect Method $profile = new ProfileInformation($user_id); // Throws Error // Correct Method $profile = ProfileInformation::GetProfile($user_id); echo $profile->first_name;
  • FINAL THOUGHTS
  • COMMON PITFALLS • Caching Only Optimization - Ignoring Other Inefficiencies • Cache Offline == Catastrophic Failure • Poor Key Choices • Inability to easily invalidate specific Cache Entries • Caching SQL Queries
  • PITFALL: QUERY CACHE <?php $sql = "SELECT * FROM users WHERE id = 5"; $result = $mem->get(md5($sql)); if(!$result) { // Execute and get the result of the query in an array $result = Database::FetchArray($sql); // set the timeout to 4 hours $mem->set(md5($sql), $result, 0, 4 * 60 * 60); } ?>
  • SECURITY No Real Security for Memcached --listen Not Super Secure / Configurable Limit Access at Network Level IPTables / Firewalls / Internal Network
  • MISCELLANEOUS THINGS Memcache Library vs Memcached Library Where can I find out More? - My Blog: Search Memcached - Google Memcached - PHP Documentation
  • QUESTIONS?
  • SHAMELESS PLUG: October 8-10, 2009 | www.utosc.com
  • THANK YOU Website www.justincarmony.com Email justin@justincarmony.com Twitter JustinCarmony Skype JustinCarmony IRC irc.freenode.net #uphpu