{{announcement.body}}
{{announcement.title}}

Flexible MariaDB Server Query Cache

DZone 's Guide to

Flexible MariaDB Server Query Cache

In this article, explore the MariaDB Server query cache.

· Database Zone ·
Free Resource

The MariaDB Server Query Cache

The Server Query Cache (QC) is a well-known feature of MariaDB Server-it caches SQL statements and the corresponding result sets. If a subsequent query then matches a cached SQL statement, the query can reuse the result set. The Query Cache also knows to invalidate the Query Cache if a table corresponding to a cached query is modified, for example by an UPDATE. For more information, see Query Cache in the MariaDB Knowledge Base.

In previous decades, amounts of RAM were limited, disks were slow, and CPUs had one core and one thread. If you wanted more cores, the cost was restrictive-up to several years' salary for two CPU machines. In those days, the Query Cache was a good idea. The likelihood of data being in limited-size disk caches was small. Getting data from disk was a bad idea as it meant dealing with the slow performance of magnetic media. Today we have faster, solid-state disks and more RAM, so the Query Cache is less important. Reducing reliance on cache alleviates its negative effects, such as mutex blocking.

A mutual exclusion object (mutex) is a programming object that allows multiple program threads to share a resource (such as a folder) but not simultaneously. Mutex is set to unlock when the data is no longer needed or when a routine is finished. Mutex creates a bottleneck effect. The blocking means only one query can look at the Query Cache at a time and other queries must wait. A query that must wait to look in the cache only to find it isn't in the cache will be slowed instead of being accelerated.

You might also be interested in: Improve MariaDB Performance Using Query Profiling

Query Cache Flags

The Query Cache has three modes: ON, OFF, and DEMAND. In OFF mode nothing will be cached. In either ON or DEMAND modes, flags can be used to determine which statements are cached.

In DEMAND mode, only specified statements are cached. To specify that a statement should be cached, the SQL_CACHE flag is set in a SELECT statement:

SQL
 




x


 
1
SELECT SQL_CACHE id, name FROM products;



This SELECT statement caches only the SQL text and corresponding result of set for the specified statements. Three issues emerge with this assumption:

  1. The application needs modification to any applicable SELECT to use this flag.
  2. When the SQL_CACHE is missing in the SELECT statement, it will not be eligible for inclusion in the cache and doesn't check for any previous cached statements; therefore, it will never use the Query Cache.
  3. The DML, such as INSERT, UPDATE, and DELETE statements, need to be inspected for invalidation, which will incur in the blocking effects of the Query Cache mutex.

If the Query Cache is ON, you can avoid a statement from being cached or looked up in the cache, by including the SQL_NO_CACHE flag:

SQL
 




xxxxxxxxxx
1


 
1
SELECT SQL_NO_CACHE order_id, line_id, product, amt FROM order_item;



Query Cache Concerns

Remember, in the previous decades there were only one or two simultaneous threads. When you had a single CPU with a single thread, Query Cache mutex wasn't a big deal because there was little chance another thread would run concurrently. Query Cache mutex wasn't regarded as a bad thing. You just noticed that when Query Cache was switched on, your website was suddenly running ten times faster.

Today if you run modern hardware with 16 threads, even without Query Cache, your website runs hundreds of times faster. If Query Cache were switched on, the mutex slows it down to a rate comparable to previous decades. Ugh.

The MaxScale Query Filter

MariaDB MaxScale database proxy provides another Query Cache as part of the cache filter. See Cache in the MariaDB Knowledge Base. The cache filter overcomes the limitations of the Query Cache inside MariaDB Server, but it adds a few obstacles of its own.

MaxScale cache filter eliminates the mutex issues; and it's more configurable compared to the MariaDB Server Query Cache. You can specify which tables, databases, columns, etc. are affected with a flexible set of rules.

Having the option to specify tables is useful if we don't want all the tables cached, but it makes the cache filter more difficult to configure. With complexity such as this, how does invalidation work in the query filter?

We could check all DML processed by MariaDB MaxScale and then invalidate the relevant tables. Using this approach will not work because any processing inside the MariaDB Server that modifies a table will not be seen by MaxScale, which includes stored procedures, functions, and triggers.

When using the cache filter each statement has time to live (TTL). When the statement times out, the cache needs to be refreshed. The tuning is difficult because we want to cache as long as possible, so we don't have to revisit the server to refresh, but that means the data being returned may be outdated.

The query filter has an advanced runtime configuration to deal with tuning issues. MariaDB MaxScale is useful, if you want to make this effort, but it's more difficult to set up and configure than using Query Cache in MariaDB Server.

Mutex Work Around

Attempts have been made to find a way to work around mutex in the Query Cache. Unfortunately, because mutex is central to internal processing, it's still not solved. What if we could at least specify which tables and SQL statements cached in the MariaDB Server Query Cache? There would still be an issue with cache invalidation statements, but at least the cache focuses on tables where it makes sense to use it, such as tables with mostly static content and where the SELECTS are frequent (for example products on a website).

