Оптимизация настроек Redis
Чтобы получить наилучшую производительность необходима тонкая настройка, которая уменьшит вероятность непредвиденных ошибок, ограничений и пиковых нагрузок. Это касается всех частей системы, железа и базы данных.
С чего начать
Любую оптимизацию необходимо начинать с профилирования и тестирования приложения под высокими нагрузками. Также не забывайте о серверной оптимизации, правильной настройке Nginx и дополнительной оптимизации Ubuntu-сервера. Такой подход сохранит нервы и упростит дальнейшую процедуру тюнинга.
Когда Redis настроена и готова к работе, рекомендуем проверить ее при помощи встроенного теста:
# Выполнит 100 000 запросов от 50 клиентов по 12 команд одновременно
Бэкапы
В Redis реализовано два persistence-режима: RDB и AOF.
При включении RDB система создает компактные снэпшоты данных в заданные интервалы времени. Это хороший подход для восстановления информации в случае сбоя. Бэкапы пишутся в параллельном процессе при помощи команды fork() , который в случае большой БД затратен по ресурсам и времени. Кроме этого, в случае неожиданного выключения сервера, все данные, которые не были записаны или находились в процессе создания резервной копии, будут утеряны.
AOF представляет собой лог операций, которые выполняют клиенты. Метод расшифровывается как Append Only File, то есть все новые данные добавляются к уже имеющимся данным, причем, каждую секунду по умолчания. Так что в случае сбоя потери будут минимальны. Но подход немного медленнее RDB, лог-файл существенно больше, производительность зависит от параметров fsync.
Для настройки Redis нужно отредактировать файл конфигурации /etc/redis/redis.conf :
# По умолчанию включен режим RDB
Хотите максимальной производительности — отключите persistence полностью. Или же настройте частоту создания снэпшотов. По умолчанию установлены параметры:
- Создать копию, если было хотя бы одно изменение в течение 15 минут (900 секунд);
- Создать копию, если в течение 5 минут (300 секунд) было хотя бы 10 изменений;
- Создать копию, если за минуту было 10 000 изменений.
Еще один вариант — используйте репликацию.
Дополнительные параметры
Чтобы избежать узких мест, рекомендуем увеличить количество соединений, которые слушает сокет:
# Значение по умолчанию — 511
Также стоит обратить внимание на разрешенное количество клиентов:
# Если слишком низкое, то появится ошибка ‘max number of clients reached’
Redis работает с ОЗУ, используя весь максимум доступной памяти. Так что есть смысл ограничить разрешенный объем, чтобы другие процессы сервера также могли выполняться:
Поиск проблем при помощи INFO
Просмотр статистики работы Redis поможет найти ошибки и проблемные места. К примеру, можно оценить скорость кэширования:
# Система явно не успевает
Таким способом отслеживайте лимит доступной памяти maxmemory через eviction ключей:
# Система упирается в доступный объем памяти
Также стоит подобрать наилучшую политику отклонения ключей (eviction policy):
# Указывать в файле конфигурации Redis
Доступно 6 параметров:
- noeviction — возвращает ошибку;
- allkeys-lru — отклоняет ключи, убирая наименее используемые ключи (least recently used (LRU);
- volatile-lru — отклоняет ключи, удаляя наименее используемые, если установлен срок истечения;
- allkeys-random — отклоняет ключи в случайном порядке;
- volatile-random — отклоняет ключи в случайном порядке, если установлен срок истечения;
- volatile-ttl — в первую очередь отклоняет ключи c наименьшим сроком истечения.
Самое главное
Для создания отказоустойчивой системы используйте репликацию. Отключение снэпшотов принесет заметный прирост производительности. Также стоит подобрать наилучшую eviction policy для вашего приложения.
Сравнение Vertica и Mysql на практике
Включение и использование логов ошибок, запросов и медленных запросов, бинарного лога для проверки работы MySQL
Check-unused-keys для определения неиспользуемых индексов в базе данных
Повышение скорости работы запросов с MySQL Handlersocket
Ускорение репликации в Mysql 5.6+
Правила выбора типов данных для максимальной производительности в Mysql
Настройки для улучшения производительности Postgres
Быстрая альтернатива Mysqldump для больших таблиц без блокировок и выключений.
Как восстановить данные, если MySQL упал и не поднимается
Что такое индексы в Mysql и как их использовать для оптимизации запросов
Как устроена распределенная база данных на основе blockchain механизма
Правильная настройка Mysql под нагрузки и не только. Обновлено.
Примеры использования колоночной базы данных Vertica
Устройство колоночных баз данных
Простые и быстрые варианты переноса ключей Redis на другой сервер.
Примеры использования Lua в Nginx для решения стандартных задач
Быстрый подсчет уникальных значений за разные периоды времени
Fuzzy search на основе ElasticSearch
Анализ работы СУБД при помощи pgFouine
Сравнение двух движков и когда стоит использовать каждый из них
Анализ медленных запросов с помощью EXPLAIN
Правильный поиск по тексту в Mysql (full-text search)
How to Benchmark the Performance of a Redis Server on Ubuntu 18.04
Posted August 16, 2019
Introduction
Benchmarking is an important practice when it comes to analyzing the overall performance of database servers. It’s helpful for identifying bottlenecks as well as opportunities for improvement within those systems.
Redis is an in-memory data store that can be used as database, cache and message broker. It supports from simple to complex data structures including hashes, strings, sorted sets, bitmaps, geospatial data, among other types. In this guide, we’ll demonstrate how to benchmark the performance of a Redis server running on Ubuntu 18.04, using a few different tools and methods.
Prerequisites
To follow this guide, you’ll need:
- One Ubuntu 18.04 server with a non-root sudo user and a basic firewall configured. To set this up, you can follow our Initial Server Setup Guide for Ubuntu 18.04.
- Redis installed on your server, as explained in our guide on How to Install and Secure Redis on Ubuntu 18.04.
Note: The commands demonstrated in this tutorial were executed on a dedicated Redis server running on a 4GB DigitalOcean Droplet.
Using the Included redis-benchmark Tool
Redis comes with a benchmark tool called redis-benchmark . This program can be used to simulate an arbitrary number of clients connecting at the same time and performing actions on the server, measuring how long it takes for the requests to be completed. The resulting data will give you an idea of the average number of requests that your Redis server is able to handle per second.
The following list details some of the common command options used with redis-benchmark :
- -h : Redis host. Default is 127.0.0.1 .
- -p : Redis port. Default is 6379 .
- -a : If your server requires authentication, you can use this option to provide the password.
- -c : Number of clients (parallel connections) to simulate. Default value is 50.
- -n : How many requests to make. Default is 100000.
- -d : Data size for SET and GET values, measured in bytes. Default is 3.
- -t : Run only a subset of tests. For instance, you can use -t get,set to benchmark the performance of GET and SET commands.
- -P : Use pipelining for performance improvements.
- -q : Quiet mode, shows only the average requests per second information.
For instance, if you want to check the average number of requests per second that your local Redis server can handle, you can use:
You will get output similar to this, but with different numbers:
You can also limit the tests to a subset of commands of your choice using the -t parameter. The following command shows the averages for the GET and SET commands only:
The default options will use 50 parallel connections to create 100000 requests to the Redis server. If you want to increase the number of parallel connections to simulate a peak in usage, you can use the -c option for that:
Because this will use 1000 concurrent connections instead of the default 50, you should expect a decrease in performance:
If you want detailed information in the output, you can remove the -q option. The following command will use 100 parallel connections to run 1000000 SET requests on the server:
You will get output similar to this:
The default settings use 3 bytes for key values. You can change this with the option -d . The following command will benchmark GET and SET commands using 1MB key values:
Because the server is working with a much bigger payload this time, a significant decrease of performance is expected:
It is important to realize that even though these numbers are useful as a quick way to evaluate the performance of a Redis instance, they don’t represent the maximum throughput a Redis instance can sustain. By using pipelining, applications can send multiple commands at once in order to improve the number of requests per second the server can handle. With redis-benchmark , you can use the -P option to simulate real world applications that make use of this Redis feature.
To compare the difference, first run the redis-benchmark command with default values and no pipelining, for the GET and SET tests:
The next command will run the same tests, but will pipeline 8 commands together:
As you can see from the output, there is a substantial performance improvement with the use of pipelining.
Checking Latency with redis-cli
If you’d like a simple measurement of the average time a request takes to receive a response, you can use the Redis client to check for the average server latency. In the context of Redis, latency is a measure of how long does a ping command take to receive a response from the server.
The following command will show real-time latency stats for your Redis server:
You’ll get output similar to this, showing an increasing number of samples and a variable average latency:
This command will keep running indefinitely. You can stop it with a CTRL+C .
To monitor latency over a certain period of time, you can use:
This will track latency averages over time, with a configurable interval that is set to 15 seconds by default. You will get output similar to this:
Because the Redis server on our example is idle, there’s not much variation between latency samples. If you have a peak in usage, however, this should be reflected as an increase in latency within the results.
If you’d like to measure the system latency only, you can use —intrinsic-latency for that. The intrinsic latency is inherent to the environment, depending on factors such as hardware, kernel, server neighbors and other factors that aren’t controlled by Redis.
You can see the intrinsic latency as a baseline for your overall Redis performance. The following command will check for the intrinsic system latency, running a test for 30 seconds:
You should get output similar to this:
Comparing both latency tests can be helpful for identifying hardware or system bottlenecks that could affect the performance of your Redis server. Considering the total latency for a request to our example server has an average of 0.18 microseconds to complete, an intrinsic latency of 0.06 microseconds means that one third of the total request time is spent by the system in processes that aren’t controlled by Redis.
Using the Memtier Benchmark Tool
Memtier is a high-throughput benchmark tool for Redis and Memcached created by Redis Labs. Although very similar to redis-benchmark in various aspects, Memtier has several configuration options that can be tuned to better emulate the kind of load you might expect on your Redis server, in addition to offering cluster support.
To get Memtier installed on your server, you’ll need to compile the software from source. First, install the dependencies necessary to compile the code:
Next, go to your home directory and clone the memtier_benchmark project from its Github repository:
Navigate to the project directory and run the autoreconf command to generate the application configuration scripts:
Run the configure script in order to generate the application artifacts required for compiling:
Now run make to compile the application:
Once the build is finished, you can test the executable with:
This will give you the following output:
The following list contains some of the most common options used with the memtier_benchmark command:
- -s : Server host. Default is localhost.
- -p : Server port. Default is 6379 .
- -a : Authenticate requests using the provided password.
- -n : Number of requests per client (default is 10000).
- -c : Number of clients (default is 50).
- -t : Number of threads (default is 4).
- —pipeline : Enable pipelining.
- —ratio : Ratio between SET and GET commands, default is 1:10.
- —hide-histogram : Hides detailed output information.
Most of these options are very similar to the options present in redis-benchmark , but Memtier tests performance in a different way. To simulate common real-world environments better, the default benchmark performed by memtier_benchmark will test for GET and SET requests only, on a ratio of 1 to 10. With 10 GET operations for each SET operation in the test, this arrangement is more representative of a common web application using Redis as a database or cache. You can adjust the ratio value with the option —ratio .
The following command runs memtier_benchmark with default settings, while providing only high-level output information:
Note: if you have configured your Redis server to require authentication, you should provide the -a option along with your Redis password to the memtier_benchmark command:
You’ll see output similar to this:
According to this run of memtier_benchmark , our Redis server can execute about 90 thousand operations per second in a 1:10 SET / GET ratio.
It’s important to note that each benchmark tool has its own algorithm for performance testing and data presentation. For that reason, it’s normal to have slightly different results on the same server, even when using similar settings.
Conclusion
In this guide, we demonstrated how to perform benchmark tests on a Redis server using two distinct tools: the included redis-benchmark , and the memtier_benchmark tool developed by Redis Labs. We also saw how to check for the server latency using redis-cli . Based on the data obtained from these tests, you’ll have a better understanding of what to expect from your Redis server in terms of performance, and what are the bottlenecks of your current setup.