SlideShare a Scribd company logo
Mysqlnd Query Cache
<Insert Picture Here>
MySQL Client Side Caching
Johannes Schlüter
Twitter: @phperror
MySQL Engineering – Connectors and Client Connectivity
# pecl install mysqlnd_qc-beta
Gracias por vuestra atención!
mysqlnd
Server API (SAPI)
CGI CLI Embed ISAPI NSAPI phttpd thttpd ...
Zend Engine PHP Runtime
PHP Extensions
bcmath mysql mysqli mysqlnd pdo pdo_mysql xml ...
PHP 5.3 and mysqlndPHP
PHPMemory
PHPStreams
Infrastructure
mysqlnd – MySQL native driver for PHP
MySQL Server
ext/mysql mysqli PDO_mysql
…
PHP Module (Extension) API
Building PHP with mysqlnd
• ./configure 
--with-mysql=mysqlnd 
--with-mysqli=msqlnd 
--with-pdo-mysql=mysqlnd
• Default on Windows and some distributions
mysqlnd vs. libmysql
MySQL Server MySQL Server
mysqlnd libmysql
PHP PHP
PHP Memory
libmysql Memory
PHP Memory
PHP Memory
copy
copy
usedirectly
copy
mysqlnd Statistics
• Around 150 statistic values collected
• mysqli_get_client_stats (),
mysqli_get_connection_stats()
Asynchronous Queries
/* Do something */
PHP Script MySQL
query
result
query
poll
result
$conn = new MySQLi(...);
$conn->query(
"SELECT * FROM t WHERE ....",
MYSQLI_ASYNC);
/* Process query results */
mysqli_poll($links, $errors, $reject, 1);
Sharding
<?php
…
?>
Sharding
foreach ($all_links as $link)
$link->query("SELECT 'test' ", MYSQLI_ASYNC);
$processed = 0;
do {
$links = $all_links;
if (!mysqli_poll($links, $errors, $reject, 1)) continue; /* TIMEOUT */
foreach ($links as $link) {
if ($result = $link->reap_async_query()) {
print_r($result->fetch_row());
mysqli_free_result($result);
$processed++;
}
}
} while ($processed < count($all_links));
mysqlnd plugins
Plugin Hook
mysqlnd Query
mysqli::query()mysql_query() PDO::query()
Wire Protocol
Plugin Hook
Network
Drupal, Symphony, phpMyFAQ, phpMyAdmin, Oxid, ...
ext/mysql, ext/mysqli, ext/PDO_MYSQL
MySQL Server
mysqlnd
Load Balancing Monitoring Performance
mysqlnd plugin
Query Cache Plugin vs. MySQL Proxy
Application client Application client Application client
MySQL Proxy
PHP client PHP client PHP client
mysqlnd pluginmysqlnd plugin mysqlnd plugin
MySQL Server
MySQL Server
Experimental Extensions
• By Oracle:
– mysqlnd_sip
– mysqlnd_mc
– mysqlnd_ms
– mysqlnd_pscache
• By Community:
– mysqlnd_uh
(David Soria Parra /
Mayflower GmbH)
• http://pecl.php.net/
The Database Is The Bottleneck
Caching!
“Traditional” Caches
• MySQL Server Cache
– MySQL Query Cache
• Application-Level Cache
– PEAR::Cache, Zend_Cache, …
MySQL Query Cache (Server-Side)
✔
Integrated with the MySQL Server
✔
No application changes
✔
Automatic invalidation
–
table based
✗
Needs network communication with server
✗
Needs server resources (memory, CPU)
Application-Level Caches
✔
Can cache higher level structures
– Complete rendered HTML blocks
✔
Multiple backends
– Can be shared over multiple servers (via memcache etc.)
✗
No automatic invalidation
✗
Requires application changes
<Insert Picture Here>
Introducing:
mysqlnd Client Side Cache
# pecl install mysqlnd_qc-beta
Andrey Hristov
Ulf Wendel
mysqlnd Query Cache
PHP
mysql / mysqli / PDO_mysql
mysqlnd
Cache Backend
Query Cache
MySQL Server
SELECT a
FROM t No!
SELECT a
FROM t
ResultResult
Local Memory, APC,
Memcache, Custom Handler
Key Properties
• Transparent
– PHP Extension hooking into mysqlnd
• Works with ext/mysql, mysqli, pdo_mysql
• Pluggable storage handler
– By default: local memory, APC, memcache, SQLite
– PHP Userspace
• Invalidation via TTL
– No automatic invalidation by server
– Custom handlers may use custom invalidation logic
Transparent?
$mysqli = new mysqli($host, $user, $pw, $db);
$sql = “SELECT SLEEP(10) FROM table”;
$start = microtime(true);
$res = $mysqli->query($sql);
$res = $mysqli->query($sql);
$end = microtime(true);
echo $end - $start;
→ 20.019539117813
Transparent?
$mysqli = new mysqli($host, $user, $pw, $db);
$sql = sprintf(“/*%s*/SELECT SLEEP(10) FROM table”,
MYSQLND_QC_ENABLE_SWITCH);
$start = microtime(true);
$res = $mysqli->query($sql);
$res = $mysqli->query($sql);
$end = microtime(true);
echo $end - $start;
→ 10.142804088593
Transparent!
mysqlnd_qc.cache_by_default = 1
!Usually you should NOT do this!
SQL Hints
• MYSQLND_QC_ENABLE_SWITCH
– qc=on
• MYSQLND_QC_DISABLE_SWITCH
– qc=off
• MYSQLND_QC_TTL_SWITCH
– qc_ttl=
Storage Handlers
●
Storage
– Scope: request, process, machine, multi-machine
– Location: distance to cache
– Replacement strategy
– Slam defense strategy
●
Decide what to cache
– is_select() - detect SQL hints
●
Extended statistics
– Storage statistics, traces, timings
Cache Expiry
Client 1
MySQL
Client 2...n
Cache Hit
MySQL
Client 1 Client 2...n
Slam Defense
Client 1
MySQL
Client 2...n
Expired
MySQL
Client 1 Client 2...n
Cache Hit
Refresh
Core Statistics
• Collected by: mysqlnd_qc core
– php.net/manual/en/function.mysqlnd_qc_get_core_stats.php
• Scope: process
– Process: mysqlnd_qc_get_core_stats()
– Aggregated values from all PHP MySQL APIs
• Contents: wide range
– Cache usage and efficiency
– Network related
– Timings
Query Statistics and Backtraces
• Collected by: mysqlnd_qc core
– php.net/manual/en/function.mysqlnd_qc_get_query_trace_log
.php
• Scope: process
– mysqlnd_qc_get_query_trace_log()
– mysqlnd_qc_get_normalized_query_trace_log()
• Contents
– Origin - backtrace
– Timings
Storage Handler Statistics
• Collected by: storage handler
– php.net/manual/en/function..mysqlnd_qc_get_cache_info.php
• Scope: cache entry
– Depends on storage handler scope
– Aggregated values from all PHP MySQL APIs
• Contents: none or assorted
– Depends on storage handler support
– APC: timings, hit ratio, result set size
– Default: APC plus result set meta data
User-Defined Storage Handler
• Procedural
– php.net/manual/en/function.mysqlnd_qc_set_user_handlers.php
– Callback functions
• Object oriented
– slideshare.net/nixnutz/mysqlnd-query-cache-plugin-userdefined-
storage-handler
– Interface mysqlnd_qc_handler
• Extending mysqlnd_qc_handler_default
<?php
/* auto_prepend_file = /path/to/prepend.php */
class my_qc extends mysqlnd_qc_handler_default
{
public function is_select($query)
{
if (preg_match("@from employees where@ism", $query))
{
/* cache query for mysqlnd_qc.ttl seconds */
return true;
}
return parent::is_select($query);
}
}
$qc = new my_qc();
mysqlnd_qc_change_handler($qc);
?>
Resources
• php.net/mysqlnd_qc
– Installation, Examples, Functions
• php.net/mysqlnd
– Introduction, Changes, C plugin API
• slideshare.net/nixnutz/presentations
– QC Basics
– QC User defined storage handler
– QC Statistics
– QC Benchmark impressions
Mysqlnd Query Cache
The preceding is intended to outline our general
product direction. It is intended for information
purposes only, and may not be incorporated into any
contract. It is not a commitment to deliver any
material, code, or functionality, and should not be
relied upon in making purchasing decisions.
The development, release, and timing of any
features or functionality described for Oracle’s
products remains at the sole discretion of Oracle.
Mysqlnd Query Cache
Mysqlnd Query Cache