Selecting from the products table would be speedy because we can cache the result for many queries. We would not see much cache invalidation, as the set of products rarely changes. Can we fix that with what is available right now? Yes, let's have a look.

Fixing the Query Cache

When the Query Cache type is set to DEMAND, SELECT statements will use the Query Cache when explicitly specified by the SQL_CACHE flag. This is done in the MariaDB Server Configuration File, /etc/my.cnf.d/server.cnf in the [mysqld] section, where we add:

SQL
 




xxxxxxxxxx
1


 
1
query_cache_type=DEMAND



Now, we don't want to rewrite all our applications to selectively use the SQL_CACHE flag-we'll use MariaDB MaxScale to do that for us.

The regex filter is used this time, as it's not a query filter. The regex filter is intuitive and allows a search and replace of SQL statements being processed. In this instance, SQL_CACHE is added to the selected statements. The examples below show a simple website table with two tables ( products and customers) that are hit all the time.

SQL
 




xxxxxxxxxx
1
12


 
1
CREATE TABLE `products` (
2
`id` int(11) NOT NULL,
3
`category` int(11) NOT NULL,
4
`name` varchar(255) DEFAULT NULL,
5
PRIMARY KEY (`id`)
6
) ENGINE=InnoDB;
7
 
          
8
CREATE TABLE `customers` (
9
`id` int(11) NOT NULL,
10
`name` varchar(255) DEFAULT NULL,
11
PRIMARY KEY (`id`)
12
) ENGINE=InnoDB;



1. We can configure the MaxScale regex filter to insert SQL_CACHE into any statement, such as:

SQL
 




xxxxxxxxxx
1


 
1
SELECT id, name FROM products WHERE category = 1;



or

SQL
 




xxxxxxxxxx
1


 
1
SELECT name FROM customer WHERE id = 42;



2. This configuration for the regex filter uses the PCRE2 syntax for matching:

SQL
 




xxxxxxxxxx
1


 
1
 [QcOnDemand]
2
type=filter
3
module=regexfilter
4
match=(?i)^([[:space:]]*select)([[:space:]]+.*[[:space:]]+from[[:space:]]+(products|customers)([[:space:]]|$))
5
replace=$1 SQL_CACHE$2



PCRE2 regular expression syntax is intricate, yet powerful. Below is an element by element explanation of the above regular expression:

3. The following configuration settings tell the MariaDB MaxScale router to use the filter created:

Properties files
 




xxxxxxxxxx
1


 
1
 [DefaultService]
2
type=service
3
router=readwritesplit
4
servers=server1
5
filters=QcOnDemand



4. With configuration in place, restart MariaDB Server and MariaDB MaxScale. We're now ready to test.

Testing the Fixed Query Cache

To test the configured Query Cache, connect to MariaDB through the MariaDB MaxScale port of your choice (this example uses port 4004).

1. Connect to the database.

Java
 




xxxxxxxxxx
1
13


 
1
$ mysql -h mydbhost -P 4004 -usomeuser -psomepassword test
2
Reading table information for completion of table and column names
3
You can turn off this feature to get a quicker startup with -A
4
 
5
Welcome to the MariaDB monitor.  Commands end with ; or \g.
6
Your MariaDB connection id is 3
7
Server version: 10.4.6-MariaDB-log MariaDB Server
8
 
9
Copyright (c) 2000, 2018, Oracle, MariaDB Corporation Ab and others.
10
 
11
Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.
12
 
13
MariaDB [test]>



2. Review what is currently in the Query Cache.

Java
 




xxxxxxxxxx
1
13


 
1
MariaDB [test]> show global status like 'qc%';
2
+-------------------------+---------+
3
| Variable_name           | Value   |
4
+-------------------------+---------+
5
| Qcache_free_blocks      | 1       |
6
| Qcache_free_memory      | 1031320 |
7
| Qcache_hits             | 0       |
8
| Qcache_inserts          | 0       |
9
| Qcache_lowmem_prunes    | 0       |
10
| Qcache_not_cached       | 265     |
11
| Qcache_queries_in_cache | 0       |
12
| Qcache_total_blocks     | 1       |
13
+-------------------------+---------+



3. Note the tables order and order_line should not be cached unlike tables products and customers.

Java
 




xxxxxxxxxx
1


 
1
MariaDB [test]> select * from orders;
2
+----------+-------------+
3
| order_id | customer_id |
4
+----------+-------------+
5
|        1 |           1 |
6
|        2 |           7 |
7
|        9 |           2 |
8
+----------+-------------+



Did the tables hit the Query Cache? Review the following and notice nothing was inserted into the Query Cache, and there were no hits.

Java
 




