SlideShare a Scribd company logo
memcached

 scaling your website
 with memcached


 by: steve yen
about me

• Steve Yen

 • NorthScale
 • Escalate Software
 • Kiva Software
what you’ll learn

•   what, where, why, when



• how
 • especially, best practices
“mem cache dee”

• latest version1.4.1

• http://code.google.com/p/memcached
open source
distributed cache
livejournal
helps your websites run
          fast
popular
simple
KISS
easy
small bite-sized steps


• not a huge, forklift replacement
  rearchitecture / reengineering project
fast
“i only block for
  memcached”
scalable
many client libraries
• might be TOO many
• the hit list...
 • Java ==> spymemcached
 • C ==> libmemcached
 • Python, Ruby, etc ==>
    • libmemcached wrappers
frameworks

• rails
• django
• spring / hibernate
• cakephp, symphony, etc
applications

• drupal
• wordpress
• mediawiki
• etc
it works

it promises to solve performance problems


                               it delivers!
problem?
your website is too
      slow
RDBMS melting down
urgent! emergency
one server


web app + RDBMS
1 + 1 servers

     web app


     RDBMS
N + 1 servers

web app, web app, web app, web app


             RDBMS
RDBMS
EXPLAIN PLAN?
buy a bigger box
buy better disks
master write DB +
multiple read DB?
vertical partitioning?
sharding?
uh oh, big reengineering

• risky!

• touch every line of code, every query!!
and, it’s 2AM
you need a band-aid
a simple band-aid now
use a cache
keep things in memory!
don’t hit disk
distributed cache


• to avoid wasting memory
don’t write one of
  these yourself
memcached
simple API


• hash-table-ish
your code before



v = db.query( SOME SLOW QUERY )
your code after

v = memcachedClient.get(key)
if (!v) {
    v = db.query( SOME SLOW QUERY )
    memcachedClient.set(key, v)
}
cache read-heavy stuff
invalidate when writing


• db.execute(“UPDATE foo WHERE ...”)
• memcachedClient.delete(...)
and, repeat

• each day...
 • look for the next slowest operations
 • add code to cache a few more things
your life gets better
thank you memcached!
no magic
you are in control
now for the decisions
memcached adoption

• first, start using memcached
 • poorly
   • but you can breathe again
memcached adoption


• next, start using memcached correctly
memcached adoption

• later
 • queueing
 • persistence
 • replication
 • ...
an early question
where to run servers?
answer 1

• right on your web servers

• a great place to start, if you have extra
  memory
servers

web app web app web app web app
memcached   memcached   memcached,   memcached




                  RDBMS
add up your memory
        usage!


• having memcached server swap == bad!
answer 2

• run memcached right on your database
  server?


• WRONG!
answer 3
• run memcached on separate dedicated
  memcached servers


• congratulations!
 • you either have enough money
 • or enough traffic that it matters
running a server

• daemonize

• don’t be root!

• no security
server lists

• mc-server1:11211
• mc-server2:11211
• mc-server3:11211
consistent hashing




 source: http://www.spiteful.com/2008/03/17/programmers-toolbox-part-3-consistent-hashing/
client-side intelligence


• no “server master” bottleneck
libmemcached

• fast C memcached client
 • supports consistent hashing
 • many wrappers to your favorite languages
updating server lists

• push out new configs and restart?

• moxi
 • memcached + integrated proxy
keys

• no whitespace
• 250 char limit
• use short prefixes
keys & MD5

• don’t

• stats become useless
values
• any binary object

• 1MB limit
 • change #define & recompile if you want more
 • and you’re probably doing something wrong if
    you want more
values
• query resultset
•   serialized object
•   page fragment

•
•
    pages
    etc
nginx + memcached
>1 language?

• JSON
• protocol buffers
• XML
memcached is lossy


• memcached WILL lose data
that’s a good thing




         remember, it’s a CACHE
why is memcached
      lossy?
memcached node dies
when node restarts...

• you just get a bunch of cache misses
                    (and a short RDBMS spike)
eviction


more disappearing data!
LRU


• can config memcached to not evict
 • but, you’re probably doing something
    wrong if you do this
remember, it forgets


• it’s just a CACHE
expiration

• aka, timeouts

• memcached.set(key, value, timeout)
use expirations or not?
1st school of thought

