SlideShare a Scribd company logo
1 of 24
Download to read offline
Getting Creative With
  Memcached and
   AR-extensions

    Daniel Lockhart, Newzwag
            Nov 19, 2008
Our Situation:
 - Using conventional Memcached techniques (caching
   AR queries, rendered views, etc..), we were able to
  eliminate almost all of the reads from the database.

 - Writes were still still taking quite a bit of time, as up
to four separate tables were being written to each time
              a user answered a question.
Abstract Solution:
• Cache the new information that needs to
  be written to the database and periodically
  write all of it at once.
Our Requirements:
• Ability to store both new records and
  updates to existing records in Memcached.
• Thread-safe - needs to be able to handle
  simultaneous reading/writing of data.
• Ability to retrieve all of the new data
  periodically to commit to the database.
• No stale data.
Memcached
          Limitations:
• No data redundancy - if Memcached goes
  down or runs out of space, new records
  and updates will be lost.
• No built in locking/mutex type capability
  (other than using set/add)
• No ability to iterate over data or
  determine what keys have been stored.
Solution:
     Data Redundancy
• Ignore it! If we commit changes to the
  database frequently, we can limit the
  damage from lost data.
• The minimal risk of lost data is
  acceptable for our project.
Solution:
    No locking/mutex

• There is one aspect of Memcached that is
  atomic/thread-safe: incr and decr
• This feature can be leveraged in creative
  ways to overcome our other limitations.
Using Incr and Decr

• Some of our data updates are simple
    counters: how many people have answered
    a question, how many people chose each
    answer, etc.
•    For this type of data, we can use incr and
    decr directly.
Incr and Decr for
      Question Stats
• Each attribute gets its own key:
  answer_count_27 will be the total number
  of answers for a question with ID 27, while
  correct_count_27 would be the count of
  correct answers.
• Example:
  CACHE.incr(“answer_count_27”, 1)
  CACHE.incr(“correct_count_27”, 1) if answer.is_correct?
Incr and Decr for
       Question Stats
