SlideShare una empresa de Scribd logo
1 de 68
Descargar para leer sin conexión
Memcached
http://download.tangent.org/talks/Memcached%20Study.pdf
memcached is a high-performance, distributed memory object
caching system, generic in nature, but intended for use in
speeding up dynamic web applications by alleviating
database load.
Who?
• Facebook
• Yahoo
• Amazon
• LiveJournal
• Mixi
• ...
Why?
(aka why would I...)‫‏‬
LiveJournal

• Origin of memcached
• 30G of cache. Terabytes of data
• Writes to DB based on reads from the DB,
  not cache
Mixi

• Memcached on dedicated servers
• 100 servers in production (reuse old
  MySQL Servers)

• 4 gigs of Memory
• 15,000 qps / 400Mbps throughput
Patrick Lenz
Eins.de
http://poocs.net
Grazr
100+ Nodes
2gigs a Node   Processing



                            Incoming Data




  Memcached
How
Server

• Slab Allocator
• Libevent based
• Simple Protocol (no xml)
• Server has Internal Hash Table
• Servers know nothing about each other
Clients


•   Client hashes Key to Server List (distribution)‫‏‬

•   Serializes the Object (server just likes byte arrays)‫‏‬

•   Compresses data
Consistent Hash
So what should I ask?

• How do I dump data?
• How is it redundant? *
• How does it handle failover?*
• How does it authenticate?
Details on the Server?

• set/get/replace/add
• append/prepend
• increment/decrement
• cas (compare and swap atomic!)‫‏‬
• stats (detail)‫‏‬
Platforms

• FreeBSD and Linux are top tier
• Windows exists
• Solaris (as of 1.2.5)‫‏‬
• OSX Good Support
Examples
Ruby
 # Set up client object

 require 'memcache'
 servers = ['127.0.0.1:43042', '127.0.0.1:43043']
 CACHE = MemCache.new(servers, :namespace => 'my_app')
# Get; fall through to Rails' MySQL load if missing

 key = quot;recent_postsquot;
 # Try to get; returns nil on failure
 posts = CACHE.get(key)

 unless posts
   # Load from DB
   posts = Post.find(:all, :limit => 10, :order => 'id DESC')
   # Cache the new value, which is automatically serialized
   CACHE.set(key), posts, 60
 end