More Related Content

PPT
Understanding MySql locking issues
PDF
MySQL Manchester TT - Performance Tuning
PPT
MySQL Performance Tuning at COSCUP 2014
PDF
MySQL Performance Metrics that Matter
PDF
MySQL Server Defaults
PDF
MySQL: From Single Instance to Big Data
PDF
MySQL NoSQL APIs
PDF
Mysql 57-upcoming-changes
Understanding MySql locking issues
MySQL Manchester TT - Performance Tuning
MySQL Performance Tuning at COSCUP 2014
MySQL Performance Metrics that Matter
MySQL Server Defaults
MySQL: From Single Instance to Big Data
MySQL NoSQL APIs
Mysql 57-upcoming-changes

What's hot (20)

ODP
MySQL 5.7 - What's new and How to upgrade
PDF
MySQL Performance Tuning. Part 1: MySQL Configuration (includes MySQL 5.7)
PDF
Upgrade to MySQL 5.7 and latest news planned for MySQL 8
PDF
My sql 5.7-upcoming-changes-v2
PDF
MySQL Performance - Best practices
PDF
Technical Introduction to PostgreSQL and PPAS
PDF
My sql5.7 whatsnew_presentedatgids2015
PDF
Mysql User Camp : 20th June - Mysql New Features
PDF
Tool it Up! - Session #3 - MySQL
PDF
MySQL :What's New #GIDS16
PDF
MySQL configuration - The most important Variables
PDF
Upcoming changes in MySQL 5.7
PDF
Mysql User Camp : 20-June-14 : Mysql Fabric
PDF
MySQL For Linux Sysadmins
PDF
MySQL Tuning
PDF
MySQL Performance Tuning Variables
PPT
MySQL Performance Tuning - GNUnify 2010
PDF
Optimizing MySQL for Cascade Server
PPTX
Proxysql use case scenarios fosdem17
PDF
Performance Tuning Best Practices
MySQL 5.7 - What's new and How to upgrade
MySQL Performance Tuning. Part 1: MySQL Configuration (includes MySQL 5.7)
Upgrade to MySQL 5.7 and latest news planned for MySQL 8
My sql 5.7-upcoming-changes-v2
MySQL Performance - Best practices
Technical Introduction to PostgreSQL and PPAS
My sql5.7 whatsnew_presentedatgids2015
Mysql User Camp : 20th June - Mysql New Features
Tool it Up! - Session #3 - MySQL
MySQL :What's New #GIDS16
MySQL configuration - The most important Variables
Upcoming changes in MySQL 5.7
Mysql User Camp : 20-June-14 : Mysql Fabric
MySQL For Linux Sysadmins
MySQL Tuning
MySQL Performance Tuning Variables
MySQL Performance Tuning - GNUnify 2010
Optimizing MySQL for Cascade Server
Proxysql use case scenarios fosdem17
Performance Tuning Best Practices
Ad