• Since we know all of the question IDs, we
  can easily periodically retrieve all of the
  keys to write the counters to the database.
  (Bulk DB updating will be explained soon)


 Question.find(:all).map {|x| “correct_count_#{x.id}”}
Stretching the use of incr and decr:
         UserActions

• Our UserAction model stores information
  about each action a user takes - a new
  record is created for every request.
• None of the attributes lend themselves to
  be counted with incr and decr.
Caching a UserAction
• When rails starts, initialize a counter and
  store the starting value as the lower
  bounds.

  CACHE.add(“ua_counter”, “0”, 0, true)
  Cache.put(“ua_lower_bounds”, 0)
Caching a UserAction
• When a UserAction needs to be created,
  call incr on the counter. Since this call is
  atomic, each request will be guaranteed to
  return a unique value.
 ua_number = CACHE.incr(“ua_counter”)
Caching a UserAction
• Store the marshaled UserAction object
  with a key created from the counter value
  (i.e. ua_2, ua_3, etc..)


      Cache.add(“ua_#{ua_number}”, ua)
Writing to the database
• Call incr on the counter to get an upper
  bounds.
• Using this number and our lower bounds
  number we recorded when we started
  rails, we can reconstruct and array of all of
  the keys that store the individual
  UserAction objects.
Writing to the database
• Use Cache.get_multi to retrieve all of the
   UserAction objects.


user_action_objects = CACHE.get_multi(keys)
Writing to the database
• Store previous upper bounds as our new
  lower bounds for the next time we import.

    Cache.put(“ua_lower_bounds”, upper_bounds)
Ar-Extensions
• Ar-Extensions - the best RoR plugin since
  sliced_bread.rb
• Bulk importing - commit multiple records
  in a single database call.
• Very simple syntax:
Updating Existing Records
  with AR-Extensions

• Using AR-extensions with MySQL allows
  you to update multiple records in a single
  call.
• This is accomplished by utilizing the MySQL
  feature ON DUPLICATE KEY UPDATE.
Updating User Records
• Each user record includes columns for a
  total score, number of questions answered,
  longest streak, etc.
• These attributes are cached in Memcached.
  When a user record is retrieved from the
  DB, the object attributes are updated from
  the cache. When the attributes are
  updated, they are written to the cache
  instead of the DB.
Update Example
Flaws
• No redundancy of the data.
• You can never bring a Memcached server
  down or add a new one to the pool while
  people are playing.
• If the background updating process stops
  for any reason, updates do not occur and
  there is a possibility that the Memcached
  server could fill up.
Possible Solutions
• MirroredMemcached: Write the same data
  to two or more Memcached server
  clusters. This would slow the updates
  down slightly, but would still be an
  improvement over writing directly to the
  DB.
• A consistent hashing algorithm might
  mitigate the damage of losing a Memcached
  server instance.
Is it worth it?
• Any attempt to offload database writes into
  a single query(that I can think of) will be at
  some risk of data loss.
• If the data is stored in memory, it can be
  lost; if it is stored on disk, it will be slow to
  update.
• Each app has to strike its own balance
  between speed and data protection.

More Related Content

What's hot

Maintaining Consistency Across Data Centers (Randy Fradin, BlackRock) | Cassa...
Maintaining Consistency Across Data Centers (Randy Fradin, BlackRock) | Cassa...Maintaining Consistency Across Data Centers (Randy Fradin, BlackRock) | Cassa...
Maintaining Consistency Across Data Centers (Randy Fradin, BlackRock) | Cassa...
DataStax
 

What's hot (20)

Instaclustr Webinar 50,000 Transactions Per Second with Apache Spark on Apach...
Instaclustr Webinar 50,000 Transactions Per Second with Apache Spark on Apach...Instaclustr Webinar 50,000 Transactions Per Second with Apache Spark on Apach...
Instaclustr Webinar 50,000 Transactions Per Second with Apache Spark on Apach...
 
Building a Multi-Region Cluster at Target (Aaron Ploetz, Target) | Cassandra ...
Building a Multi-Region Cluster at Target (Aaron Ploetz, Target) | Cassandra ...Building a Multi-Region Cluster at Target (Aaron Ploetz, Target) | Cassandra ...
Building a Multi-Region Cluster at Target (Aaron Ploetz, Target) | Cassandra ...
 
Instaclustr Apache Cassandra Best Practices & Toubleshooting
Instaclustr Apache Cassandra Best Practices & ToubleshootingInstaclustr Apache Cassandra Best Practices & Toubleshooting
Instaclustr Apache Cassandra Best Practices & Toubleshooting
 
Monitoring Cassandra with graphite using Yammer Coda-Hale Library
Monitoring Cassandra with graphite using Yammer Coda-Hale LibraryMonitoring Cassandra with graphite using Yammer Coda-Hale Library
Monitoring Cassandra with graphite using Yammer Coda-Hale Library
 
Using Galera Cluster to Power Geo-distributed Applications on the WAN
Using Galera Cluster to Power Geo-distributed Applications on the WANUsing Galera Cluster to Power Geo-distributed Applications on the WAN
Using Galera Cluster to Power Geo-distributed Applications on the WAN
 
Cassandra Community Webinar | Data Model on Fire
Cassandra Community Webinar | Data Model on FireCassandra Community Webinar | Data Model on Fire
Cassandra Community Webinar | Data Model on Fire
 
Performance Testing: Scylla vs. Cassandra vs. Datastax
Performance Testing: Scylla vs. Cassandra vs. DatastaxPerformance Testing: Scylla vs. Cassandra vs. Datastax
Performance Testing: Scylla vs. Cassandra vs. Datastax
 
Scalabe MySQL Infrastructure
Scalabe MySQL InfrastructureScalabe MySQL Infrastructure
Scalabe MySQL Infrastructure
 
Cassandra Community Webinar | Practice Makes Perfect: Extreme Cassandra Optim...
Cassandra Community Webinar | Practice Makes Perfect: Extreme Cassandra Optim...Cassandra Community Webinar | Practice Makes Perfect: Extreme Cassandra Optim...
Cassandra Community Webinar | Practice Makes Perfect: Extreme Cassandra Optim...
 
Maintaining Consistency Across Data Centers (Randy Fradin, BlackRock) | Cassa...
Maintaining Consistency Across Data Centers (Randy Fradin, BlackRock) | Cassa...Maintaining Consistency Across Data Centers (Randy Fradin, BlackRock) | Cassa...
Maintaining Consistency Across Data Centers (Randy Fradin, BlackRock) | Cassa...
 
Apache Cassandra and DataStax Enterprise Explained with Peter Halliday at Wil...
Apache Cassandra and DataStax Enterprise Explained with Peter Halliday at Wil...Apache Cassandra and DataStax Enterprise Explained with Peter Halliday at Wil...
Apache Cassandra and DataStax Enterprise Explained with Peter Halliday at Wil...
 
Instaclustr introduction to managing cassandra
Instaclustr introduction to managing cassandraInstaclustr introduction to managing cassandra
Instaclustr introduction to managing cassandra
 
Micro-batching: High-performance writes
Micro-batching: High-performance writesMicro-batching: High-performance writes
Micro-batching: High-performance writes
 
Cassandra Tuning - above and beyond
Cassandra Tuning - above and beyondCassandra Tuning - above and beyond
Cassandra Tuning - above and beyond
 
PostgreSQL Terminology
PostgreSQL TerminologyPostgreSQL Terminology
PostgreSQL Terminology
 
HandsOn ProxySQL Tutorial - PLSC18
HandsOn ProxySQL Tutorial - PLSC18HandsOn ProxySQL Tutorial - PLSC18
HandsOn ProxySQL Tutorial - PLSC18
 
Load testing Cassandra applications
Load testing Cassandra applicationsLoad testing Cassandra applications
Load testing Cassandra applications
 
Cassandra TK 2014 - Large Nodes
Cassandra TK 2014 - Large NodesCassandra TK 2014 - Large Nodes
Cassandra TK 2014 - Large Nodes
 
Everyday I’m scaling... Cassandra
Everyday I’m scaling... CassandraEveryday I’m scaling... Cassandra
Everyday I’m scaling... Cassandra
 
Introduction to Cassandra
Introduction to CassandraIntroduction to Cassandra
Introduction to Cassandra
 

Viewers also liked (9)

Aerospace and electronics cost index July 2010
Aerospace and electronics cost index July 2010Aerospace and electronics cost index July 2010
Aerospace and electronics cost index July 2010
 
Planilha
PlanilhaPlanilha
Planilha
 
1 DEzembro de 1640
1 DEzembro de 16401 DEzembro de 1640
1 DEzembro de 1640
 
Malaysian Fashion And Designer
Malaysian Fashion And DesignerMalaysian Fashion And Designer
Malaysian Fashion And Designer
 
Om Webbstjärnan åva 2010-01-27
Om Webbstjärnan åva  2010-01-27Om Webbstjärnan åva  2010-01-27
Om Webbstjärnan åva 2010-01-27
 
Nehezen MegmagyaráZható SzituáCióK
Nehezen MegmagyaráZható SzituáCióKNehezen MegmagyaráZható SzituáCióK
Nehezen MegmagyaráZható SzituáCióK
 
VRMevent: 3 - Luuk Boonstra - Beabo
VRMevent: 3 - Luuk Boonstra - BeaboVRMevent: 3 - Luuk Boonstra - Beabo
VRMevent: 3 - Luuk Boonstra - Beabo
 
minaintryck #iis12
minaintryck #iis12minaintryck #iis12
minaintryck #iis12
 
Apresentação do Blog do Laboratório da UESC II - CP II
Apresentação do Blog do Laboratório da UESC II - CP IIApresentação do Blog do Laboratório da UESC II - CP II
Apresentação do Blog do Laboratório da UESC II - CP II
 

Similar to Memcached Presentation

Mongodb in-anger-boston-rb-2011
Mongodb in-anger-boston-rb-2011Mongodb in-anger-boston-rb-2011
Mongodb in-anger-boston-rb-2011
bostonrb
 
Scaling Rails with memcached
Scaling Rails with memcachedScaling Rails with memcached
Scaling Rails with memcached
elliando dias
 
RedisConf18 - Fail-Safe Starvation-Free Durable Priority Queues in Redis
RedisConf18 - Fail-Safe Starvation-Free Durable Priority Queues in RedisRedisConf18 - Fail-Safe Starvation-Free Durable Priority Queues in Redis
RedisConf18 - Fail-Safe Starvation-Free Durable Priority Queues in Redis
Redis Labs
 
Make Your Life Easier With Maatkit
Make Your Life Easier With MaatkitMake Your Life Easier With Maatkit
Make Your Life Easier With Maatkit
MySQLConference
 

Similar to Memcached Presentation (20)

Memcached Presentation
Memcached PresentationMemcached Presentation
Memcached Presentation
 
Building an Analytic Extension to MySQL with ClickHouse and Open Source
Building an Analytic Extension to MySQL with ClickHouse and Open SourceBuilding an Analytic Extension to MySQL with ClickHouse and Open Source
Building an Analytic Extension to MySQL with ClickHouse and Open Source
 
Building an Analytic Extension to MySQL with ClickHouse and Open Source.pptx
Building an Analytic Extension to MySQL with ClickHouse and Open Source.pptxBuilding an Analytic Extension to MySQL with ClickHouse and Open Source.pptx
Building an Analytic Extension to MySQL with ClickHouse and Open Source.pptx
 
How to boost performance of your rails app using dynamo db and memcached
How to boost performance of your rails app using dynamo db and memcachedHow to boost performance of your rails app using dynamo db and memcached
How to boost performance of your rails app using dynamo db and memcached
 
Storage Systems for High Scalable Systems Presentation
Storage Systems for High Scalable Systems PresentationStorage Systems for High Scalable Systems Presentation
Storage Systems for High Scalable Systems Presentation
 
Mongodb in-anger-boston-rb-2011
Mongodb in-anger-boston-rb-2011Mongodb in-anger-boston-rb-2011
Mongodb in-anger-boston-rb-2011
 
Cassandra at Pollfish
Cassandra at PollfishCassandra at Pollfish
Cassandra at Pollfish
 
Cassandra at Pollfish
Cassandra at PollfishCassandra at Pollfish
Cassandra at Pollfish
 
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
 
Scaling Rails with memcached
Scaling Rails with memcachedScaling Rails with memcached
Scaling Rails 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 2012
 
System Design.pdf
System Design.pdfSystem Design.pdf
System Design.pdf
 
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
 
No sql presentation
No sql presentationNo sql presentation
No sql presentation
 
MySQL and Spark machine learning performance on Azure VMsbased on 3rd Gen AMD...
MySQL and Spark machine learning performance on Azure VMsbased on 3rd Gen AMD...MySQL and Spark machine learning performance on Azure VMsbased on 3rd Gen AMD...
MySQL and Spark machine learning performance on Azure VMsbased on 3rd Gen AMD...
 
RedisConf18 - Fail-Safe Starvation-Free Durable Priority Queues in Redis
RedisConf18 - Fail-Safe Starvation-Free Durable Priority Queues in RedisRedisConf18 - Fail-Safe Starvation-Free Durable Priority Queues in Redis
RedisConf18 - Fail-Safe Starvation-Free Durable Priority Queues in Redis
 
Make Your Life Easier With Maatkit
Make Your Life Easier With MaatkitMake Your Life Easier With Maatkit
Make Your Life Easier With Maatkit
 
Accelerating Application Performance with Amazon ElastiCache (DAT207) | AWS r...
Accelerating Application Performance with Amazon ElastiCache (DAT207) | AWS r...Accelerating Application Performance with Amazon ElastiCache (DAT207) | AWS r...
Accelerating Application Performance with Amazon ElastiCache (DAT207) | AWS r...
 
phptek13 - Caching and tuning fun tutorial
phptek13 - Caching and tuning fun tutorialphptek13 - Caching and tuning fun tutorial
phptek13 - Caching and tuning fun tutorial
 
Speed up R with parallel programming in the Cloud
Speed up R with parallel programming in the CloudSpeed up R with parallel programming in the Cloud
Speed up R with parallel programming in the Cloud
 

Recently uploaded

+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
?#DUbAI#??##{{(☎️+971_581248768%)**%*]'#abortion pills for sale in dubai@
 
Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire business
panagenda
 
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Victor Rentea
 

Recently uploaded (20)

TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
 
Mcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot Model
Mcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot ModelMcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot Model
Mcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot Model
 
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
 
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
 
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ..."I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
 
Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire business
 
CNIC Information System with Pakdata Cf In Pakistan
CNIC Information System with Pakdata Cf In PakistanCNIC Information System with Pakdata Cf In Pakistan
CNIC Information System with Pakdata Cf In Pakistan
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...
 
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
 
Vector Search -An Introduction in Oracle Database 23ai.pptx
Vector Search -An Introduction in Oracle Database 23ai.pptxVector Search -An Introduction in Oracle Database 23ai.pptx
Vector Search -An Introduction in Oracle Database 23ai.pptx
 
MS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectorsMS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectors
 
DEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 AmsterdamDEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
 
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century education
 
MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a Fresher
 
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
 
Corporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptxCorporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptx
 

Memcached Presentation

  • 1. Getting Creative With Memcached and AR-extensions Daniel Lockhart, Newzwag Nov 19, 2008
  • 2. Our Situation: - Using conventional Memcached techniques (caching AR queries, rendered views, etc..), we were able to eliminate almost all of the reads from the database. - Writes were still still taking quite a bit of time, as up to four separate tables were being written to each time a user answered a question.
  • 3. Abstract Solution: • Cache the new information that needs to be written to the database and periodically write all of it at once.
  • 4. Our Requirements: • Ability to store both new records and updates to existing records in Memcached. • Thread-safe - needs to be able to handle simultaneous reading/writing of data. • Ability to retrieve all of the new data periodically to commit to the database. • No stale data.
  • 5. Memcached Limitations: • No data redundancy - if Memcached goes down or runs out of space, new records and updates will be lost. • No built in locking/mutex type capability (other than using set/add) • No ability to iterate over data or determine what keys have been stored.
  • 6. Solution: Data Redundancy • Ignore it! If we commit changes to the database frequently, we can limit the damage from lost data. • The minimal risk of lost data is acceptable for our project.
  • 7. Solution: No locking/mutex • There is one aspect of Memcached that is atomic/thread-safe: incr and decr • This feature can be leveraged in creative ways to overcome our other limitations.
  • 8. Using Incr and Decr • Some of our data updates are simple counters: how many people have answered a question, how many people chose each answer, etc. • For this type of data, we can use incr and decr directly.
  • 9. Incr and Decr for Question Stats • Each attribute gets its own key: answer_count_27 will be the total number of answers for a question with ID 27, while correct_count_27 would be the count of correct answers. • Example: CACHE.incr(“answer_count_27”, 1) CACHE.incr(“correct_count_27”, 1) if answer.is_correct?
  • 10. Incr and Decr for Question Stats • Since we know all of the question IDs, we can easily periodically retrieve all of the keys to write the counters to the database. (Bulk DB updating will be explained soon) Question.find(:all).map {|x| “correct_count_#{x.id}”}
  • 11. Stretching the use of incr and decr: UserActions • Our UserAction model stores information about each action a user takes - a new record is created for every request. • None of the attributes lend themselves to be counted with incr and decr.
  • 12. Caching a UserAction • When rails starts, initialize a counter and store the starting value as the lower bounds. CACHE.add(“ua_counter”, “0”, 0, true) Cache.put(“ua_lower_bounds”, 0)
  • 13. Caching a UserAction • When a UserAction needs to be created, call incr on the counter. Since this call is atomic, each request will be guaranteed to return a unique value. ua_number = CACHE.incr(“ua_counter”)
  • 14. Caching a UserAction • Store the marshaled UserAction object with a key created from the counter value (i.e. ua_2, ua_3, etc..) Cache.add(“ua_#{ua_number}”, ua)
  • 15. Writing to the database • Call incr on the counter to get an upper bounds. • Using this number and our lower bounds number we recorded when we started rails, we can reconstruct and array of all of the keys that store the individual UserAction objects.
  • 16. Writing to the database • Use Cache.get_multi to retrieve all of the UserAction objects. user_action_objects = CACHE.get_multi(keys)
  • 17. Writing to the database • Store previous upper bounds as our new lower bounds for the next time we import. Cache.put(“ua_lower_bounds”, upper_bounds)
  • 18. Ar-Extensions • Ar-Extensions - the best RoR plugin since sliced_bread.rb • Bulk importing - commit multiple records in a single database call. • Very simple syntax:
  • 19. Updating Existing Records with AR-Extensions • Using AR-extensions with MySQL allows you to update multiple records in a single call. • This is accomplished by utilizing the MySQL feature ON DUPLICATE KEY UPDATE.
  • 20. Updating User Records • Each user record includes columns for a total score, number of questions answered, longest streak, etc. • These attributes are cached in Memcached. When a user record is retrieved from the DB, the object attributes are updated from the cache. When the attributes are updated, they are written to the cache instead of the DB.
  • 22. Flaws • No redundancy of the data. • You can never bring a Memcached server down or add a new one to the pool while people are playing. • If the background updating process stops for any reason, updates do not occur and there is a possibility that the Memcached server could fill up.
  • 23. Possible Solutions • MirroredMemcached: Write the same data to two or more Memcached server clusters. This would slow the updates down slightly, but would still be an improvement over writing directly to the DB. • A consistent hashing algorithm might mitigate the damage of losing a Memcached server instance.
  • 24. Is it worth it? • Any attempt to offload database writes into a single query(that I can think of) will be at some risk of data loss. • If the data is stored in memory, it can be lost; if it is stored on disk, it will be slow to update. • Each app has to strike its own balance between speed and data protection.