# Ghetto locking implementation for memcache-client
 # from http://fauna.rubyforge.org/svn/interlock/trunk/lib/interlock/lock.rb

 def lock(key, lock_expiry = 30, retries = 5)
   retries.times do |count|
     # Try to acquire the lock
     response = CACHE.add(quot;lock:#{key}quot;, quot;Locked by #{Process.pid}quot;, lock_expiry)
     if response == quot;STOREDrnquot;
       # We got it
       begin
         # Yield the current value to the closure
         value = yield(CACHE.get(key))
         # Set the new value returned from the closure CACHE.set(key, value)
         # We're done ('ensure' block will still run)
         return value
       ensure
         # Release the lock
         CACHE.delete(quot;lock:#{key}quot;)
       end
     else
       # Exponentially back off requests if the lock can't be acquired
       sleep((2**count) / 2.0)
     end
   end
   # We waited and waited but our turn never came
   raise MemCacheError, quot;Couldn't acquire lock for #{key}quot;
 end
Perl
sub get_foo_object {
   my $foo_id = int(shift);
   my $obj = FooClass::MemCache->get(quot;foo:$foo_idquot;);
   return $obj if $obj;

    $obj = FooClass::db->selectrow_hashref(quot;SELECT .... FROM foo f, bar b quot;.
                                    quot;WHERE ... AND f.fooid=$foo_idquot;);
    FooClass::MemCache->set(quot;foo:$foo_idquot;, $obj);
    return $obj;
}
PHP
/**
 * Initalize Memcache object and add local server 127.0.0.1 using port 11211
 */
$cache = new Memcache;
$cache->addServer(quot;127.0.0.1quot;,11211);
/** Look in cache, if not found, set object (misses null) **/
if (!$user = $cache->get($user_key)) {

    /**
     * Set object with expire of 1 hour and no compression
     */
    $cache->set($user_key,$value,NULL, $expire);
    $user = $value;
}
/* Get user counter value (does not handle add fail) */
if (!$counter = $cache->get($counter_key)) {
  /* No counter, set to 1 */
  $cache->add($counter_key,1);
} else {
  /* Increment by 1 */
  $cache->increment($counter_key);
}
/* Print out stats from memcached server */
print_r($cache->getStats());

/* Print out extended stats from memcached server */
print_r($cache->getExtendedStats());

/* Flush memcached (bad idea in production)*/
var_dump($cache->flush());
C
libmemcached

• C/C++ (many language wrappers)
• Multiget support
• Async/Sync Modes (including buffered)
• Replicated
• Read Through Cache Support
memcached_st *memc;
memcached_return rc;
memc= memcached_create(NULL);
...do stuff...
memcached_free(memc);
memcached_server_st *servers;
memcached_st *memc= memcached_create(NULL);
char servername[]= quot;0.example.comquot;;
servers= memcached_server_list_append(NULL, servername, 400, &rc);
for (x= 0; x < 20; x++)
{
  char buffer[SMALL_STRING_LEN];
  snprintf(buffer, SMALL_STRING_LEN, quot;%u.example.comquot;, 400+x);
  servers= memcached_server_list_append(servers, buffer, 401, &rc);
}
rc= memcached_server_push(memc, servers);
memcached_server_free(servers);
memcached_free(memc);
char *key= quot;fooquot;;
char *value;
size_t value_length= 8191;
unsigned int x;
value = (char*)malloc(value_length);

for (x= 0; x < value_length; x++)
  value[x] = (char) (x % 127);
for (x= 0; x < 1; x++)
{
  rc= memcached_set(memc, key, strlen(key),
  value, value_length,
  (time_t)0, (uint32_t)0);
  assert(rc == MEMCACHED_SUCCESS);
}
free(value);
memcached_return rc;
char *keys[]= {quot;fudgequot;, quot;sonquot;, quot;foodquot;};
size_t key_length[]= {5, 3, 4};
uint32_t flags;
char return_key[MEMCACHED_MAX_KEY];
size_t return_key_length;
char *return_value;
size_t return_value_length;

rc= memcached_mget(memc, keys, key_length, 3);

while ((return_value= memcached_fetch(memc, return_key, &return_key_length,
                       &return_value_length, &flags, &rc)))
{
  free(return_value);
}
Memcached foo;
char *value_set= quot;Data for server Aquot;;
char *master_key_a= quot;server-aquot;;
char *master_key_b= quot;server-bquot;;
char *key= quot;xyzquot;;
char *value;
size_t value_length;

foo.set_by_key(master_key_a, key, value_set, strlen(value_set));
value= foo.get_by_key(master_key_a, key, &value_length);

assert((memcmp(value, value_set, value_length) == 0));

value= foo.get_by_key(master_key_b, key, &value_length);
assert((memcmp(value, value_set, value_length) == 0));

return 0;
Application Integration
Postgres Integration


• pgmemcache()‫‏‬
• Same as MySQL’s... but we don’t know
  much about it :)
lighttpd/mod_memcache
• Cache files from disk
• Specify mime/types
• Create Expire Times
Apache (mod_memcached)‫‏‬
• CAS operations exposed
• GET/PUT/DELETE operations
• Still Alpha
• (pandoraport.com!)
NGINX
• Support variable Time outs
• Based on Perl
• http://wiki.codemongers.com/
  NginxHttpMemcachedModule

• http://www.igvita.com/2008/02/11/nginx-
  and-memcached-a-400-boost/
Memcached Functions
    for MySQL
Overview...

• Uses UDF API and libmemcached
• Manage memcached Cluster via SQL
• Read through Cache
• Write through Cache
Installation

•   CREATE FUNCTION memc_servers_add RETURNS INT SONAME
    quot;libmemcached_functions_mysql.soquot;;

•   CREATE FUNCTION memc_set RETURNS INT SONAME
    quot;libmemcached_functions_mysql.soquot;;

•   CREATE FUNCTION memc_get RETURNS STRING SONAME
    quot;libmemcached_functions_mysql.soquot;;
Functions Available
• memc_servers_set();
• memc_servers_behavior_set()
• memc_set()
• memc_get()
• memc_append()
• memc_prepend()
Setting via SELECT
select id, url, memc_set(concat('feeds', md5(url)), url) from feeds;

select memc_get(concat('feeds', md5(url))) from feeds;
+-------------------------------------------------------+
| memc_get(concat('feeds', md5(url)))                   |
+-------------------------------------------------------+
| http://feeds.feedburner.com/littlegreenfootballs/Ilds |
| http://del.icio.us/rss/jacomien                       |
| http://del.icio.us/rss/tags/rmj20                     |
| http://www.jihadwatch.org/index.rdf                   |
| http://www.connotea.org/rss/user/rmj20                |
| http://devblog.grazr.com/?feed=rss2x                  |
| http://feeds.feedburner.com/littlegreenfootballs/kyeH |
+-------------------------------------------------------+
Trigger
DROP TRIGGER IF EXISTS feed_insert;
CREATE TRIGGER feed_insert BEFORE INSERT ON feeds FOR EACH ROW
BEGIN   SET @mm= memc_set(concat('feeds:',md5(NEW.url)),
NEW.url);END |


insert into feeds (url) values ('http://grazr.com/feedlist.xml');

select memc_get(concat('feeds:', md5('http://grazr.com/feedlist.xml')));
+------------------------------------------------------------------+|
memc_get(concat('feeds:', md5('http://grazr.com/feedlist.xml'))) |
+------------------------------------------------------------------+|
http://grazr.com/feedlist.xml                                    |
+------------------------------------------------------------------+
Memcached Replication
    via MySQL

INSERT INTO table_a VALUES (“key”, “value”, “values”);
INSERT INTO blackhole_table VALUES (memc_delete(“key”));
Implementation
Limits

• Key Size (250 bytes)‫‏‬
• Data Size (under 1 megabyte)‫‏‬
• 32bit/64bit (maximum size of the process)‫‏‬
• Maxbytes (limits item cache, not everything!)‫‏‬
LRU
• Least recently accessed items are up for
  eviction and can be seen

• One LRU exists per “slab class”
• LRU evictions don't need to be common
Threads
• You might not need them (yet!)‫‏‬
• Great for large instances (16G+)‫‏‬
• Also great for large multiget requests
• Scales okay now. Will get better in the
  future
Slab Allocator

• Memory permanently allocated from OS
• Classes created by chunk size
• Cannot (presently) reassign slab pages
• Carefully use 'stats sizes' to test efficiency
Tools
Protocol

• Telnet’able (see doc/protocol.txt)‫‏‬
• All commands are text based (binary soon)‫‏‬
• Store commands are binary (no escaping)‫‏‬
memcached-tool

• Example minimal monitoring tool
• Shows details of server stats, slabs
• memcached-tool 10.0.0.1 display
• memcached-tool 10.0.0.1 stats
libmemcached Tools

• memcp
• memrm
• memstat
• memslap (hahahhaha)‫‏‬
MRTG


• Plenty of interfaces monitored
• Old technology, been around forever
...and others

• Cacti
 • http://dealnews.com/developers/cacti/
    memcached.html
• Ganglia
 • http://ganglia.wiki.sourceforge.net/
Current Connections
Requests Per Second
Future
1.2.5 Release
• Multi Interface Support
• UDP all the time
• noreply (SET with no response)
• Solaris Support (large memory page
  support)

• getimeofday() optimizations
• IPV6
Future
• Binary Protocol
• Multiple Engine Support
 • Char based
 • Durable
 • Queue
 • Highly Threaded
More Resources...
• http://danga.com/memcached/
• #memcached on Freenode
• http://tangent.org/552/libmemcached.html
• http://groups.google.com/groups/
  memcached

• http://dev.mysql.com/doc/refman/5.1/en/ha-
  memcached.html

Más contenido relacionado

La actualidad más candente

Caching with Varnish
Caching with VarnishCaching with Varnish
Caching with Varnishschoefmax
 
Introduction to Redis
Introduction to RedisIntroduction to Redis
Introduction to RedisDvir Volk
 
cache concepts and varnish-cache
cache concepts and varnish-cachecache concepts and varnish-cache
cache concepts and varnish-cacheMarc Cortinas Val
 
Varnish Configuration Step by Step
Varnish Configuration Step by StepVarnish Configuration Step by Step
Varnish Configuration Step by StepKim Stefan Lindholm
 
Varnish http accelerator
Varnish http acceleratorVarnish http accelerator
Varnish http acceleratorno no
 
Automating complex infrastructures with Puppet
Automating complex infrastructures with PuppetAutomating complex infrastructures with Puppet
Automating complex infrastructures with PuppetKris Buytaert
 
Apache Traffic Server & Lua
Apache Traffic Server & LuaApache Traffic Server & Lua
Apache Traffic Server & LuaKit Chan
 
NginX - good practices, tips and advanced techniques
NginX - good practices, tips and advanced techniquesNginX - good practices, tips and advanced techniques
NginX - good practices, tips and advanced techniquesClaudio Borges
 
Memcached: What is it and what does it do?
Memcached: What is it and what does it do?Memcached: What is it and what does it do?
Memcached: What is it and what does it do?Brian Moon
 
Practicing Continuous Deployment
Practicing Continuous DeploymentPracticing Continuous Deployment
Practicing Continuous Deploymentzeeg
 
Content Caching with NGINX and NGINX Plus
Content Caching with NGINX and NGINX PlusContent Caching with NGINX and NGINX Plus
Content Caching with NGINX and NGINX PlusKevin Jones
 
PHP Performance with APC + Memcached
PHP Performance with APC + MemcachedPHP Performance with APC + Memcached
PHP Performance with APC + MemcachedFord AntiTrust
 
NGINX High-performance Caching
NGINX High-performance CachingNGINX High-performance Caching
NGINX High-performance CachingNGINX, Inc.
 
Scalable Architecture 101
Scalable Architecture 101Scalable Architecture 101
Scalable Architecture 101ConFoo
 

La actualidad más candente (20)

Caching with Varnish
Caching with VarnishCaching with Varnish
Caching with Varnish
 
Introduction to Redis
Introduction to RedisIntroduction to Redis
Introduction to Redis
 
Cassandra as Memcache
Cassandra as MemcacheCassandra as Memcache
Cassandra as Memcache
 
cache concepts and varnish-cache
cache concepts and varnish-cachecache concepts and varnish-cache
cache concepts and varnish-cache
 
Varnish Configuration Step by Step
Varnish Configuration Step by StepVarnish Configuration Step by Step
Varnish Configuration Step by Step
 
Memcache
MemcacheMemcache
Memcache
 
Varnish http accelerator
Varnish http acceleratorVarnish http accelerator
Varnish http accelerator
 
Varnish - PLNOG 4
Varnish - PLNOG 4Varnish - PLNOG 4
Varnish - PLNOG 4
 
Varnish 4 cool features
Varnish 4 cool featuresVarnish 4 cool features
Varnish 4 cool features
 
Caching
CachingCaching
Caching
 
Varnish intro
Varnish introVarnish intro
Varnish intro
 
Automating complex infrastructures with Puppet
Automating complex infrastructures with PuppetAutomating complex infrastructures with Puppet
Automating complex infrastructures with Puppet
 
Apache Traffic Server & Lua
Apache Traffic Server & LuaApache Traffic Server & Lua
Apache Traffic Server & Lua
 
NginX - good practices, tips and advanced techniques
NginX - good practices, tips and advanced techniquesNginX - good practices, tips and advanced techniques
NginX - good practices, tips and advanced techniques
 
Memcached: What is it and what does it do?
Memcached: What is it and what does it do?Memcached: What is it and what does it do?
Memcached: What is it and what does it do?
 
Practicing Continuous Deployment
Practicing Continuous DeploymentPracticing Continuous Deployment
Practicing Continuous Deployment
 
Content Caching with NGINX and NGINX Plus
Content Caching with NGINX and NGINX PlusContent Caching with NGINX and NGINX Plus
Content Caching with NGINX and NGINX Plus
 
PHP Performance with APC + Memcached
PHP Performance with APC + MemcachedPHP Performance with APC + Memcached
PHP Performance with APC + Memcached
 
NGINX High-performance Caching
NGINX High-performance CachingNGINX High-performance Caching
NGINX High-performance Caching
 
Scalable Architecture 101
Scalable Architecture 101Scalable Architecture 101
Scalable Architecture 101
 

Destacado

Behind the Scenes at LiveJournal: Scaling Storytime
Behind the Scenes at LiveJournal: Scaling StorytimeBehind the Scenes at LiveJournal: Scaling Storytime
Behind the Scenes at LiveJournal: Scaling StorytimeSergeyChernyshev
 
Memcached, presented to LCA2010
Memcached, presented to LCA2010Memcached, presented to LCA2010
Memcached, presented to LCA2010Mark Atwood
 
Implementing High Availability Caching with Memcached
Implementing High Availability Caching with MemcachedImplementing High Availability Caching with Memcached
Implementing High Availability Caching with MemcachedGear6
 
Facebook architecture presentation: scalability challenge
Facebook architecture presentation: scalability challengeFacebook architecture presentation: scalability challenge
Facebook architecture presentation: scalability challengeCristina Munoz
 
facebook architecture for 600M users
facebook architecture for 600M usersfacebook architecture for 600M users
facebook architecture for 600M usersJongyoon Choi
 

Destacado (6)

Cache design
Cache design Cache design
Cache design
 
Behind the Scenes at LiveJournal: Scaling Storytime
Behind the Scenes at LiveJournal: Scaling StorytimeBehind the Scenes at LiveJournal: Scaling Storytime
Behind the Scenes at LiveJournal: Scaling Storytime
 
Memcached, presented to LCA2010
Memcached, presented to LCA2010Memcached, presented to LCA2010
Memcached, presented to LCA2010
 
Implementing High Availability Caching with Memcached
Implementing High Availability Caching with MemcachedImplementing High Availability Caching with Memcached
Implementing High Availability Caching with Memcached
 
Facebook architecture presentation: scalability challenge
Facebook architecture presentation: scalability challengeFacebook architecture presentation: scalability challenge
Facebook architecture presentation: scalability challenge
 
facebook architecture for 600M users
facebook architecture for 600M usersfacebook architecture for 600M users
facebook architecture for 600M users
 

Similar a Optimize Database Performance with Memcached

Caching and tuning fun for high scalability @ FOSDEM 2012
Caching and tuning fun for high scalability @ FOSDEM 2012Caching and tuning fun for high scalability @ FOSDEM 2012
Caching and tuning fun for high scalability @ FOSDEM 2012Wim 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
 
4069180 Caching Performance Lessons From Facebook
4069180 Caching Performance Lessons From Facebook4069180 Caching Performance Lessons From Facebook
4069180 Caching Performance Lessons From Facebookguoqing75
 
Facebook的缓存系统
Facebook的缓存系统Facebook的缓存系统
Facebook的缓存系统yiditushe
 
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 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
 
PECL Picks - Extensions to make your life better
PECL Picks - Extensions to make your life betterPECL Picks - Extensions to make your life better
PECL Picks - Extensions to make your life betterZendCon
 
WordPress Performance & Scalability
WordPress Performance & ScalabilityWordPress Performance & Scalability
WordPress Performance & ScalabilityJoseph Scott
 
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
 
php & performance
 php & performance php & performance
php & performancesimon8410
 
Caching and tuning fun for high scalability @ PHPTour
Caching and tuning fun for high scalability @ PHPTourCaching and tuning fun for high scalability @ PHPTour
Caching and tuning fun for high scalability @ PHPTourWim Godden
 
0628阙宏宇
0628阙宏宇0628阙宏宇
0628阙宏宇zhu02
 
Railsconf2011 deployment tips_for_slideshare
Railsconf2011 deployment tips_for_slideshareRailsconf2011 deployment tips_for_slideshare
Railsconf2011 deployment tips_for_slidesharetomcopeland
 
Salesforce at Stacki Atlanta Meetup February 2016
Salesforce at Stacki Atlanta Meetup February 2016Salesforce at Stacki Atlanta Meetup February 2016
Salesforce at Stacki Atlanta Meetup February 2016StackIQ
 
X64服务器 lnmp服务器部署标准 new
X64服务器 lnmp服务器部署标准 newX64服务器 lnmp服务器部署标准 new
X64服务器 lnmp服务器部署标准 newYiwei Ma
 

Similar a Optimize Database Performance with Memcached (20)

Caching and tuning fun for high scalability @ FOSDEM 2012
Caching and tuning fun for high scalability @ FOSDEM 2012Caching and tuning fun for high scalability @ FOSDEM 2012
Caching and tuning fun for high scalability @ FOSDEM 2012
 
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
 
4069180 Caching Performance Lessons From Facebook
4069180 Caching Performance Lessons From Facebook4069180 Caching Performance Lessons From Facebook
4069180 Caching Performance Lessons From Facebook
 
Facebook的缓存系统
Facebook的缓存系统Facebook的缓存系统
Facebook的缓存系统
 
Pecl Picks
Pecl PicksPecl Picks
Pecl Picks
 
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 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
 
PECL Picks - Extensions to make your life better
PECL Picks - Extensions to make your life betterPECL Picks - Extensions to make your life better
PECL Picks - Extensions to make your life better
 
WordPress Performance & Scalability
WordPress Performance & ScalabilityWordPress Performance & Scalability
WordPress Performance & Scalability
 
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
 
Memcache
MemcacheMemcache
Memcache
 
php & performance
 php & performance php & performance
php & performance
 
All The Little Pieces
All The Little PiecesAll The Little Pieces
All The Little Pieces
 
Caching and tuning fun for high scalability @ PHPTour
Caching and tuning fun for high scalability @ PHPTourCaching and tuning fun for high scalability @ PHPTour
Caching and tuning fun for high scalability @ PHPTour
 
0628阙宏宇
0628阙宏宇0628阙宏宇
0628阙宏宇
 
Railsconf2011 deployment tips_for_slideshare
Railsconf2011 deployment tips_for_slideshareRailsconf2011 deployment tips_for_slideshare
Railsconf2011 deployment tips_for_slideshare
 
Salesforce at Stacki Atlanta Meetup February 2016
Salesforce at Stacki Atlanta Meetup February 2016Salesforce at Stacki Atlanta Meetup February 2016
Salesforce at Stacki Atlanta Meetup February 2016
 
X64服务器 lnmp服务器部署标准 new
X64服务器 lnmp服务器部署标准 newX64服务器 lnmp服务器部署标准 new
X64服务器 lnmp服务器部署标准 new
 
Osol Pgsql
Osol PgsqlOsol Pgsql
Osol Pgsql
 
Puppet Camp 2012
Puppet Camp 2012Puppet Camp 2012
Puppet Camp 2012
 

Último

Gen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfGen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfAddepto
 
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptx
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptxPasskey Providers and Enabling Portability: FIDO Paris Seminar.pptx
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptxLoriGlavin3
 
What is DBT - The Ultimate Data Build Tool.pdf
What is DBT - The Ultimate Data Build Tool.pdfWhat is DBT - The Ultimate Data Build Tool.pdf
What is DBT - The Ultimate Data Build Tool.pdfMounikaPolabathina
 
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
 
Moving Beyond Passwords: FIDO Paris Seminar.pdf
Moving Beyond Passwords: FIDO Paris Seminar.pdfMoving Beyond Passwords: FIDO Paris Seminar.pdf
Moving Beyond Passwords: FIDO Paris Seminar.pdfLoriGlavin3
 
WordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your BrandWordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your Brandgvaughan
 
Digital Identity is Under Attack: FIDO Paris Seminar.pptx
Digital Identity is Under Attack: FIDO Paris Seminar.pptxDigital Identity is Under Attack: FIDO Paris Seminar.pptx
Digital Identity is Under Attack: FIDO Paris Seminar.pptxLoriGlavin3
 
Take control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test SuiteTake control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test SuiteDianaGray10
 
DevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsDevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsSergiu Bodiu
 
SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024Lorenzo Miniero
 
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptxThe Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptxLoriGlavin3
 
How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.Curtis Poe
 
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
 
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
 
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptxThe Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptxLoriGlavin3
 
What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024Stephanie Beckett
 
Connect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationConnect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationSlibray Presentation
 
Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Commit University
 
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024BookNet Canada
 
"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr BaganFwdays
 

Último (20)

Gen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfGen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdf
 
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptx
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptxPasskey Providers and Enabling Portability: FIDO Paris Seminar.pptx
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptx
 
What is DBT - The Ultimate Data Build Tool.pdf
What is DBT - The Ultimate Data Build Tool.pdfWhat is DBT - The Ultimate Data Build Tool.pdf
What is DBT - The Ultimate Data Build Tool.pdf
 
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
 
Moving Beyond Passwords: FIDO Paris Seminar.pdf
Moving Beyond Passwords: FIDO Paris Seminar.pdfMoving Beyond Passwords: FIDO Paris Seminar.pdf
Moving Beyond Passwords: FIDO Paris Seminar.pdf
 
WordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your BrandWordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your Brand
 
Digital Identity is Under Attack: FIDO Paris Seminar.pptx
Digital Identity is Under Attack: FIDO Paris Seminar.pptxDigital Identity is Under Attack: FIDO Paris Seminar.pptx
Digital Identity is Under Attack: FIDO Paris Seminar.pptx
 
Take control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test SuiteTake control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test Suite
 
DevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsDevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platforms
 
SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024
 
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptxThe Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
 
How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.
 
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
 
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
 
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptxThe Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
 
What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024
 
Connect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationConnect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck Presentation
 
Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!
 
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
 
"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan
 

Optimize Database Performance with Memcached

  • 2. memcached is a high-performance, distributed memory object caching system, generic in nature, but intended for use in speeding up dynamic web applications by alleviating database load.
  • 3. Who? • Facebook • Yahoo • Amazon • LiveJournal • Mixi • ...
  • 4. Why? (aka why would I...)‫‏‬
  • 5.
  • 6. LiveJournal • Origin of memcached • 30G of cache. Terabytes of data • Writes to DB based on reads from the DB, not cache
  • 7. Mixi • Memcached on dedicated servers • 100 servers in production (reuse old MySQL Servers) • 4 gigs of Memory • 15,000 qps / 400Mbps throughput
  • 8.
  • 10. Grazr
  • 11. 100+ Nodes 2gigs a Node Processing Incoming Data Memcached
  • 12. How
  • 13. Server • Slab Allocator • Libevent based • Simple Protocol (no xml) • Server has Internal Hash Table • Servers know nothing about each other
  • 14. Clients • Client hashes Key to Server List (distribution)‫‏‬ • Serializes the Object (server just likes byte arrays)‫‏‬ • Compresses data
  • 16. So what should I ask? • How do I dump data? • How is it redundant? * • How does it handle failover?* • How does it authenticate?
  • 17. Details on the Server? • set/get/replace/add • append/prepend • increment/decrement • cas (compare and swap atomic!)‫‏‬ • stats (detail)‫‏‬
  • 18. Platforms • FreeBSD and Linux are top tier • Windows exists • Solaris (as of 1.2.5)‫‏‬ • OSX Good Support
  • 20. Ruby
  • 21.  # Set up client object  require 'memcache'  servers = ['127.0.0.1:43042', '127.0.0.1:43043']  CACHE = MemCache.new(servers, :namespace => 'my_app')
  • 22. # Get; fall through to Rails' MySQL load if missing  key = quot;recent_postsquot;  # Try to get; returns nil on failure  posts = CACHE.get(key)  unless posts    # Load from DB    posts = Post.find(:all, :limit => 10, :order => 'id DESC')    # Cache the new value, which is automatically serialized    CACHE.set(key), posts, 60  end
  • 23. # Ghetto locking implementation for memcache-client  # from http://fauna.rubyforge.org/svn/interlock/trunk/lib/interlock/lock.rb  def lock(key, lock_expiry = 30, retries = 5)    retries.times do |count|      # Try to acquire the lock      response = CACHE.add(quot;lock:#{key}quot;, quot;Locked by #{Process.pid}quot;, lock_expiry)      if response == quot;STOREDrnquot;        # We got it        begin          # Yield the current value to the closure          value = yield(CACHE.get(key))          # Set the new value returned from the closure CACHE.set(key, value)          # We're done ('ensure' block will still run)          return value        ensure          # Release the lock          CACHE.delete(quot;lock:#{key}quot;)        end      else        # Exponentially back off requests if the lock can't be acquired        sleep((2**count) / 2.0)      end    end    # We waited and waited but our turn never came    raise MemCacheError, quot;Couldn't acquire lock for #{key}quot;  end
  • 24. Perl
  • 25. sub get_foo_object { my $foo_id = int(shift); my $obj = FooClass::MemCache->get(quot;foo:$foo_idquot;); return $obj if $obj; $obj = FooClass::db->selectrow_hashref(quot;SELECT .... FROM foo f, bar b quot;. quot;WHERE ... AND f.fooid=$foo_idquot;); FooClass::MemCache->set(quot;foo:$foo_idquot;, $obj); return $obj; }
  • 26. PHP
  • 27. /** * Initalize Memcache object and add local server 127.0.0.1 using port 11211 */ $cache = new Memcache; $cache->addServer(quot;127.0.0.1quot;,11211);
  • 28. /** Look in cache, if not found, set object (misses null) **/ if (!$user = $cache->get($user_key)) { /** * Set object with expire of 1 hour and no compression */ $cache->set($user_key,$value,NULL, $expire); $user = $value; }
  • 29. /* Get user counter value (does not handle add fail) */ if (!$counter = $cache->get($counter_key)) { /* No counter, set to 1 */ $cache->add($counter_key,1); } else { /* Increment by 1 */ $cache->increment($counter_key); }
  • 30. /* Print out stats from memcached server */ print_r($cache->getStats()); /* Print out extended stats from memcached server */ print_r($cache->getExtendedStats()); /* Flush memcached (bad idea in production)*/ var_dump($cache->flush());
  • 31. C
  • 32. libmemcached • C/C++ (many language wrappers) • Multiget support • Async/Sync Modes (including buffered) • Replicated • Read Through Cache Support
  • 33. memcached_st *memc; memcached_return rc; memc= memcached_create(NULL); ...do stuff... memcached_free(memc);
  • 34. memcached_server_st *servers; memcached_st *memc= memcached_create(NULL); char servername[]= quot;0.example.comquot;; servers= memcached_server_list_append(NULL, servername, 400, &rc); for (x= 0; x < 20; x++) { char buffer[SMALL_STRING_LEN]; snprintf(buffer, SMALL_STRING_LEN, quot;%u.example.comquot;, 400+x); servers= memcached_server_list_append(servers, buffer, 401, &rc); } rc= memcached_server_push(memc, servers); memcached_server_free(servers); memcached_free(memc);
  • 35. char *key= quot;fooquot;; char *value; size_t value_length= 8191; unsigned int x; value = (char*)malloc(value_length); for (x= 0; x < value_length; x++) value[x] = (char) (x % 127); for (x= 0; x < 1; x++) { rc= memcached_set(memc, key, strlen(key), value, value_length, (time_t)0, (uint32_t)0); assert(rc == MEMCACHED_SUCCESS); } free(value);
  • 36. memcached_return rc; char *keys[]= {quot;fudgequot;, quot;sonquot;, quot;foodquot;}; size_t key_length[]= {5, 3, 4}; uint32_t flags; char return_key[MEMCACHED_MAX_KEY]; size_t return_key_length; char *return_value; size_t return_value_length; rc= memcached_mget(memc, keys, key_length, 3); while ((return_value= memcached_fetch(memc, return_key, &return_key_length, &return_value_length, &flags, &rc))) { free(return_value); }
  • 37. Memcached foo; char *value_set= quot;Data for server Aquot;; char *master_key_a= quot;server-aquot;; char *master_key_b= quot;server-bquot;; char *key= quot;xyzquot;; char *value; size_t value_length; foo.set_by_key(master_key_a, key, value_set, strlen(value_set)); value= foo.get_by_key(master_key_a, key, &value_length); assert((memcmp(value, value_set, value_length) == 0)); value= foo.get_by_key(master_key_b, key, &value_length); assert((memcmp(value, value_set, value_length) == 0)); return 0;
  • 39. Postgres Integration • pgmemcache()‫‏‬ • Same as MySQL’s... but we don’t know much about it :)
  • 40. lighttpd/mod_memcache • Cache files from disk • Specify mime/types • Create Expire Times
  • 41. Apache (mod_memcached)‫‏‬ • CAS operations exposed • GET/PUT/DELETE operations • Still Alpha • (pandoraport.com!)
  • 42. NGINX • Support variable Time outs • Based on Perl • http://wiki.codemongers.com/ NginxHttpMemcachedModule • http://www.igvita.com/2008/02/11/nginx- and-memcached-a-400-boost/
  • 43. Memcached Functions for MySQL
  • 44. Overview... • Uses UDF API and libmemcached • Manage memcached Cluster via SQL • Read through Cache • Write through Cache
  • 45.
  • 46. Installation • CREATE FUNCTION memc_servers_add RETURNS INT SONAME quot;libmemcached_functions_mysql.soquot;; • CREATE FUNCTION memc_set RETURNS INT SONAME quot;libmemcached_functions_mysql.soquot;; • CREATE FUNCTION memc_get RETURNS STRING SONAME quot;libmemcached_functions_mysql.soquot;;
  • 47. Functions Available • memc_servers_set(); • memc_servers_behavior_set() • memc_set() • memc_get() • memc_append() • memc_prepend()
  • 48. Setting via SELECT select id, url, memc_set(concat('feeds', md5(url)), url) from feeds; select memc_get(concat('feeds', md5(url))) from feeds; +-------------------------------------------------------+ | memc_get(concat('feeds', md5(url))) | +-------------------------------------------------------+ | http://feeds.feedburner.com/littlegreenfootballs/Ilds | | http://del.icio.us/rss/jacomien | | http://del.icio.us/rss/tags/rmj20 | | http://www.jihadwatch.org/index.rdf | | http://www.connotea.org/rss/user/rmj20 | | http://devblog.grazr.com/?feed=rss2x | | http://feeds.feedburner.com/littlegreenfootballs/kyeH | +-------------------------------------------------------+
  • 49. Trigger DROP TRIGGER IF EXISTS feed_insert; CREATE TRIGGER feed_insert BEFORE INSERT ON feeds FOR EACH ROW BEGIN SET @mm= memc_set(concat('feeds:',md5(NEW.url)), NEW.url);END | insert into feeds (url) values ('http://grazr.com/feedlist.xml'); select memc_get(concat('feeds:', md5('http://grazr.com/feedlist.xml'))); +------------------------------------------------------------------+| memc_get(concat('feeds:', md5('http://grazr.com/feedlist.xml'))) | +------------------------------------------------------------------+| http://grazr.com/feedlist.xml | +------------------------------------------------------------------+
  • 50. Memcached Replication via MySQL INSERT INTO table_a VALUES (“key”, “value”, “values”); INSERT INTO blackhole_table VALUES (memc_delete(“key”));
  • 52. Limits • Key Size (250 bytes)‫‏‬ • Data Size (under 1 megabyte)‫‏‬ • 32bit/64bit (maximum size of the process)‫‏‬ • Maxbytes (limits item cache, not everything!)‫‏‬
  • 53. LRU • Least recently accessed items are up for eviction and can be seen • One LRU exists per “slab class” • LRU evictions don't need to be common
  • 54. Threads • You might not need them (yet!)‫‏‬ • Great for large instances (16G+)‫‏‬ • Also great for large multiget requests • Scales okay now. Will get better in the future
  • 55. Slab Allocator • Memory permanently allocated from OS • Classes created by chunk size • Cannot (presently) reassign slab pages • Carefully use 'stats sizes' to test efficiency
  • 56. Tools
  • 57. Protocol • Telnet’able (see doc/protocol.txt)‫‏‬ • All commands are text based (binary soon)‫‏‬ • Store commands are binary (no escaping)‫‏‬
  • 58. memcached-tool • Example minimal monitoring tool • Shows details of server stats, slabs • memcached-tool 10.0.0.1 display • memcached-tool 10.0.0.1 stats
  • 59. libmemcached Tools • memcp • memrm • memstat • memslap (hahahhaha)‫‏‬
  • 60. MRTG • Plenty of interfaces monitored • Old technology, been around forever
  • 61.
  • 62. ...and others • Cacti • http://dealnews.com/developers/cacti/ memcached.html • Ganglia • http://ganglia.wiki.sourceforge.net/
  • 66. 1.2.5 Release • Multi Interface Support • UDP all the time • noreply (SET with no response) • Solaris Support (large memory page support) • getimeofday() optimizations • IPV6
  • 67. Future • Binary Protocol • Multiple Engine Support • Char based • Durable • Queue • Highly Threaded
  • 68. More Resources... • http://danga.com/memcached/ • #memcached on Freenode • http://tangent.org/552/libmemcached.html • http://groups.google.com/groups/ memcached • http://dev.mysql.com/doc/refman/5.1/en/ha- memcached.html