Similar to Mysqlnd Query Cache (20)

ODP
Built-in query caching for all PHP MySQL extensions/APIs
ODP
mysqlnd query cache plugin: user-defined storage handler
ODP
Mysqlnd query cache plugin statistics and tuning
PDF
Ipc mysql php
PPTX
20141011 mastering mysqlnd
PDF
MySQL PHP native driver : Advanced Functions / PHP forum Paris 2013
ODP
MySQL native driver for PHP (mysqlnd) - Introduction and overview, Edition 2011
PDF
Mysql tracing
PDF
Mysql tracing
ODP
Caching and tuning fun for high scalability
ODP
Award-winning technology: Oxid loves the query cache
PDF
PostgreSQL Query Cache - "pqc"
PDF
The Native NDB Engine for Memcached
PDF
Mysqlnd, an unknown powerful PHP extension
KEY
Introduction to memcached
PPTX
Fundamentals of performance tuning PHP on IBM i
KEY
Intro to PECL/mysqlnd_ms (4/7/2011)
PPTX
Php and database functionality
PPTX
Php and database functionality
PPTX
PHP and database functionality
Built-in query caching for all PHP MySQL extensions/APIs
mysqlnd query cache plugin: user-defined storage handler
Mysqlnd query cache plugin statistics and tuning
Ipc mysql php
20141011 mastering mysqlnd
MySQL PHP native driver : Advanced Functions / PHP forum Paris 2013
MySQL native driver for PHP (mysqlnd) - Introduction and overview, Edition 2011
Mysql tracing
Mysql tracing
Caching and tuning fun for high scalability
Award-winning technology: Oxid loves the query cache
PostgreSQL Query Cache - "pqc"
The Native NDB Engine for Memcached
Mysqlnd, an unknown powerful PHP extension
Introduction to memcached
Fundamentals of performance tuning PHP on IBM i
Intro to PECL/mysqlnd_ms (4/7/2011)
Php and database functionality
Php and database functionality
PHP and database functionality
Ad