• expirations hide bugs
• you should be doing proper invalidations
 • (aka, deletes)
 • coherency!
school 2

• it’s 3AM and I can’t think anymore

• business guy:
 • “sessions should auto-logout after 30
    minutes due to bank security policy”
put sessions
      in memcached?

• just a config change
 • eg, Ruby on Rails
good


• can load-balance requests to any web host
• don’t touch the RDBMS on every web
  request
bad


• could lose a user’s session
solution

• save sessions to memcached
• the first time, also save to RDBMS
 • ideally, asynchronously
• on cache miss, restore from RDBMS
solution

• save sessions to memcached
• the first time, also save to RDBMS
 • ideally, asynchronously
• on cache miss, restore from RDBMS
in the background...
• have a job querying the RDBMS
 • cron job?
• the job queries for “old” looking session
  records in the sessions table
  • refresh old session records from
    memcached
add vs replace vs set
append vs prepend
CAS


• compare - and - swap
incr and decr


• no negative numbers
queueing


• “hey, with those primitives, I could build a queue!”
don’t
• memcached is lossy
• protocol is incorrect for a queue
• instead
 • gearman
 • beanstalkd
 • etc
cache stampedes

• gearman job-unique-id
• encode a timestamp in your values
 • one app node randomly decides to
    refresh slightly early
coherency
denormalization


• or copies of data
example: changing a
   product price
memcached UDF’s

• another great tool in your toolbox

• on a database trigger, delete stuff from
  memcached
memcached UDF’s


• works even if you do UPDATES with fancy
  WHERE clauses
multigets

• they are your friend

• memcached is fast, but...
 • imagine 1ms for a get request
   • 200 serial gets ==> 200ms
a resultset loop

foreach product in resultset
  c = memcached.get(product.category_id)
  do something with c
2 loops
for product in resultset
  multiget_request.append(product.category_id)
multiget_response = memcachedClient.multiget(
  multiget_request)
for c in multiget_response
  do something with c
memcached slabber

• allocates memory into slabs

• it might “learn” the wrong slab sizes

• watch eviction stats
losing a node


• means your RDBMS gets hit
replication
• simple replication in libmemcached

• >= 2x memory cost
• only simple verbs
 • set, get, delete
• doesn’t handle flapping nodes
persistence
things that speak
        memcached

• tokyo tyrant
• memcachedb
• moxi
another day

• monitoring & statistics
• near caching
• moxi
thanks!!!

• love any feedback
 • your memcached war stories
    • your memcached wishlist

• steve.yen@northscale.com
thanks!

photo credits

 •     http://flickr.com/photos/davebluedevil/15877348/

 •     http://www.flickr.com/photos/theamarand/2874288064/

 •     http://www.flickr.com/photos/splityarn/3469596708/

 •     http://www.flickr.com/photos/heisnofool/3241930754/

 •     http://www.flickr.com/photos/onourminds/2885704630/

 •     http://www.flickr.com/photos/lunaspin/990825818/

More Related Content

What's hot

Caching with Varnish
Caching with VarnishCaching with Varnish
Caching with Varnish
schoefmax
 
Caching with varnish
Caching with varnishCaching with varnish
Caching with varnish
90kts
 
Scalable Architecture 101
Scalable Architecture 101Scalable Architecture 101
Scalable Architecture 101
ConFoo
 

What's hot (19)

Introduction to memcached
Introduction to memcachedIntroduction to memcached
Introduction to memcached
 
Caching with Varnish
Caching with VarnishCaching with Varnish
Caching with Varnish
 
Using memcache to improve php performance
Using memcache to improve php performanceUsing memcache to improve php performance
Using memcache to improve php performance
 
cache concepts and varnish-cache
cache concepts and varnish-cachecache concepts and varnish-cache
cache concepts and varnish-cache
 
Building your own CDN using Amazon EC2
Building your own CDN using Amazon EC2Building your own CDN using Amazon EC2
Building your own CDN using Amazon EC2
 
Usenix LISA 2012 - Choosing a Proxy
Usenix LISA 2012 - Choosing a ProxyUsenix LISA 2012 - Choosing a Proxy
Usenix LISA 2012 - Choosing a Proxy
 
Memcache
MemcacheMemcache
Memcache
 