xxxxxxxxxx
1
13


 
1
MariaDB [test]> show global status like 'qc%';
2
+-------------------------+---------+
3
| Variable_name           | Value   |
4
+-------------------------+---------+
5
| Qcache_free_blocks      | 1       |
6
| Qcache_free_memory      | 1031320 |
7
| Qcache_hits             | 0       |
8
| Qcache_inserts          | 0       |
9
| Qcache_lowmem_prunes    | 0       |
10
| Qcache_not_cached       | 485     |
11
| Qcache_queries_in_cache | 0       |
12
| Qcache_total_blocks     | 1       |
13
+-------------------------+---------+



Next, let's check a query on the products table.

Java
 




xxxxxxxxxx
1


 
1
MariaDB [test]> select id, category, name from products where category = 1;
2
+----+----------+-----------------+
3
| id | category | name            |
4
+----+----------+-----------------+
5
|  1 |        1 | Database system |
6
|  2 |        1 | Word processor  |
7
+----+----------+-----------------+



We can see the products within the table. Let's have a look at the status of the Query Cache again.

Java
 




xxxxxxxxxx
1
13


 
1
MariaDB [test]> show global status like 'qc%';
2
+-------------------------+---------+
3
| Variable_name           | Value   |
4
+-------------------------+---------+
5
| Qcache_free_blocks      | 1       |
6
| Qcache_free_memory      | 1029784 |
7
| Qcache_hits             | 0       |
8
| Qcache_inserts          | 1       |
9
| Qcache_lowmem_prunes    | 0       |
10
| Qcache_not_cached       | 737     |
11
| Qcache_queries_in_cache | 1       |
12
| Qcache_total_blocks     | 4       |
13
+-------------------------+---------+



An insert was made into the Query Cache. When we run the same query again will we have the same result?

Java
 




xxxxxxxxxx
1
21


 
1
MariaDB [test]> select id, category, name from products where category = 1;
2
+----+----------+-----------------+
3
| id | category | name            |
4
+----+----------+-----------------+
5
|  1 |        1 | Database system |
6
|  2 |        1 | Word processor  |
7
+----+----------+-----------------+
8
 
9
MariaDB [test]> show global status like 'qc%';
10
+-------------------------+---------+
11
| Variable_name           | Value   |
12
+-------------------------+---------+
13
| Qcache_free_blocks      | 1       |
14
| Qcache_free_memory      | 1029784 |
15
| Qcache_hits             | 1       |
16
| Qcache_inserts          | 1       |
17
| Qcache_lowmem_prunes    | 0       |
18
| Qcache_not_cached       | 899     |
19
| Qcache_queries_in_cache | 1       |
20
| Qcache_total_blocks     | 4       |
21
+-------------------------+---------+



It worked the way it was supposed to. There is one insert into the Query Cache and one hit.
Next, let's try to invalidate the cache.

Java
 




xxxxxxxxxx
1
15


1
MariaDB [test]> insert into products values(5,1,'Spreadsheet');
2
 
3
MariaDB [test]> show global status like 'qc%';
4
+-------------------------+---------+
5
| Variable_name           | Value   |
6
+-------------------------+---------+
7
| Qcache_free_blocks      | 1       |
8
| Qcache_free_memory      | 1031320 |
9
| Qcache_hits             | 1       |
10
| Qcache_inserts          | 1       |
11
| Qcache_lowmem_prunes    | 0       |
12
| Qcache_not_cached       | 1112    |
13
| Qcache_queries_in_cache | 0       |
14
| Qcache_total_blocks     | 1       |
15
+-------------------------+---------+



The number of queries in the cache is 0 because the cache was invalidated. Let's try one more time to invalidate the cache.

Java
 




xxxxxxxxxx
1
23


1
MariaDB [test]> select id, category, name from products where category = 1;
2
+----+----------+-----------------+
3
| id | category | name            |
4
+----+----------+-----------------+
5
|  1 |        1 | Database system |
6
|  2 |        1 | Word processor  |
7
|  5 |        1 | Spreadsheet     |
8
+----+----------+-----------------+
9
3 rows in set (0.001 sec)
10
 
11
MariaDB [test]> show global status like 'qc%';
12
+-------------------------+---------+
13
| Variable_name           | Value   |
14
+-------------------------+---------+
15
| Qcache_free_blocks      | 1       |
16
| Qcache_free_memory      | 1029784 |
17
| Qcache_hits             | 1       |
18
| Qcache_inserts          | 2       |
19
| Qcache_lowmem_prunes    | 0       |
20
| Qcache_not_cached       | 1232    |
21
| Qcache_queries_in_cache | 1       |
22
| Qcache_total_blocks     | 4       |
23
+-------------------------+---------+



The statement was inserted into the cache as expected ( Qcache_inserts is now 2). The same statement was inserted twice, and the result set was invalidated in between the two executions.

Happy SQL'ing

Further Reading

Using MySQL as a Cache Layer for BigQuery

A Look at MariaDB’s Subquery Cache

Topics:
database, mariadb, mariadb server query cache, tutorial

Published at DZone with permission of Anders Karlsson , DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}