SlideShare une entreprise Scribd logo
1  sur  26
MUC
Moodle Universal Cache
Tim Hunt
Introduction
What is a cache
A place to keep data that would take time to re-compute
A cache stores values identified by a key
E.g. list of activities in a course, stored by course id
Caches may get purged at any time
Cannot store real data there, just derived values for
performance
Why have a cache system?
Developers want to do stuff with data, not re-implement
caching
Want to be able to use different back-end stores
Disc, Memcache, REDIS, …
cachestore_ is a plugin type
Admins should control which data goes in which store
Cache performance
Typical call to cache::get For a typical page
• 0.5 ms data fetched from Memcache 150
• 0.05 ms data in static acceleration 700
For comparison: typical DB query
• 3 ms 40
Using caches
Typical use
$cache = cache::make('core', 'string');
$strings = $cache->get($component);
if ($strings === false) {
$strings = load_strings($component);
$cache->set($component, $strings);
}
Defining your cache
In db/caches.php in your plugin. E.g. from lib/db/caches.php
$definitions = array(
// Used to store processed lang files.
// Keys used are revision, lang and component of the string file.
// Static acceleration size is based on student access of the site.
'string' => array(
'mode' => cache_store::MODE_APPLICATION,
'simplekeys' => true,
'simpledata' => true,
'staticacceleration' => true, // Metadata helps cache
'staticaccelerationsize' => 30, // system handle the data
'canuselocalstore' => true, // efficiently.
),
);
$string['cachedef_string'] = 'Language string cache';
Types of cache
Application – Data that applies throughout Moodle
E.g. list of activities in each course / language strings
Session – Data that is relevant while a user is logged in
E.g. list of all course categories this user can access
Request – Data within the handling of one request
E.g. list of temporary tables
Clearing the cache
$cache = cache::make('core', 'questiondata');
$cache->delete($questionid);
cache::make('core', 'questiondata')->purge();
Recommended: just clear out what has changed
Dangerous
Also not recommended: time-to-live in cache definition
Bulk actions
$cache->get_many(['key1', 'key2']);
// ['key1' => 'value1', 'key2' => 'value2']
$cache->set_many(
['key1' => 'value1', 'key2' => 'value2']);
$cache->delete_many(['key1', 'key2']);
Advanced use: data source
Data source: why?
Avoids the normal
“is this in the cache? Yes: good; No, re-compute”
Tell the cache where to get the data if it is not yet stored
Data source: definition
$definitions = array(
// Cache for question definitions. This is used by the question
// bank class. Users probably do not need to know about this cache.
// They will just call question_bank::load_question.
'questiondata' => array(
'mode' => cache_store::MODE_APPLICATION,
'simplekeys' => true, // The id of the question is used.
'requiredataguarantee' => false,
'datasource' => 'question_finder',
'datasourcefile' => 'question/engine/bank.php',
),
)
class question_finder implements cache_data_source {
public static function get_instance_for_cache(cache_definition $definition) {
return self::get_instance(); // Singleton pattern.
}
public function load_for_cache($questionid) {
global $DB;
$questiondata = $DB->get_record_sql('SELECT q.*, qc.contextid
FROM {question} q
JOIN {question_categories} qc ON q.category = qc.id
WHERE q.id = :id', array('id' => $questionid), MUST_EXIST);
get_question_options($questiondata);
return $questiondata;
}
}
Data source: use
$cache = cache::make('core', 'questiondata');
$cache->get($questionid);
Data source: implementation
public function get($key, $strictness = IGNORE_MISSING) {
// ...
$result = $this->store->get($key);
// ...
if ($result === false) {
if ($this->loader !== false) {
$result = $this->loader->get($key);
} else {
if ($this->datasource !== false) {
$result = $this->datasource->load_for_cache($key);
}
}
}
// ...
}
Cache administration
Cache administration
E.g. https://learn2acct.open.ac.uk/cache/admin.php
Cache administration: continued
Cache administration:
continued
Cache administration: continued
Issues
Memcache purging
MUC lets you store many different caches in one backend
cache::purge(); should just clear one of those caches
With Memcache, cache::purge() wipes all caches
This is one of the reasons the VLE crashed in October
Moodle 3.2 now has REDIS cache store in core
We should consider switching
Complex keys
MUC tries to support keys that are not just ints or strings
However this hurts performance – best not to use it
This probably applies to other advanced MUC features
Caching is about performance
Simple is good
Automated tests
MUC caches are automatically cleared between each unit
test or Behat test
Useful links
https://docs.moodle.org/dev/Cache_API
https://docs.moodle.org/dev/Cache_API_-_Quick_reference
cache/README.md in the code
https://docs.moodle.org/dev/The_Moodle_Universal_Cache_(MUC)

Contenu connexe

Tendances

Oracle db performance tuning
Oracle db performance tuningOracle db performance tuning
Oracle db performance tuning
Simon Huang
 
Description and Definition of HCM Data Loader
Description and Definition of HCM Data LoaderDescription and Definition of HCM Data Loader
Description and Definition of HCM Data Loader
Ashish Harbhajanka
 
20894109 te040-i procurement-test-script-on-oracle-iprocurement
20894109 te040-i procurement-test-script-on-oracle-iprocurement20894109 te040-i procurement-test-script-on-oracle-iprocurement
20894109 te040-i procurement-test-script-on-oracle-iprocurement
Pietro Prestia
 

Tendances (20)

Oracle 12c and its pluggable databases
Oracle 12c and its pluggable databasesOracle 12c and its pluggable databases
Oracle 12c and its pluggable databases
 
Five_Things_You_Might_Not_Know_About_Oracle_Database_v2.pptx
Five_Things_You_Might_Not_Know_About_Oracle_Database_v2.pptxFive_Things_You_Might_Not_Know_About_Oracle_Database_v2.pptx
Five_Things_You_Might_Not_Know_About_Oracle_Database_v2.pptx
 
Maximum Availability Architecture - Best Practices for Oracle Database 19c
Maximum Availability Architecture - Best Practices for Oracle Database 19cMaximum Availability Architecture - Best Practices for Oracle Database 19c
Maximum Availability Architecture - Best Practices for Oracle Database 19c
 
Oracle_Multitenant_19c_-_All_About_Pluggable_D.pdf
Oracle_Multitenant_19c_-_All_About_Pluggable_D.pdfOracle_Multitenant_19c_-_All_About_Pluggable_D.pdf
Oracle_Multitenant_19c_-_All_About_Pluggable_D.pdf
 
Dmv's & Performance Monitor in SQL Server
Dmv's & Performance Monitor in SQL ServerDmv's & Performance Monitor in SQL Server
Dmv's & Performance Monitor in SQL Server
 
Beginners guide to_optimizer
Beginners guide to_optimizerBeginners guide to_optimizer
Beginners guide to_optimizer
 
UniVerse Files
UniVerse FilesUniVerse Files
UniVerse Files
 
Query all roles and duties and privileges Oracle Fusion Cloud
Query all roles and duties and privileges Oracle Fusion CloudQuery all roles and duties and privileges Oracle Fusion Cloud
Query all roles and duties and privileges Oracle Fusion Cloud
 
Oracle db performance tuning
Oracle db performance tuningOracle db performance tuning
Oracle db performance tuning
 
Oracle Cloud ERP Report and Analytics | What are Cloud ERP reporting Options ...
Oracle Cloud ERP Report and Analytics | What are Cloud ERP reporting Options ...Oracle Cloud ERP Report and Analytics | What are Cloud ERP reporting Options ...
Oracle Cloud ERP Report and Analytics | What are Cloud ERP reporting Options ...
 
Oracle Core HR with Screen Shots
Oracle Core HR with Screen ShotsOracle Core HR with Screen Shots
Oracle Core HR with Screen Shots
 
Oracle DBA
Oracle DBAOracle DBA
Oracle DBA
 
Oracle 資料庫檔案介紹
Oracle 資料庫檔案介紹Oracle 資料庫檔案介紹
Oracle 資料庫檔案介紹
 
Description and Definition of HCM Data Loader
Description and Definition of HCM Data LoaderDescription and Definition of HCM Data Loader
Description and Definition of HCM Data Loader
 
(ZDM) Zero Downtime DB Migration to Oracle Cloud
(ZDM) Zero Downtime DB Migration to Oracle Cloud(ZDM) Zero Downtime DB Migration to Oracle Cloud
(ZDM) Zero Downtime DB Migration to Oracle Cloud
 
Hcm export data rahul vishwanath
Hcm export data rahul vishwanathHcm export data rahul vishwanath
Hcm export data rahul vishwanath
 
Oracle Fusion Financial Report Centre Reporting Beginner course
Oracle Fusion Financial Report Centre Reporting Beginner courseOracle Fusion Financial Report Centre Reporting Beginner course
Oracle Fusion Financial Report Centre Reporting Beginner course
 
BI Publisher Data model design document
BI Publisher Data model design documentBI Publisher Data model design document
BI Publisher Data model design document
 
20894109 te040-i procurement-test-script-on-oracle-iprocurement
20894109 te040-i procurement-test-script-on-oracle-iprocurement20894109 te040-i procurement-test-script-on-oracle-iprocurement
20894109 te040-i procurement-test-script-on-oracle-iprocurement
 
Prevent merging columns in excel output using rtf template
Prevent merging columns in excel output using rtf templatePrevent merging columns in excel output using rtf template
Prevent merging columns in excel output using rtf template
 

Similaire à MUC - Moodle Universal Cache

Dependency Injection with PHP and PHP 5.3
Dependency Injection with PHP and PHP 5.3Dependency Injection with PHP and PHP 5.3
Dependency Injection with PHP and PHP 5.3
Fabien Potencier
 
CHI-YAPC-2009
CHI-YAPC-2009CHI-YAPC-2009
CHI-YAPC-2009
jonswar
 
Dependency injection in PHP 5.3/5.4
Dependency injection in PHP 5.3/5.4Dependency injection in PHP 5.3/5.4
Dependency injection in PHP 5.3/5.4
Fabien Potencier
 
Dependency injection - phpday 2010
Dependency injection - phpday 2010Dependency injection - phpday 2010
Dependency injection - phpday 2010
Fabien Potencier
 
Dependency Injection IPC 201
Dependency Injection IPC 201Dependency Injection IPC 201
Dependency Injection IPC 201
Fabien Potencier
 
Dependency Injection - ConFoo 2010
Dependency Injection - ConFoo 2010Dependency Injection - ConFoo 2010
Dependency Injection - ConFoo 2010
Fabien Potencier
 
Decouple Your Code For Reusability (International PHP Conference / IPC 2008)
Decouple Your Code For Reusability (International PHP Conference / IPC 2008)Decouple Your Code For Reusability (International PHP Conference / IPC 2008)
Decouple Your Code For Reusability (International PHP Conference / IPC 2008)
Fabien Potencier
 
DrupalCamp Foz - Novas APIs Drupal 7
DrupalCamp Foz - Novas APIs Drupal 7DrupalCamp Foz - Novas APIs Drupal 7
DrupalCamp Foz - Novas APIs Drupal 7
chuvainc
 

Similaire à MUC - Moodle Universal Cache (20)

Built-in query caching for all PHP MySQL extensions/APIs
Built-in query caching for all PHP MySQL extensions/APIsBuilt-in query caching for all PHP MySQL extensions/APIs
Built-in query caching for all PHP MySQL extensions/APIs
 
Dependency Injection with PHP and PHP 5.3
Dependency Injection with PHP and PHP 5.3Dependency Injection with PHP and PHP 5.3
Dependency Injection with PHP and PHP 5.3
 
Dependency Injection with PHP 5.3
Dependency Injection with PHP 5.3Dependency Injection with PHP 5.3
Dependency Injection with PHP 5.3
 
CHI-YAPC-2009
CHI-YAPC-2009CHI-YAPC-2009
CHI-YAPC-2009
 
Caching in WordPress
Caching in WordPressCaching in WordPress
Caching in WordPress
 
Drupal 7 Queues
Drupal 7 QueuesDrupal 7 Queues
Drupal 7 Queues
 
Dependency injection in PHP 5.3/5.4
Dependency injection in PHP 5.3/5.4Dependency injection in PHP 5.3/5.4
Dependency injection in PHP 5.3/5.4
 
Dependency injection - phpday 2010
Dependency injection - phpday 2010Dependency injection - phpday 2010
Dependency injection - phpday 2010
 
Dependency Injection IPC 201
Dependency Injection IPC 201Dependency Injection IPC 201
Dependency Injection IPC 201
 
Dependency Injection - ConFoo 2010
Dependency Injection - ConFoo 2010Dependency Injection - ConFoo 2010
Dependency Injection - ConFoo 2010
 
Dependency Injection
Dependency InjectionDependency Injection
Dependency Injection
 
Decouple Your Code For Reusability (International PHP Conference / IPC 2008)
Decouple Your Code For Reusability (International PHP Conference / IPC 2008)Decouple Your Code For Reusability (International PHP Conference / IPC 2008)
Decouple Your Code For Reusability (International PHP Conference / IPC 2008)
 
About Data::ObjectDriver
About Data::ObjectDriverAbout Data::ObjectDriver
About Data::ObjectDriver
 
Lazy evaluation drupal camp moscow 2014
Lazy evaluation drupal camp moscow 2014Lazy evaluation drupal camp moscow 2014
Lazy evaluation drupal camp moscow 2014
 
Caching and Scaling WordPress using Fragment Caching
Caching and Scaling WordPress using Fragment CachingCaching and Scaling WordPress using Fragment Caching
Caching and Scaling WordPress using Fragment Caching
 
Intro to advanced caching in WordPress
Intro to advanced caching in WordPressIntro to advanced caching in WordPress
Intro to advanced caching in WordPress
 
WordCamp San Francisco 2011: Transients, Caching, and the Complexities of Mul...
WordCamp San Francisco 2011: Transients, Caching, and the Complexities of Mul...WordCamp San Francisco 2011: Transients, Caching, and the Complexities of Mul...
WordCamp San Francisco 2011: Transients, Caching, and the Complexities of Mul...
 
DrupalCamp Foz - Novas APIs Drupal 7
DrupalCamp Foz - Novas APIs Drupal 7DrupalCamp Foz - Novas APIs Drupal 7
DrupalCamp Foz - Novas APIs Drupal 7
 
Speed Things Up with Transients
Speed Things Up with TransientsSpeed Things Up with Transients
Speed Things Up with Transients
 
mysqlnd query cache plugin: user-defined storage handler
mysqlnd query cache plugin: user-defined storage handlermysqlnd query cache plugin: user-defined storage handler
mysqlnd query cache plugin: user-defined storage handler
 

Plus de Tim Hunt

Plus de Tim Hunt (14)

Writing better Behat tests
Writing better Behat testsWriting better Behat tests
Writing better Behat tests
 
What’s next for the Quiz and Question bank and for Moodle community collabora...
What’s next for the Quiz and Question bank and for Moodle community collabora...What’s next for the Quiz and Question bank and for Moodle community collabora...
What’s next for the Quiz and Question bank and for Moodle community collabora...
 
Question bank improvements in Moodle 4.0 : A successful community collaboration
Question bank improvements in Moodle 4.0 : A successful community collaborationQuestion bank improvements in Moodle 4.0 : A successful community collaboration
Question bank improvements in Moodle 4.0 : A successful community collaboration
 
Looking after the Open University's Moodle
Looking after the Open University's MoodleLooking after the Open University's Moodle
Looking after the Open University's Moodle
 
Embedding questions anywhere in Moodle
Embedding questions anywhere in MoodleEmbedding questions anywhere in Moodle
Embedding questions anywhere in Moodle
 
Hosting STACK at scale
Hosting STACK at scaleHosting STACK at scale
Hosting STACK at scale
 
Moodle questions without the quiz
Moodle questions without the quizMoodle questions without the quiz
Moodle questions without the quiz
 
2017 UK/IE MoodleMoot: What makes a good moodle quiz? Lessons from the Open U...
2017 UK/IE MoodleMoot: What makes a good moodle quiz? Lessons from the Open U...2017 UK/IE MoodleMoot: What makes a good moodle quiz? Lessons from the Open U...
2017 UK/IE MoodleMoot: What makes a good moodle quiz? Lessons from the Open U...
 
I wish I could believe you: the frustrating unreliability of some assessment ...
I wish I could believe you: the frustrating unreliability of some assessment ...I wish I could believe you: the frustrating unreliability of some assessment ...
I wish I could believe you: the frustrating unreliability of some assessment ...
 
The Moodle quiz at the Open University
The Moodle quiz at the Open UniversityThe Moodle quiz at the Open University
The Moodle quiz at the Open University
 
The Moodle Quiz at the Open University: how we use it & how that helps students
The Moodle Quiz at the Open University: how we use it & how that helps studentsThe Moodle Quiz at the Open University: how we use it & how that helps students
The Moodle Quiz at the Open University: how we use it & how that helps students
 
2012 Computer-Assisted Assessment
2012 Computer-Assisted Assessment2012 Computer-Assisted Assessment
2012 Computer-Assisted Assessment
 
Moodle’s building blocks for eAssessment tools
Moodle’s building blocks for eAssessment toolsMoodle’s building blocks for eAssessment tools
Moodle’s building blocks for eAssessment tools
 
A basic introduction to the Moodle architecture
A basic introduction to the Moodle architectureA basic introduction to the Moodle architecture
A basic introduction to the Moodle architecture
 

Dernier

TECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providerTECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service provider
mohitmore19
 
introduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdf
introduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdfintroduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdf
introduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdf
VishalKumarJha10
 
AI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
AI Mastery 201: Elevating Your Workflow with Advanced LLM TechniquesAI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
AI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
VictorSzoltysek
 
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICECHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
9953056974 Low Rate Call Girls In Saket, Delhi NCR
 

Dernier (20)

TECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providerTECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service provider
 
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
 
Define the academic and professional writing..pdf
Define the academic and professional writing..pdfDefine the academic and professional writing..pdf
Define the academic and professional writing..pdf
 
How To Use Server-Side Rendering with Nuxt.js
How To Use Server-Side Rendering with Nuxt.jsHow To Use Server-Side Rendering with Nuxt.js
How To Use Server-Side Rendering with Nuxt.js
 
introduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdf
introduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdfintroduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdf
introduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdf
 
A Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docxA Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docx
 
Microsoft AI Transformation Partner Playbook.pdf
Microsoft AI Transformation Partner Playbook.pdfMicrosoft AI Transformation Partner Playbook.pdf
Microsoft AI Transformation Partner Playbook.pdf
 
Direct Style Effect Systems - The Print[A] Example - A Comprehension Aid
Direct Style Effect Systems -The Print[A] Example- A Comprehension AidDirect Style Effect Systems -The Print[A] Example- A Comprehension Aid
Direct Style Effect Systems - The Print[A] Example - A Comprehension Aid
 
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
 
Introducing Microsoft’s new Enterprise Work Management (EWM) Solution
Introducing Microsoft’s new Enterprise Work Management (EWM) SolutionIntroducing Microsoft’s new Enterprise Work Management (EWM) Solution
Introducing Microsoft’s new Enterprise Work Management (EWM) Solution
 
Azure_Native_Qumulo_High_Performance_Compute_Benchmarks.pdf
Azure_Native_Qumulo_High_Performance_Compute_Benchmarks.pdfAzure_Native_Qumulo_High_Performance_Compute_Benchmarks.pdf
Azure_Native_Qumulo_High_Performance_Compute_Benchmarks.pdf
 
Exploring the Best Video Editing App.pdf
Exploring the Best Video Editing App.pdfExploring the Best Video Editing App.pdf
Exploring the Best Video Editing App.pdf
 
AI & Machine Learning Presentation Template
AI & Machine Learning Presentation TemplateAI & Machine Learning Presentation Template
AI & Machine Learning Presentation Template
 
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
 
AI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
AI Mastery 201: Elevating Your Workflow with Advanced LLM TechniquesAI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
AI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
 
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
 
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
 
Software Quality Assurance Interview Questions
Software Quality Assurance Interview QuestionsSoftware Quality Assurance Interview Questions
Software Quality Assurance Interview Questions
 
Diamond Application Development Crafting Solutions with Precision
Diamond Application Development Crafting Solutions with PrecisionDiamond Application Development Crafting Solutions with Precision
Diamond Application Development Crafting Solutions with Precision
 
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICECHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
 

MUC - Moodle Universal Cache