More from Anis Berejeb (6)

PDF
Perf tuning2
PDF
Explain2
PDF
Advanced Date/Time Handling with PHP
PDF
APC & Memcache the High Performance Duo
PDF
Barcelona mysqlnd qc
PDF
Barcelona 2010 hidden_features
Perf tuning2
Explain2
Advanced Date/Time Handling with PHP
APC & Memcache the High Performance Duo
Barcelona mysqlnd qc
Barcelona 2010 hidden_features

Recently uploaded (20)

PDF
The Rise and Fall of 3GPP – Time for a Sabbatical?
PDF
Empathic Computing: Creating Shared Understanding
PDF
Optimiser vos workloads AI/ML sur Amazon EC2 et AWS Graviton
PDF
Reach Out and Touch Someone: Haptics and Empathic Computing
PPTX
20250228 LYD VKU AI Blended-Learning.pptx
PDF
How UI/UX Design Impacts User Retention in Mobile Apps.pdf
PPTX
MYSQL Presentation for SQL database connectivity
PDF
Chapter 3 Spatial Domain Image Processing.pdf
PDF
Approach and Philosophy of On baking technology
PPTX
Effective Security Operations Center (SOC) A Modern, Strategic, and Threat-In...
PPT
“AI and Expert System Decision Support & Business Intelligence Systems”
PPTX
sap open course for s4hana steps from ECC to s4
PDF
Mobile App Security Testing_ A Comprehensive Guide.pdf
PDF
Encapsulation_ Review paper, used for researhc scholars
PDF
Profit Center Accounting in SAP S/4HANA, S4F28 Col11
PPTX
Spectroscopy.pptx food analysis technology
PDF
Dropbox Q2 2025 Financial Results & Investor Presentation
PDF
MIND Revenue Release Quarter 2 2025 Press Release
PPTX
Understanding_Digital_Forensics_Presentation.pptx
PDF
Architecting across the Boundaries of two Complex Domains - Healthcare & Tech...
The Rise and Fall of 3GPP – Time for a Sabbatical?
Empathic Computing: Creating Shared Understanding
Optimiser vos workloads AI/ML sur Amazon EC2 et AWS Graviton
Reach Out and Touch Someone: Haptics and Empathic Computing
20250228 LYD VKU AI Blended-Learning.pptx
How UI/UX Design Impacts User Retention in Mobile Apps.pdf
MYSQL Presentation for SQL database connectivity
Chapter 3 Spatial Domain Image Processing.pdf
Approach and Philosophy of On baking technology
Effective Security Operations Center (SOC) A Modern, Strategic, and Threat-In...
“AI and Expert System Decision Support & Business Intelligence Systems”
sap open course for s4hana steps from ECC to s4
Mobile App Security Testing_ A Comprehensive Guide.pdf
Encapsulation_ Review paper, used for researhc scholars
Profit Center Accounting in SAP S/4HANA, S4F28 Col11
Spectroscopy.pptx food analysis technology
Dropbox Q2 2025 Financial Results & Investor Presentation
MIND Revenue Release Quarter 2 2025 Press Release
Understanding_Digital_Forensics_Presentation.pptx
Architecting across the Boundaries of two Complex Domains - Healthcare & Tech...