Varnish intro
Varnish introVarnish intro
Varnish intro
 
Varnish Configuration Step by Step
Varnish Configuration Step by StepVarnish Configuration Step by Step
Varnish Configuration Step by Step
 
Varnish - PLNOG 4
Varnish - PLNOG 4Varnish - PLNOG 4
Varnish - PLNOG 4
 
Using advanced options in MariaDB Connector/J
Using advanced options in MariaDB Connector/JUsing advanced options in MariaDB Connector/J
Using advanced options in MariaDB Connector/J
 
Apache Performance Tuning: Scaling Up
Apache Performance Tuning: Scaling UpApache Performance Tuning: Scaling Up
Apache Performance Tuning: Scaling Up
 
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?
 
Ehcache 3: JSR-107 on steroids at Devoxx Morocco
Ehcache 3: JSR-107 on steroids at Devoxx MoroccoEhcache 3: JSR-107 on steroids at Devoxx Morocco
Ehcache 3: JSR-107 on steroids at Devoxx Morocco
 
Caching with varnish
Caching with varnishCaching with varnish
Caching with varnish
 
Caching
CachingCaching
Caching
 
Scalable Architecture 101
Scalable Architecture 101Scalable Architecture 101
Scalable Architecture 101
 
03 h base-2-installation_andshell
03 h base-2-installation_andshell03 h base-2-installation_andshell
03 h base-2-installation_andshell
 
Top ten-list
Top ten-listTop ten-list
Top ten-list
 

Similar to Memcached Code Camp 2009

A Case Study of NoSQL Adoption: What Drove Wordnik Non-Relational?
A Case Study of NoSQL Adoption: What Drove Wordnik Non-Relational?A Case Study of NoSQL Adoption: What Drove Wordnik Non-Relational?
A Case Study of NoSQL Adoption: What Drove Wordnik Non-Relational?
DATAVERSITY
 
Fixing Twitter Improving The Performance And Scalability Of The Worlds Most ...
Fixing Twitter  Improving The Performance And Scalability Of The Worlds Most ...Fixing Twitter  Improving The Performance And Scalability Of The Worlds Most ...
Fixing Twitter Improving The Performance And Scalability Of The Worlds Most ...
xlight
 
Discover MongoDB - Israel
Discover MongoDB - IsraelDiscover MongoDB - Israel
Discover MongoDB - Israel
Michael Fiedler
 
Performance and scalability with drupal
Performance and scalability with drupalPerformance and scalability with drupal
Performance and scalability with drupal
Ronan Berder
 
From vagrant to production - Mark Eijsermans
From vagrant to production - Mark EijsermansFrom vagrant to production - Mark Eijsermans
From vagrant to production - Mark Eijsermans
Devopsdays
 
Host and Boast: Best Practices for Magento Hosting | Imagine 2013 Technolog…
Host and Boast: Best Practices for Magento Hosting | Imagine 2013 Technolog…Host and Boast: Best Practices for Magento Hosting | Imagine 2013 Technolog…
Host and Boast: Best Practices for Magento Hosting | Imagine 2013 Technolog…
Atwix
 
Membase Intro from Membase Meetup San Francisco
Membase Intro from Membase Meetup San FranciscoMembase Intro from Membase Meetup San Francisco
Membase Intro from Membase Meetup San Francisco
Membase
 

Similar to Memcached Code Camp 2009 (20)

Where Django Caching Bust at the Seams
Where Django Caching Bust at the SeamsWhere Django Caching Bust at the Seams
Where Django Caching Bust at the Seams
 
A Case Study of NoSQL Adoption: What Drove Wordnik Non-Relational?
A Case Study of NoSQL Adoption: What Drove Wordnik Non-Relational?A Case Study of NoSQL Adoption: What Drove Wordnik Non-Relational?
A Case Study of NoSQL Adoption: What Drove Wordnik Non-Relational?
 
Redis ndc2013
Redis ndc2013Redis ndc2013
Redis ndc2013
 
Running MongoDB in the Cloud
Running MongoDB in the CloudRunning MongoDB in the Cloud
Running MongoDB in the Cloud
 
Fixing twitter
Fixing twitterFixing twitter
Fixing twitter
 
Fixing_Twitter
Fixing_TwitterFixing_Twitter
Fixing_Twitter
 