  • 3. What is a cache A place to keep data that would take time to re-compute A cache stores values identified by a key E.g. list of activities in a course, stored by course id Caches may get purged at any time Cannot store real data there, just derived values for performance
  • 4. Why have a cache system? Developers want to do stuff with data, not re-implement caching Want to be able to use different back-end stores Disc, Memcache, REDIS, … cachestore_ is a plugin type Admins should control which data goes in which store
  • 5. Cache performance Typical call to cache::get For a typical page • 0.5 ms data fetched from Memcache 150 • 0.05 ms data in static acceleration 700 For comparison: typical DB query • 3 ms 40
  • 7. Typical use $cache = cache::make('core', 'string'); $strings = $cache->get($component); if ($strings === false) { $strings = load_strings($component); $cache->set($component, $strings); }
  • 8. Defining your cache In db/caches.php in your plugin. E.g. from lib/db/caches.php $definitions = array( // Used to store processed lang files. // Keys used are revision, lang and component of the string file. // Static acceleration size is based on student access of the site. 'string' => array( 'mode' => cache_store::MODE_APPLICATION, 'simplekeys' => true, 'simpledata' => true, 'staticacceleration' => true, // Metadata helps cache 'staticaccelerationsize' => 30, // system handle the data 'canuselocalstore' => true, // efficiently. ), ); $string['cachedef_string'] = 'Language string cache';
  • 9. Types of cache Application – Data that applies throughout Moodle E.g. list of activities in each course / language strings Session – Data that is relevant while a user is logged in E.g. list of all course categories this user can access Request – Data within the handling of one request E.g. list of temporary tables
  • 10. Clearing the cache $cache = cache::make('core', 'questiondata'); $cache->delete($questionid); cache::make('core', 'questiondata')->purge(); Recommended: just clear out what has changed Dangerous Also not recommended: time-to-live in cache definition
  • 11. Bulk actions $cache->get_many(['key1', 'key2']); // ['key1' => 'value1', 'key2' => 'value2'] $cache->set_many( ['key1' => 'value1', 'key2' => 'value2']); $cache->delete_many(['key1', 'key2']);
  • 13. Data source: why? Avoids the normal “is this in the cache? Yes: good; No, re-compute” Tell the cache where to get the data if it is not yet stored
  • 14. Data source: definition $definitions = array( // Cache for question definitions. This is used by the question // bank class. Users probably do not need to know about this cache. // They will just call question_bank::load_question. 'questiondata' => array( 'mode' => cache_store::MODE_APPLICATION, 'simplekeys' => true, // The id of the question is used. 'requiredataguarantee' => false, 'datasource' => 'question_finder', 'datasourcefile' => 'question/engine/bank.php', ), )
  • 15. class question_finder implements cache_data_source { public static function get_instance_for_cache(cache_definition $definition) { return self::get_instance(); // Singleton pattern. } public function load_for_cache($questionid) { global $DB; $questiondata = $DB->get_record_sql('SELECT q.*, qc.contextid FROM {question} q JOIN {question_categories} qc ON q.category = qc.id WHERE q.id = :id', array('id' => $questionid), MUST_EXIST); get_question_options($questiondata); return $questiondata; } } Data source: use $cache = cache::make('core', 'questiondata'); $cache->get($questionid);
  • 16. Data source: implementation public function get($key, $strictness = IGNORE_MISSING) { // ... $result = $this->store->get($key); // ... if ($result === false) { if ($this->loader !== false) { $result = $this->loader->get($key); } else { if ($this->datasource !== false) { $result = $this->datasource->load_for_cache($key); } } } // ... }
  • 23. Memcache purging MUC lets you store many different caches in one backend cache::purge(); should just clear one of those caches With Memcache, cache::purge() wipes all caches This is one of the reasons the VLE crashed in October Moodle 3.2 now has REDIS cache store in core We should consider switching
  • 24. Complex keys MUC tries to support keys that are not just ints or strings However this hurts performance – best not to use it This probably applies to other advanced MUC features Caching is about performance Simple is good
  • 25. Automated tests MUC caches are automatically cleared between each unit test or Behat test