Fixes #4921 ## Problem With atomic slot migration, an import target that is at `maxmemory` evicts keys of the slots it owns to make room for the imported ones. **Those evictions are never replicated**: 1. Before executing each command of the slot import client, `processCommand()` calls `performEvictions()`. At that point `server.current_client` is already the import client. 2. Each eviction goes through `propagateDeletion()` → `alsoPropagate()`. There, the slot migration guard drops everything propagated while `current_client->slot_migration_job` is set. 3. The guard exists because the import client's stream is proxied to the replicas verbatim. Evictions are a local decision of the target, so they are not part of that stream. 4. Replicas don't evict (`replica-ignore-maxmemory yes`). So they keep every key their primary evicted, and grow by about the imported volume while the primary stays at `maxmemory`. When the importing shards are full, as in a scale-in, replicas can grow well past `maxmemory` within a minute and get OOM-killed. Their resyncs then cause further pressure. A failed import (`Ran out of memory (OOM) during slot import`) leaks the same way: the primary evicted everything it owned before failing, so it ends with no keys while its replicas keep all of them. The bug was introduced with atomic slot migration (#1949) and is present in `unstable` and 9.0. Local reproduction: ASM into a 64 MB `allkeys-lru` primary with one replica, repeated 3 times. | | evictions on target | target keys | replica keys | keys only on replica | |---|---|---|---|---| | ASM | ~35,000 | 47,483 | 82,305 | **34,822**, all in the target's own slots | | legacy `MIGRATE`, same fill | ~34,300 | 48,203 | 48,203 | 0 | | ASM, import fails with OOM | ~48,900 | 0 | 48,937 | **48,937** | ## Fix ### 1. Replicate evictions done while a slot import client is current Only suppress the propagation while a command of an **import** client is executing: ```c if (cc != NULL && cc->slot_migration_job && isImportSlotMigrationJob(cc->slot_migration_job) && server.executing_client != NULL) { ``` `call()` sets `executing_client` for the whole call tree, around its own `alsoPropagate()`, so the guard still covers exactly what the proxied stream contains. Anything propagated while the import client is current but no command is executing, such as `performEvictions()` in `processCommand()`, is now replicated like on any other primary. `_addReplyToBufferOrList()` already uses `executing_client` in the same way to tell evictions apart from command execution. `c->flag.executing_command` can't be used instead, because it is cleared before `call()` propagates the command. Checked: - **No double propagation.** I went through every `propagateDeletion()` caller: - lazy expiry is skipped for import clients; - active expiry, `delKeysInSlot()` and the beforeSleep cleanup all run without a current client. - **SYNCSLOTS ESTABLISH/FINISH** are still suppressed. Their `forceCommandPropagation()` runs inside `call()`. - **Ordering.** Each eviction is flushed as its own execution unit before the command's bytes are proxied. - **The pause assertion in `propagateNow()`** can't be reached, because evictions are paused whenever replica writes are. - **AOF** behaviour is unchanged. ### 2. Keep replicas in the right DB around a proxied slot import stream The target feeds its replicas two streams: the proxied import stream, and its own commands via `replicationFeedReplicas()`. The latter now includes evictions. `replicationFeedReplicas()` tracks the replicas' selected db in `server.replicas_eldb`, but the proxied stream can select a db itself, since the snapshot selects each db that has keys, and nothing accounts for that. With `cluster-databases > 1`, this sends commands to the wrong db on the replicas: - a write or eviction in db 1 is applied to db 2 if the proxied stream last selected db 2; - the next proxied command for db 2 is applied to db 0 if the target last selected db 0 for its own writes. The fix: - track on the import client (`repl_applied_dbid`) the db the import stream is in; - before proxying what the client applied, select that db for the replicas if needed (`replicationFeedStreamFromSlotImport()`); - after proxying, set `replicas_eldb` to the db the stream leaves them in. `replicationFeedStreamFromSlotImport()` asserts that we are a primary: in cluster mode a primary can only be demoted by `clusterSetPrimary()`, which unlinks the import client from its job (`clusterUpdateSlotImportsOnOwnershipChange()`) right after `replicationSetPrimary()`. Without this, the first commit would make multi-db clusters worse: evictions in another db would switch the replicas' db in the middle of an import. It also fixes the existing case of normal client writes to other dbs during an import. ### 3. Replicate evictions done while a slot export client is current The old guard matched any slot migration client, so it also covered the source's export client. While processing its commands (e.g. `SYNCSLOTS ACK`), `processCommand()` can evict, and the guard then dropped `PROPAGATE_REPL`, which `propagateNow()` uses both for `replicationFeedReplicas()` and `clusterFeedSlotExportJobs()`. Those evictions reached neither the source's replicas nor the target, so a key evicted in a migrating slot could survive on the target. The export client no longer matches the guard (commit 1). Its own commands propagate nothing, so nothing else changes for it. ## Compatibility - **With a single db:** at most an extra `SELECT 0` in the replication stream, e.g. after a full sync resets `replicas_eldb`. - No config or protocol change. ## Tests New tests in `tests/unit/cluster/cluster-migrateslots.tcl`. Each checks that the primary and replica have matching `DBSIZE` per db and matching `DEBUG DIGEST` once their offsets meet, and that no resync happened. A primary at maxmemory can evict on any command, including the ones checking it, so the target's own keys have a TTL and are evicted with `volatile-random` (the imported keys are never evicted), and the primary doesn't evict while it is compared with its replica. | test | `unstable` | commit 1 only | this PR | |---|---|---|---| | Evictions on a full import target are replicated | ❌ replica 547 vs primary 285 keys | ✅ | ✅ | | Evictions on an import target that runs out of memory are replicated | ❌ replica 457 vs primary 0 keys | ✅ | ✅ | | Writes in other DBs during a slot import are replicated to the right DB | ❌ db 0: replica 2 vs primary 1 | ❌ db 0: replica 2 vs primary 1 | ✅ | | Evictions in another DB than the imported keys are replicated to the right DB | ❌ db 1: replica 484 vs primary 221 | ❌ db 1: replica 398 vs primary 222 | ✅ | With this PR, the 4 tests also passed 20 times in a row with 4 test clients pinned to 2 CPUs, and 20 times with 8 unpinned test clients. Regression runs, Linux x86_64, `BUILD_TLS=yes`: | suite | result | |---|---| | `unit/cluster/{cluster-migrateslots,multidb,slot-stats,cluster-flush-slot,slot-migration,many-slot-migration}` | 228 ok (includes the 4 new tests) | | `unit/{maxmemory,expire,hashexpire,multi}` | 673 ok | | `integration/{replication,replication-2,replication-3,replication-4,replication-psync,replication-buffer,dual-channel-replication,block-repl}` | 269 ok | | `unit/moduleapi/{propagate,postnotifications,hooks}` | 65 ok | With only the first commit, the full `cluster-migrateslots` suite also passes (117 ok). `clang-format` makes no changes. This should be backported to 9.0, 9.1 and 9.2, which have the same guard. --------- Signed-off-by: Shane Zhang <xzhang14@snapchat.com>
This project was forked from the open source Redis project right before the transition to their new source available licenses.
This README is just a fast quick start document. More details can be found under valkey.io
What is Valkey?
Valkey is a high-performance data structure server that primarily serves key/value workloads. It supports a wide range of native structures and an extensible plugin system for adding new data structures and access patterns.
Building Valkey using Makefile
Valkey can be compiled and used on Linux, macOS, OpenBSD, NetBSD, FreeBSD. We support big endian and little endian architectures, and both 32 bit and 64 bit systems.
It may compile on Solaris derived systems (for instance SmartOS) but our support for this platform is best effort and Valkey is not guaranteed to work as well as in Linux, macOS, and *BSD.
It is as simple as:
% make
To build with TLS support, you'll need OpenSSL development libraries (e.g. libssl-dev on Debian/Ubuntu).
To build TLS support as Valkey built-in:
% make BUILD_TLS=yes
To build TLS as Valkey module:
% make BUILD_TLS=module
Note that sentinel mode does not support TLS module.
To build with experimental RDMA support you'll need RDMA development libraries (e.g. librdmacm-dev and libibverbs-dev on Debian/Ubuntu).
To build RDMA support as Valkey built-in:
% make BUILD_RDMA=yes
To build RDMA as Valkey module:
% make BUILD_RDMA=module
To build with systemd support, you'll need systemd development libraries (such as libsystemd-dev on Debian/Ubuntu or systemd-devel on CentOS) and run:
% make USE_SYSTEMD=yes
To build with enhanced stack traces that include file names and line numbers for all functions (including static functions), use libbacktrace:
% make USE_LIBBACKTRACE=yes
Streaming RDB and replication compression can use Zstandard 1.4.7 or newer.
Its static archive is required because Valkey uses Zstandard's
static-linking-only custom allocator APIs to include codec allocations in
memory accounting. Use make BUILD_ZSTD=yes to enable Zstandard support, and
optionally set ZSTD_PREFIX for a custom installation.
To build Valkey without the Lua engine:
% make BUILD_LUA=no
To append a suffix to Valkey program names, use:
% make PROG_SUFFIX="-alt"
You can build a 32 bit Valkey binary using:
% make 32bit
After building Valkey, it is a good idea to test it using:
% make test
The above runs the main integration tests. Additional tests are started using:
% make test-unit # Unit tests
% make test-modules # Tests of the module API
% make test-sentinel # Valkey Sentinel integration tests
% make test-cluster # Valkey Cluster integration tests
More about running the integration tests can be found in tests/README.md and for unit tests, see src/unit/README.md.
Performance monitoring
Valkey Performance Dashboards provide a consolidated view of throughput trends across versions, helping contributors validate improvements and identify regressions quickly.
- Performance Overview - Compare throughput across Valkey versions
- Unstable Branch Dashboard - Track performance of all commits in the unstable branch
Fixing build problems with dependencies or cached build options
Valkey has some dependencies which are included in the deps directory.
make does not automatically rebuild dependencies even if something in
the source code of dependencies changes.
When you update the source code with git pull or when code inside the
dependencies tree is modified in any other way, make sure to use the following
command in order to really clean everything and rebuild from scratch:
% make distclean
This will clean: jemalloc, lua, libvalkey, linenoise and other dependencies.
Also if you force certain build options like 32bit target, no C compiler
optimizations (for debugging purposes), and other similar build time options,
those options are cached indefinitely until you issue a make distclean
command.
Fixing problems building 32 bit binaries
If after building Valkey with a 32 bit target you need to rebuild it
with a 64 bit target, or the other way around, you need to perform a
make distclean in the root directory of the Valkey distribution.
In case of build errors when trying to build a 32 bit binary of Valkey, try the following steps:
- Install the package libc6-dev-i386 (also try g++-multilib).
- Try using the following command line instead of
make 32bit:make CFLAGS="-m32 -march=native" LDFLAGS="-m32"
Allocator
Selecting a non-default memory allocator when building Valkey is done by setting
the MALLOC environment variable. Valkey is compiled and linked against libc
malloc by default, with the exception of jemalloc being the default on Linux
systems. This default was picked because jemalloc has proven to have fewer
fragmentation problems than libc malloc.
To force compiling against libc malloc, use:
% make MALLOC=libc
To compile against jemalloc on Mac OS X systems, use:
% make MALLOC=jemalloc
Monotonic clock
By default, Valkey uses the processor's internal instruction clock (TSC on x86, CNTVCT on ARM) for monotonic time tracking, which provides approximately 3x faster time access compared to POSIX clock_gettime (~10-30ns vs ~100ns). This is enabled by default on supported architectures (x86_64 Linux and aarch64) and automatically falls back to POSIX clock_gettime on unsupported systems.
For more information about processor clock usage, see: http://oliveryang.net/2015/09/pitfalls-of-TSC-usage/
To disable the processor clock and force POSIX clock_gettime, use:
% make CFLAGS="-DNO_PROCESSOR_CLOCK"
Verbose build
Valkey will build with a user-friendly colorized output by default. If you want to see a more verbose output, use the following:
% make V=1
Running Valkey
To run Valkey with the default configuration, just type:
% cd src
% ./valkey-server
If you want to provide your valkey.conf, you have to run it using an additional parameter (the path of the configuration file):
% cd src
% ./valkey-server /path/to/valkey.conf
It is possible to alter the Valkey configuration by passing parameters directly as options using the command line. Examples:
% ./valkey-server --port 9999 --replicaof 127.0.0.1 6379
% ./valkey-server /etc/valkey/6379.conf --loglevel debug
All the options in valkey.conf are also supported as options using the command line, with exactly the same name.
Running Valkey with TLS:
Running manually
To manually run a Valkey server with TLS mode (assuming ./utils/gen-test-certs.sh
was invoked so sample certificates/keys are available):
-
TLS built-in mode:
./src/valkey-server --tls-port 6379 --port 0 \ --tls-cert-file ./tests/tls/valkey.crt \ --tls-key-file ./tests/tls/valkey.key \ --tls-ca-cert-file ./tests/tls/ca.crt -
TLS module mode:
./src/valkey-server --tls-port 6379 --port 0 \ --tls-cert-file ./tests/tls/valkey.crt \ --tls-key-file ./tests/tls/valkey.key \ --tls-ca-cert-file ./tests/tls/ca.crt \ --loadmodule src/valkey-tls.so
Note that you can disable TCP by specifying --port 0 explicitly.
It's also possible to have both TCP and TLS available at the same time,
but you'll have to assign different ports.
Use valkey-cli to connect to the Valkey server:
./src/valkey-cli --tls \
--cert ./tests/tls/valkey.crt \
--key ./tests/tls/valkey.key \
--cacert ./tests/tls/ca.crt
Specifying --tls-replication yes makes a replica connect to the primary.
Using --tls-cluster yes makes Valkey Cluster use TLS across nodes.
Running Valkey with RDMA:
Note that Valkey Over RDMA is an experimental feature. It may be changed or removed in any minor or major version. Currently, it is only supported on Linux.
-
RDMA built-in mode:
./src/valkey-server --protected-mode no \ --rdma-bind 192.168.122.100 --rdma-port 6379 -
RDMA module mode:
./src/valkey-server --protected-mode no \ --loadmodule src/valkey-rdma.so --rdma-bind 192.168.122.100 --rdma-port 6379
It's possible to change bind address/port of RDMA by runtime command:
192.168.122.100:6379> CONFIG SET rdma-port 6380
It's also possible to have both RDMA and TCP available, and there is no conflict of TCP(6379) and RDMA(6379), Ex:
% ./src/valkey-server --protected-mode no \
--loadmodule src/valkey-rdma.so --rdma-bind 192.168.122.100 --rdma-port 6379 \
--port 6379
Note that the network card (192.168.122.100 of this example) should support RDMA. To test a server supports RDMA or not:
% rdma res show (a new version iproute2 package)
Or:
% ibv_devices
Playing with Valkey
You can use valkey-cli to play with Valkey. Start a valkey-server instance, then in another terminal try the following:
% cd src
% ./valkey-cli
valkey> ping
PONG
valkey> set foo bar
OK
valkey> get foo
"bar"
valkey> incr mycounter
(integer) 1
valkey> incr mycounter
(integer) 2
valkey>
Installing Valkey
In order to install Valkey binaries into /usr/local/bin, just use:
% make install
You can use make PREFIX=/some/other/directory install if you wish to use a
different destination.
Note: For compatibility with Redis, we create symlinks from the Redis names (redis-server, redis-cli, etc.) to the Valkey binaries installed by make install.
The symlinks are created in same directory as the Valkey binaries.
The symlinks are removed when using make uninstall.
The creation of the symlinks can be skipped by setting the makefile variable USE_REDIS_SYMLINKS=no.
make install will just install binaries in your system, but will not configure
init scripts and configuration files in the appropriate place. This is not
needed if you just want to play a bit with Valkey, but if you are installing
it the proper way for a production system, we have a script that does this
for Ubuntu and Debian systems:
% cd utils
% ./install_server.sh
Note: install_server.sh will not work on macOS; it is built for Linux only.
The script will ask you a few questions and will setup everything you need to run Valkey properly as a background daemon that will start again on system reboots.
You'll be able to stop and start Valkey using the script named
/etc/init.d/valkey_<portnumber>, for instance /etc/init.d/valkey_6379.
Building using CMake
In addition to the traditional Makefile build, Valkey supports an alternative, experimental, build system using CMake.
To build and install Valkey, in Release mode (an optimized build), type this into your terminal:
mkdir build-release
cd $_
cmake .. -DCMAKE_BUILD_TYPE=Release -DCMAKE_INSTALL_PREFIX=/opt/valkey
sudo make install
# Valkey is now installed under /opt/valkey
Other options supported by Valkey's CMake build system:
Special build flags
-DBUILD_TLS=<yes|no>enable TLS build for Valkey. Default:no-DBUILD_RDMA=<no|module>enable RDMA module build (only module mode supported). Default:no-DBUILD_ZSTD=<yes|no>configure Zstandard streaming compression support. Default:no-DBUILD_MALLOC=<libc|jemalloc|tcmalloc|tcmalloc_minimal>choose the allocator to use. Default on Linux:jemalloc, for other OS:libc-DBUILD_SANITIZER=<address|thread|undefined>build with address sanitizer enabled. Default: disabled (no sanitizer)-DBUILD_UNIT_GTESTS=[yes|no]when set, the build will produce unit tests executablevalkey-unit-gtests. Default:no-DBUILD_TEST_MODULES=[yes|no]when set, the build will include the modules located under thetests/modulesfolder. Default:no-DBUILD_EXAMPLE_MODULES=[yes|no]when set, the build will include the example modules located under thesrc/modulesfolder. Default:no
Common flags
-DCMAKE_BUILD_TYPE=<Debug|Release...>define the build type, see CMake manual for more details-DCMAKE_INSTALL_PREFIX=/installation/pathoverride this value to define a custom install prefix. Default:/usr/local-G"<Generator Name>"generate build files for "Generator Name". By default, CMake will generateMakefiles.
Verbose build
CMake generates a user-friendly colorized output by default.
If you want to see a more verbose output, use the following:
make VERBOSE=1
Troubleshooting
During the CMake stage, CMake caches variables in a local file named CMakeCache.txt. All variables generated by Valkey
are removed from the cache once consumed (this is done by calling to unset(VAR-NAME CACHE)). However, some variables,
like the compiler path, are kept in cache. To start a fresh build either remove the cache file CMakeCache.txt from the
build folder, or delete the build folder completely.
It is important to re-run CMake when adding new source files.
Integration with IDE
During the CMake stage of the build, CMake generates a JSON file named compile_commands.json and places it under the
build folder. This file is used by many IDEs and text editors for providing code completion (via clangd).
A small caveat is that these tools will look for compile_commands.json under the Valkey's top folder.
A common workaround is to create a symbolic link to it:
cd /path/to/valkey/
# We assume here that your build folder is `build-release`
ln -sf $(pwd)/build-release/compile_commands.json $(pwd)/compile_commands.json
Restart your IDE and voila
Code contributions
Please see the CONTRIBUTING.md. For security bugs and vulnerabilities, please see SECURITY.md.
Valkey is an open community project under LF Projects
Valkey a Series of LF Projects, LLC 2810 N Church St, PMB 57274 Wilmington, Delaware 19802-4447