Fixing Twitter Improving The Performance And Scalability Of The Worlds Most ...
Fixing Twitter  Improving The Performance And Scalability Of The Worlds Most ...Fixing Twitter  Improving The Performance And Scalability Of The Worlds Most ...
Fixing Twitter Improving The Performance And Scalability Of The Worlds Most ...
 
Fixing Twitter Improving The Performance And Scalability Of The Worlds Most ...
Fixing Twitter  Improving The Performance And Scalability Of The Worlds Most ...Fixing Twitter  Improving The Performance And Scalability Of The Worlds Most ...
Fixing Twitter Improving The Performance And Scalability Of The Worlds Most ...
 
Discover MongoDB - Israel
Discover MongoDB - IsraelDiscover MongoDB - Israel
Discover MongoDB - Israel
 
My first powershell script
My first powershell scriptMy first powershell script
My first powershell script
 
Performance and scalability with drupal
Performance and scalability with drupalPerformance and scalability with drupal
Performance and scalability with drupal
 
From vagrant to production - Mark Eijsermans
From vagrant to production - Mark EijsermansFrom vagrant to production - Mark Eijsermans
From vagrant to production - Mark Eijsermans
 
SmugMug: From MySQL to Amazon DynamoDB (DAT204) | AWS re:Invent 2013
SmugMug: From MySQL to Amazon DynamoDB (DAT204) | AWS re:Invent 2013SmugMug: From MySQL to Amazon DynamoDB (DAT204) | AWS re:Invent 2013
SmugMug: From MySQL to Amazon DynamoDB (DAT204) | AWS re:Invent 2013
 
Caching your rails application
Caching your rails applicationCaching your rails application
Caching your rails application
 
Riak at Posterous
Riak at PosterousRiak at Posterous
Riak at Posterous
 
High Scalability Toronto: Meetup #2
High Scalability Toronto: Meetup #2High Scalability Toronto: Meetup #2
High Scalability Toronto: Meetup #2
 
Host and Boast: Best Practices for Magento Hosting | Imagine 2013 Technolog…
Host and Boast: Best Practices for Magento Hosting | Imagine 2013 Technolog…Host and Boast: Best Practices for Magento Hosting | Imagine 2013 Technolog…
Host and Boast: Best Practices for Magento Hosting | Imagine 2013 Technolog…
 
OSDC 2013 | Introduction into Chef by Andy Hawkins
OSDC 2013 | Introduction into Chef by Andy HawkinsOSDC 2013 | Introduction into Chef by Andy Hawkins
OSDC 2013 | Introduction into Chef by Andy Hawkins
 
BTV PHP - Building Fast Websites
BTV PHP - Building Fast WebsitesBTV PHP - Building Fast Websites
BTV PHP - Building Fast Websites
 
Membase Intro from Membase Meetup San Francisco
Membase Intro from Membase Meetup San FranciscoMembase Intro from Membase Meetup San Francisco
Membase Intro from Membase Meetup San Francisco
 

Recently uploaded

Structuring Teams and Portfolios for Success
Structuring Teams and Portfolios for SuccessStructuring Teams and Portfolios for Success
Structuring Teams and Portfolios for Success
UXDXConf
 

Recently uploaded (20)

Free and Effective: Making Flows Publicly Accessible, Yumi Ibrahimzade
Free and Effective: Making Flows Publicly Accessible, Yumi IbrahimzadeFree and Effective: Making Flows Publicly Accessible, Yumi Ibrahimzade
Free and Effective: Making Flows Publicly Accessible, Yumi Ibrahimzade
 
A Business-Centric Approach to Design System Strategy
A Business-Centric Approach to Design System StrategyA Business-Centric Approach to Design System Strategy
A Business-Centric Approach to Design System Strategy
 
AI presentation and introduction - Retrieval Augmented Generation RAG 101
AI presentation and introduction - Retrieval Augmented Generation RAG 101AI presentation and introduction - Retrieval Augmented Generation RAG 101
AI presentation and introduction - Retrieval Augmented Generation RAG 101
 
Intelligent Gimbal FINAL PAPER Engineering.pdf
Intelligent Gimbal FINAL PAPER Engineering.pdfIntelligent Gimbal FINAL PAPER Engineering.pdf
Intelligent Gimbal FINAL PAPER Engineering.pdf
 