Mysqlnd Query Cache

  • 2. <Insert Picture Here> MySQL Client Side Caching Johannes Schlüter Twitter: @phperror MySQL Engineering – Connectors and Client Connectivity
  • 3. # pecl install mysqlnd_qc-beta
  • 4. Gracias por vuestra atención!
  • 5. mysqlnd Server API (SAPI) CGI CLI Embed ISAPI NSAPI phttpd thttpd ... Zend Engine PHP Runtime PHP Extensions bcmath mysql mysqli mysqlnd pdo pdo_mysql xml ...
  • 6. PHP 5.3 and mysqlndPHP PHPMemory PHPStreams Infrastructure mysqlnd – MySQL native driver for PHP MySQL Server ext/mysql mysqli PDO_mysql … PHP Module (Extension) API
  • 7. Building PHP with mysqlnd • ./configure --with-mysql=mysqlnd --with-mysqli=msqlnd --with-pdo-mysql=mysqlnd • Default on Windows and some distributions
  • 8. mysqlnd vs. libmysql MySQL Server MySQL Server mysqlnd libmysql PHP PHP PHP Memory libmysql Memory PHP Memory PHP Memory copy copy usedirectly copy
  • 9. mysqlnd Statistics • Around 150 statistic values collected • mysqli_get_client_stats (), mysqli_get_connection_stats()
  • 10. Asynchronous Queries /* Do something */ PHP Script MySQL query result query poll result $conn = new MySQLi(...); $conn->query( "SELECT * FROM t WHERE ....", MYSQLI_ASYNC); /* Process query results */ mysqli_poll($links, $errors, $reject, 1);
  • 12. Sharding foreach ($all_links as $link) $link->query("SELECT 'test' ", MYSQLI_ASYNC); $processed = 0; do { $links = $all_links; if (!mysqli_poll($links, $errors, $reject, 1)) continue; /* TIMEOUT */ foreach ($links as $link) { if ($result = $link->reap_async_query()) { print_r($result->fetch_row()); mysqli_free_result($result); $processed++; } } } while ($processed < count($all_links));
  • 13. mysqlnd plugins Plugin Hook mysqlnd Query mysqli::query()mysql_query() PDO::query() Wire Protocol Plugin Hook Network
  • 14. Drupal, Symphony, phpMyFAQ, phpMyAdmin, Oxid, ... ext/mysql, ext/mysqli, ext/PDO_MYSQL MySQL Server mysqlnd Load Balancing Monitoring Performance mysqlnd plugin
  • 15. Query Cache Plugin vs. MySQL Proxy Application client Application client Application client MySQL Proxy PHP client PHP client PHP client mysqlnd pluginmysqlnd plugin mysqlnd plugin MySQL Server MySQL Server
  • 16. Experimental Extensions • By Oracle: – mysqlnd_sip – mysqlnd_mc – mysqlnd_ms – mysqlnd_pscache • By Community: – mysqlnd_uh (David Soria Parra / Mayflower GmbH) • http://pecl.php.net/
  • 17. The Database Is The Bottleneck
  • 19. “Traditional” Caches • MySQL Server Cache – MySQL Query Cache • Application-Level Cache – PEAR::Cache, Zend_Cache, …
  • 20. MySQL Query Cache (Server-Side) ✔ Integrated with the MySQL Server ✔ No application changes ✔ Automatic invalidation – table based ✗ Needs network communication with server ✗ Needs server resources (memory, CPU)
  • 21. Application-Level Caches ✔ Can cache higher level structures – Complete rendered HTML blocks ✔ Multiple backends – Can be shared over multiple servers (via memcache etc.) ✗ No automatic invalidation ✗ Requires application changes
  • 23. # pecl install mysqlnd_qc-beta Andrey Hristov Ulf Wendel
  • 24. mysqlnd Query Cache PHP mysql / mysqli / PDO_mysql mysqlnd Cache Backend Query Cache MySQL Server SELECT a FROM t No! SELECT a FROM t ResultResult Local Memory, APC, Memcache, Custom Handler
  • 25. Key Properties • Transparent – PHP Extension hooking into mysqlnd • Works with ext/mysql, mysqli, pdo_mysql • Pluggable storage handler – By default: local memory, APC, memcache, SQLite – PHP Userspace • Invalidation via TTL – No automatic invalidation by server – Custom handlers may use custom invalidation logic
  • 26. Transparent? $mysqli = new mysqli($host, $user, $pw, $db); $sql = “SELECT SLEEP(10) FROM table”; $start = microtime(true); $res = $mysqli->query($sql); $res = $mysqli->query($sql); $end = microtime(true); echo $end - $start; → 20.019539117813
  • 27. Transparent? $mysqli = new mysqli($host, $user, $pw, $db); $sql = sprintf(“/*%s*/SELECT SLEEP(10) FROM table”, MYSQLND_QC_ENABLE_SWITCH); $start = microtime(true); $res = $mysqli->query($sql); $res = $mysqli->query($sql); $end = microtime(true); echo $end - $start; → 10.142804088593
  • 29. SQL Hints • MYSQLND_QC_ENABLE_SWITCH – qc=on • MYSQLND_QC_DISABLE_SWITCH – qc=off • MYSQLND_QC_TTL_SWITCH – qc_ttl=
  • 30. Storage Handlers ● Storage – Scope: request, process, machine, multi-machine – Location: distance to cache – Replacement strategy – Slam defense strategy ● Decide what to cache – is_select() - detect SQL hints ● Extended statistics – Storage statistics, traces, timings
  • 31. Cache Expiry Client 1 MySQL Client 2...n Cache Hit MySQL Client 1 Client 2...n
  • 32. Slam Defense Client 1 MySQL Client 2...n Expired MySQL Client 1 Client 2...n Cache Hit Refresh
  • 33. Core Statistics • Collected by: mysqlnd_qc core – php.net/manual/en/function.mysqlnd_qc_get_core_stats.php • Scope: process – Process: mysqlnd_qc_get_core_stats() – Aggregated values from all PHP MySQL APIs • Contents: wide range – Cache usage and efficiency – Network related – Timings
  • 34. Query Statistics and Backtraces • Collected by: mysqlnd_qc core – php.net/manual/en/function.mysqlnd_qc_get_query_trace_log .php • Scope: process – mysqlnd_qc_get_query_trace_log() – mysqlnd_qc_get_normalized_query_trace_log() • Contents – Origin - backtrace – Timings
  • 35. Storage Handler Statistics • Collected by: storage handler – php.net/manual/en/function..mysqlnd_qc_get_cache_info.php • Scope: cache entry – Depends on storage handler scope – Aggregated values from all PHP MySQL APIs • Contents: none or assorted – Depends on storage handler support – APC: timings, hit ratio, result set size – Default: APC plus result set meta data
  • 36. User-Defined Storage Handler • Procedural – php.net/manual/en/function.mysqlnd_qc_set_user_handlers.php – Callback functions • Object oriented – slideshare.net/nixnutz/mysqlnd-query-cache-plugin-userdefined- storage-handler – Interface mysqlnd_qc_handler • Extending mysqlnd_qc_handler_default
  • 37. <?php /* auto_prepend_file = /path/to/prepend.php */ class my_qc extends mysqlnd_qc_handler_default { public function is_select($query) { if (preg_match("@from employees where@ism", $query)) { /* cache query for mysqlnd_qc.ttl seconds */ return true; } return parent::is_select($query); } } $qc = new my_qc(); mysqlnd_qc_change_handler($qc); ?>
  • 38. Resources • php.net/mysqlnd_qc – Installation, Examples, Functions • php.net/mysqlnd – Introduction, Changes, C plugin API • slideshare.net/nixnutz/presentations – QC Basics – QC User defined storage handler – QC Statistics – QC Benchmark impressions
  • 40. The preceding is intended to outline our general product direction. It is intended for information purposes only, and may not be incorporated into any contract. It is not a commitment to deliver any material, code, or functionality, and should not be relied upon in making purchasing decisions. The development, release, and timing of any features or functionality described for Oracle’s products remains at the sole discretion of Oracle.