Connector Corner: Automate dynamic content and events by pushing a button
Connector Corner: Automate dynamic content and events by pushing a buttonConnector Corner: Automate dynamic content and events by pushing a button
Connector Corner: Automate dynamic content and events by pushing a button
 
JMeter webinar - integration with InfluxDB and Grafana
JMeter webinar - integration with InfluxDB and GrafanaJMeter webinar - integration with InfluxDB and Grafana
JMeter webinar - integration with InfluxDB and Grafana
 
Introduction to Open Source RAG and RAG Evaluation
Introduction to Open Source RAG and RAG EvaluationIntroduction to Open Source RAG and RAG Evaluation
Introduction to Open Source RAG and RAG Evaluation
 
Software Delivery At the Speed of AI: Inflectra Invests In AI-Powered Quality
Software Delivery At the Speed of AI: Inflectra Invests In AI-Powered QualitySoftware Delivery At the Speed of AI: Inflectra Invests In AI-Powered Quality
Software Delivery At the Speed of AI: Inflectra Invests In AI-Powered Quality
 
ECS 2024 Teams Premium - Pretty Secure
ECS 2024   Teams Premium - Pretty SecureECS 2024   Teams Premium - Pretty Secure
ECS 2024 Teams Premium - Pretty Secure
 
PLAI - Acceleration Program for Generative A.I. Startups
PLAI - Acceleration Program for Generative A.I. StartupsPLAI - Acceleration Program for Generative A.I. Startups
PLAI - Acceleration Program for Generative A.I. Startups
 
UiPath Test Automation using UiPath Test Suite series, part 2
UiPath Test Automation using UiPath Test Suite series, part 2UiPath Test Automation using UiPath Test Suite series, part 2
UiPath Test Automation using UiPath Test Suite series, part 2
 
UiPath Test Automation using UiPath Test Suite series, part 1
UiPath Test Automation using UiPath Test Suite series, part 1UiPath Test Automation using UiPath Test Suite series, part 1
UiPath Test Automation using UiPath Test Suite series, part 1
 
Speed Wins: From Kafka to APIs in Minutes
Speed Wins: From Kafka to APIs in MinutesSpeed Wins: From Kafka to APIs in Minutes
Speed Wins: From Kafka to APIs in Minutes
 
Connecting the Dots in Product Design at KAYAK
Connecting the Dots in Product Design at KAYAKConnecting the Dots in Product Design at KAYAK
Connecting the Dots in Product Design at KAYAK
 
Custom Approval Process: A New Perspective, Pavel Hrbacek & Anindya Halder
Custom Approval Process: A New Perspective, Pavel Hrbacek & Anindya HalderCustom Approval Process: A New Perspective, Pavel Hrbacek & Anindya Halder
Custom Approval Process: A New Perspective, Pavel Hrbacek & Anindya Halder
 
Structuring Teams and Portfolios for Success
Structuring Teams and Portfolios for SuccessStructuring Teams and Portfolios for Success
Structuring Teams and Portfolios for Success
 
Unpacking Value Delivery - Agile Oxford Meetup - May 2024.pptx
Unpacking Value Delivery - Agile Oxford Meetup - May 2024.pptxUnpacking Value Delivery - Agile Oxford Meetup - May 2024.pptx
Unpacking Value Delivery - Agile Oxford Meetup - May 2024.pptx
 
Behind the Scenes From the Manager's Chair: Decoding the Secrets of Successfu...
Behind the Scenes From the Manager's Chair: Decoding the Secrets of Successfu...Behind the Scenes From the Manager's Chair: Decoding the Secrets of Successfu...
Behind the Scenes From the Manager's Chair: Decoding the Secrets of Successfu...
 
10 Differences between Sales Cloud and CPQ, Blanka Doktorová
10 Differences between Sales Cloud and CPQ, Blanka Doktorová10 Differences between Sales Cloud and CPQ, Blanka Doktorová
10 Differences between Sales Cloud and CPQ, Blanka Doktorová
 
Intro in Product Management - Коротко про професію продакт менеджера
Intro in Product Management - Коротко про професію продакт менеджераIntro in Product Management - Коротко про професію продакт менеджера
Intro in Product Management - Коротко про професію продакт менеджера
 

Memcached Code Camp 2009