---
title: How to Deploy Valkey as a Self-Hosted Amazon ElastiCache Alternative
url: https://docs.vultr.com/how-to-deploy-valkey-as-a-self-hosted-amazon-elasticache-alternative
description: Deploy Valkey as a self-hosted Amazon ElastiCache alternative on Vultr with ACLs, TLS, persistence, replication, Sentinel failover, monitoring, and backups.
publish_date: 2026-12-03T19:17:55.398101Z
last_updated: 2026-12-03T20:38:26.154455Z
author: Arjun Malhotra
header_image: https://assets.vultrdevrel.com/docs-main-doc-assets-1/2694/817eff19-2d1e-4f20-b451-81c54f3bdf44.png
---

> Index of every Vultr Docs page in markdown: https://docs.vultr.com/llms.txt

[Amazon ElastiCache](https://aws.amazon.com/elasticache/) is AWS's managed in-memory caching service. It runs your choice of caching engine on a selected node type, and provisions replication groups, automatic failover, and encryption in transit and at rest through the console or API. It removes the need to operate cache servers yourself, but it ties the deployment to AWS infrastructure, AWS's engine release and maintenance schedule, and per-node-hour or per-GB-hour charges that scale with usage rather than a fixed self-hosting cost.

[Valkey](https://valkey.io/) is an open-source, high-performance, in-memory key-value data store for caching, session storage, message brokering, and real-time data processing, and it covers the same ground on infrastructure you control. It originated as a community-driven fork of Redis OSS and retains protocol and command compatibility, along with replication, persistence, access control, and clustering. Because it speaks the same RESP protocol as Redis OSS, standard client libraries integrate with it unchanged.

This article explains how to deploy Valkey as a self-hosted alternative to Amazon ElastiCache on a Linux server. It covers installation, memory and eviction configuration, access control, TLS encryption, data persistence, primary-replica replication, high availability with Valkey Sentinel, monitoring, optional benchmarking, backup and restore, and migration strategies from Amazon ElastiCache.

## Understanding Valkey Architecture

Valkey covers most Amazon ElastiCache components through a self-hosted, Redis-protocol-compatible data store. The following table maps each ElastiCache component to its Valkey counterpart and notes where the equivalence is partial.

| Amazon ElastiCache | Valkey | Description |
|---|---|---|
| ElastiCache Valkey Node | Valkey Server | Runs the in-memory data store that serves reads and writes. |
| ElastiCache Primary Node | Valkey Primary | Accepts writes and replicates changes to attached replicas. |
| ElastiCache Read Replica | Valkey Replica | Maintains a read-only copy of the primary for scaling and redundancy. |
| ElastiCache Replication Group | Valkey Primary-Replica Topology | Groups a primary with one or more replicas under a single logical dataset. |
| ElastiCache Automatic Failover | Valkey Sentinel | Monitors instances and promotes a replica when the primary fails. |
| ElastiCache Cluster Mode | Valkey Cluster | Partitions the keyspace across multiple primaries for horizontal scaling. |
| ElastiCache Parameter Groups | `valkey.conf` | Defines runtime settings such as memory limits, eviction, and persistence. |
| ElastiCache Users and Access Controls | Valkey ACL | Defines users, passwords, and command and key permissions. |
| ElastiCache Encryption in Transit | Valkey TLS | Encrypts client and replication traffic with certificates. |
| ElastiCache Snapshots | Valkey RDB and AOF Persistence | Persists the dataset to disk for recovery and backups. |
| ElastiCache Metrics | Valkey `INFO`, `SLOWLOG`, and Latency Monitoring | Exposes memory, throughput, replication, and latency statistics. |

## Prerequisites

Before you begin:

* Have access to three [Ubuntu 26.04 servers](https://docs.vultr.com/products/compute/instances/cloud-compute/provisioning), each with at least 2 vCPUs and 4 GB of memory, as a [non-root user with sudo privileges](https://docs.vultr.com/how-to-create-a-sudo-user-in-linux). This article uses the following server roles:
    * **Primary:** Runs the Valkey primary and a Sentinel instance.
    * **Replica:** Runs a Valkey replica and a Sentinel instance.
    * **Sentinel node:** Runs only a Sentinel instance, which provides the third vote that a failover needs.
* Connect the three servers to the same [private network](https://docs.vultr.com/products/compute/instances/cloud-compute/networking/vpc). The `PRIMARY_IP`, `REPLICA_IP`, `SELF_IP`, `PEER_IP`, `SENTINEL_IP`, and `SERVER_IP` placeholders in this article refer to private IP addresses.

## Install Valkey

Valkey is distributed as source code, and the Valkey project does not provide an official APT repository. Building the latest stable release from source installs a specific, known Valkey version on any Linux distribution and enables optional features such as TLS at compile time. Running the server under systemd as a dedicated unprivileged user starts Valkey at boot, restarts it after failures, and lets systemd supervise the process.

Run the steps in this section on all three servers, unless a step specifies otherwise. The Sentinel node needs the Valkey binaries, the `valkey` user, and the directories, but it does not run the Valkey server.

1. Allow SSH connections through the firewall.

    ```console
    $ sudo ufw allow OpenSSH
    ```

1. Enable the firewall. Enter `y` if UFW prompts you to confirm.

    ```console
    $ sudo ufw enable
    ```

1. Update the package index.

    ```console
    $ sudo apt update
    ```

1. Install the build dependencies.

    ```console
    $ sudo apt install -y build-essential pkg-config tcl libssl-dev libsystemd-dev wget
    ```

    * `build-essential`, `pkg-config`: Provide the compiler toolchain and build configuration.
    * `tcl`: Runs the Valkey test suite.
    * `libssl-dev`: Enables the TLS build.
    * `libsystemd-dev`: Enables `systemd` service notifications.

1. Switch to the `/usr/local/src` directory.

    ```console
    $ cd /usr/local/src
    ```

1. Download the Valkey source archive.

    ```console
    $ sudo wget https://github.com/valkey-io/valkey/archive/refs/tags/9.1.1.tar.gz -O valkey-9.1.1.tar.gz
    ```

    > [!NOTE]
    > Check the [Valkey releases page](https://github.com/valkey-io/valkey/releases) for the latest stable version.

1. Extract the archive.

    ```console
    $ sudo tar -xzf valkey-9.1.1.tar.gz
    ```

1. Switch to the extracted source directory.

    ```console
    $ cd valkey-9.1.1
    ```

1. Build Valkey with TLS and systemd support.

    ```console
    $ sudo make BUILD_TLS=yes USE_SYSTEMD=yes -j$(nproc)
    ```

    * `BUILD_TLS=yes`: Compiles TLS support for encrypted connections.
    * `USE_SYSTEMD=yes`: Compiles systemd notification support for service supervision.
    * `-j$(nproc)`: Runs the build in parallel across all available CPU cores.

    The build may take a few minutes to complete.

1. Install the compiled binaries to `/usr/local/bin`.

    ```console
    $ sudo make install
    ```

1. Verify the installed version.

    ```console
    $ valkey-server --version
    ```

    The output displays the installed version.

1. Create a dedicated system user and group to run the service.

    ```console
    $ sudo adduser --system --group --no-create-home valkey
    ```

1. Create the configuration, data, and log directories.

    ```console
    $ sudo mkdir -p /etc/valkey /var/lib/valkey /var/log/valkey
    ```

1. Create the Valkey configuration file. Run this step and the remaining steps of this section on the primary and the replica only.

    ```console
    $ sudo nano /etc/valkey/valkey.conf
    ```

1. Add the following minimal configuration to start Valkey as a service.

    ```ini
    dir /var/lib/valkey
    pidfile /run/valkey/valkey.pid
    logfile /var/log/valkey/valkey.log
    supervised systemd
    ```

    Save and close the file.

    * `dir`: Directory where Valkey stores its persistence files.
    * `pidfile`: Path to the process ID file.
    * `logfile`: Path to the server log file.
    * `supervised systemd`: Integrates the server with systemd service supervision.

1. Set the ownership of the Valkey directories and configuration file.

    ```console
    $ sudo chown -R valkey:valkey /etc/valkey /var/lib/valkey /var/log/valkey
    ```

1. Create a systemd service file.

    ```console
    $ sudo nano /etc/systemd/system/valkey.service
    ```

1. Add the following service definition.

    ```ini
    [Unit]
    Description=Valkey in-memory data store
    Documentation=https://valkey.io/topics/
    After=network-online.target
    Wants=network-online.target

    [Service]
    Type=notify
    ExecStart=/usr/local/bin/valkey-server /etc/valkey/valkey.conf
    User=valkey
    Group=valkey
    RuntimeDirectory=valkey
    RuntimeDirectoryMode=0755
    Restart=on-failure

    [Install]
    WantedBy=multi-user.target
    ```

    Save and close the file.

1. Reload the systemd manager configuration.

    ```console
    $ sudo systemctl daemon-reload
    ```

1. Enable and start the Valkey service.

    ```console
    $ sudo systemctl enable --now valkey
    ```

1. Verify that the service is active.

    ```console
    $ systemctl is-active valkey
    ```

    The output confirms that the service runs.

1. Confirm that Valkey responds to commands.

    ```console
    $ valkey-cli ping
    ```

    Valkey replies with `PONG`.

## Configure Valkey

Valkey reads its runtime settings from `valkey.conf`, which takes the place of an ElastiCache parameter group for general server behavior. The default configuration binds Valkey to the loopback interface and enables protected mode, which restricts access to the local host. Connection settings such as `maxclients`, the idle `timeout`, and TCP keepalive determine how many clients the server holds open and how quickly it reclaims connections from clients that disappeared without closing them.

Run the steps in this section on the primary and the replica.

1. Open the Valkey configuration file.

    ```console
    $ sudo nano /etc/valkey/valkey.conf
    ```

1. Add the following network and general settings.

    ```ini
    protected-mode yes
    port 6379
    tcp-backlog 511
    timeout 300
    tcp-keepalive 300
    maxclients 10000
    loglevel notice
    databases 16
    ```

    Save and close the file.

    * `protected-mode`: Rejects external connections when no password and no explicit `bind` address are configured.
    * `port`: TCP port for client connections. The default is `6379`.
    * `tcp-backlog`: Maximum length of the pending connection queue.
    * `timeout`: Seconds of client inactivity before Valkey closes the connection. A value of `0` disables the timeout.
    * `tcp-keepalive`: Interval in seconds for TCP keepalive probes on idle connections.
    * `maxclients`: Maximum number of simultaneous client connections.
    * `loglevel`: Verbosity of the server log. The `notice` level suits production use.
    * `databases`: Number of logical databases available to clients.

    > [!NOTE]
    > To accept connections from other hosts, add the server's routable address to the `bind` directive and require authentication. The Configure Access Control section adds a password, and the Configure Replication section updates the `bind` address for the primary.

1. Restart the Valkey service to apply the changes.

    ```console
    $ sudo systemctl restart valkey
    ```

1. Verify an applied setting.

    ```console
    $ valkey-cli CONFIG GET maxclients
    ```

    The output shows the configured value.

## Configure Memory and Cache Eviction

Valkey keeps its dataset in memory, so a memory limit prevents the server from consuming all available system memory. When the dataset reaches the limit, the eviction policy determines which keys Valkey removes to accept new writes. These settings replace the memory and eviction parameters in an ElastiCache parameter group. Run the steps in this section on the primary and the replica.

> [!NOTE]
> Valkey's official documentation also recommends keeping swap enabled, sized to match the system RAM, as a safety net: without swap, the Linux out-of-memory (OOM) killer can terminate Valkey when the server runs out of memory.

1. Open the Valkey configuration file.

    ```console
    $ sudo nano /etc/valkey/valkey.conf
    ```

1. Add the memory limit and eviction policy.

    ```ini
    maxmemory 512mb
    maxmemory-policy allkeys-lru
    ```

    Save and close the file.

    * `maxmemory`: Maximum memory Valkey uses for the dataset. Set this value below the total system memory to leave room for the operating system and replication buffers.
    * `maxmemory-policy`: Strategy Valkey applies when the dataset reaches `maxmemory`. The `allkeys-lru` policy evicts the least recently used keys and suits general caching.

    > [!NOTE]
    > Valkey's actual memory consumption exceeds the size of the stored data, because of memory fragmentation, client connection buffers, and replication buffers. Do not set `maxmemory` to the literal amount of data you want to cache. Choose a value that leaves headroom for this overhead within the memory available to Valkey.

1. Restart the Valkey service to apply the changes.

    ```console
    $ sudo systemctl restart valkey
    ```

1. Verify the eviction policy.

    ```console
    $ valkey-cli CONFIG GET maxmemory-policy
    ```

    The output shows the configured policy.

1. Set a key with a 100-second expiration to test time-based expiry.

    ```console
    $ valkey-cli SET session:demo "cached-value" EX 100
    ```

1. Confirm the remaining time to live.

    ```console
    $ valkey-cli TTL session:demo
    ```

    The output shows the seconds remaining before Valkey removes the key.

1. Test the eviction policy by lowering the memory limit and loading more data than fits.

    ```console
    $ valkey-cli CONFIG SET maxmemory 20mb
    ```

1. Load 300,000 random keys with `valkey-benchmark`.

    ```console
    $ valkey-benchmark -t set -n 300000 -r 300000 -d 200 -q
    ```

    * `-t set`: Runs the `SET` benchmark.
    * `-n 300000`: Issues 300,000 write requests.
    * `-r 300000`: Uses up to 300,000 distinct random keys.
    * `-d 200`: Sets a 200-byte value size.
    * `-q`: Prints only the summary line.

1. Confirm that Valkey evicted keys to stay within the limit.

    ```console
    $ valkey-cli INFO stats | grep evicted_keys
    ```

    The output shows a non-zero eviction count, which confirms that the policy removed keys to enforce the limit.

1. Restore the production memory limit.

    ```console
    $ valkey-cli CONFIG SET maxmemory 512mb
    ```

1. Clear the test data.

    ```console
    $ valkey-cli FLUSHALL
    ```

## Configure Access Control

Valkey uses Access Control Lists (ACLs) to define users, passwords, and the commands and keys each user can access. This capability replaces ElastiCache users and access controls. By default, Valkey provides a single default user with full access and no password. Run the steps in this section on the primary and the replica.

1. Create an ACL file.

    ```console
    $ sudo nano /etc/valkey/users.acl
    ```

1. Add the following user definitions. Replace `ADMIN_PASSWORD` and `APP_PASSWORD` with strong passwords.

    ```ini
    user default on >ADMIN_PASSWORD ~* &* +@all
    user cacheapp on >APP_PASSWORD ~app:* +@read +@write +@connection -@dangerous
    ```

    Save and close the file.

    * `on`: Enables the user.
    * `>ADMIN_PASSWORD`: Sets the user's password.
    * `~*` and `~app:*`: Define the key patterns the user can access. The `default` user accesses all keys, while `cacheapp` accesses only keys in the `app:` namespace.
    * `&*`: Grants access to all Pub/Sub channels.
    * `+@all`: Grants every command to the `default` administrative user.
    * `+@read +@write +@connection`: Grants the `cacheapp` user the read, write, and connection command categories.
    * `-@dangerous`: Removes administrative and destructive commands, such as `FLUSHALL` and `CONFIG`, from the `cacheapp` user.

1. Set the ownership.

    ```console
    $ sudo chown valkey:valkey /etc/valkey/users.acl
    ```

1. Restrict the file permissions.

    ```console
    $ sudo chmod 640 /etc/valkey/users.acl
    ```

1. Open the main configuration file to reference the ACL file.

    ```console
    $ sudo nano /etc/valkey/valkey.conf
    ```

1. Add the `aclfile` directive.

    ```ini
    aclfile /etc/valkey/users.acl
    ```

    Save and close the file.

1. Restart the Valkey service to apply the changes.

    ```console
    $ sudo systemctl restart valkey
    ```

1. Confirm that Valkey rejects unauthenticated commands.

    ```console
    $ valkey-cli PING
    ```

    The command fails with a `NOAUTH Authentication required` error.

1. Export the administrative password so `valkey-cli` authenticates as the default user for the rest of the shell session. Replace `ADMIN_PASSWORD` with the administrative password.

    ```console
    $ export VALKEYCLI_AUTH='ADMIN_PASSWORD'
    ```

    > [!NOTE]
    > The `VALKEYCLI_AUTH` environment variable applies only to the current shell session and avoids passing the password as a command-line argument. To authenticate a single command instead, run `valkey-cli --user default --pass ADMIN_PASSWORD`.

1. List the configured users.

    ```console
    $ valkey-cli ACL LIST
    ```

    The output shows both users and their permissions.

1. Verify that the application user can write to an allowed key. Replace `APP_PASSWORD` with the application password.

    ```console
    $ valkey-cli --no-auth-warning --user cacheapp --pass APP_PASSWORD SET app:session:1 "value"
    ```

    The output shows `OK`.

1. Confirm that the application user cannot access keys outside its namespace.

    ```console
    $ valkey-cli --no-auth-warning --user cacheapp --pass APP_PASSWORD SET other:key "value"
    ```

    The command fails with a `NOPERM` error, because the key is outside the `app:` namespace.

1. Confirm that the application user cannot run dangerous commands.

    ```console
    $ valkey-cli --no-auth-warning --user cacheapp --pass APP_PASSWORD FLUSHALL
    ```

    The command fails with a `NOPERM` error, because the user has no permission to run `FLUSHALL`.

## Enable TLS

Valkey supports Transport Layer Security (TLS) to encrypt client connections and replication traffic, which replaces ElastiCache encryption in transit. The TLS support compiled into the server can listen on a dedicated `tls-port` alongside the plaintext port, and clients verify the server's identity against a certificate authority (CA). Mutual TLS additionally requires clients to present their own certificates. Running TLS on a separate port keeps the plaintext port available on the loopback interface for local administration.

Run the steps in this section on the primary and the replica, unless a step names one server. The primary creates one CA, and both servers sign their certificates with it, so clients trust the whole deployment with a single `ca.crt` file.

1. Create a directory for the TLS certificates.

    ```console
    $ sudo mkdir -p /etc/valkey/tls
    ```

1. Switch to the TLS directory.

    ```console
    $ cd /etc/valkey/tls
    ```

1. On the primary, generate a private key for the certificate authority.

    ```console
    $ sudo openssl genrsa -out ca.key 4096
    ```

1. On the primary, create a self-signed CA certificate.

    ```console
    $ sudo openssl req -x509 -new -nodes -key ca.key -sha256 -days 3650 -subj "/CN=Valkey CA" -out ca.crt
    ```

1. On the primary, display the CA certificate, and copy the output.

    ```console
    $ sudo cat /etc/valkey/tls/ca.crt
    ```

1. On the replica, create the CA certificate file, paste the copied certificate, then save and close the file.

    ```console
    $ sudo nano /etc/valkey/tls/ca.crt
    ```

1. On the primary, display the CA private key, and copy the output.

    ```console
    $ sudo cat /etc/valkey/tls/ca.key
    ```

1. On the replica, create the CA private key file, paste the copied key, then save and close the file.

    ```console
    $ sudo nano /etc/valkey/tls/ca.key
    ```

1. Generate a private key for the Valkey server.

    ```console
    $ sudo openssl genrsa -out valkey.key 2048
    ```

1. Create a certificate signing request. Add the server's routable address to the subject alternative name (SAN) so remote clients can verify the certificate against the address they actually connect to. Replace `SERVER_IP` with the server's address.

    ```console
    $ sudo openssl req -new -key valkey.key -subj "/CN=valkey" -addext "subjectAltName=DNS:localhost,IP:127.0.0.1,IP:SERVER_IP" -out valkey.csr
    ```

1. Sign the server certificate with the CA.

    ```console
    $ sudo openssl x509 -req -in valkey.csr -CA ca.crt -CAkey ca.key -CAcreateserial -days 365 -sha256 -copy_extensions copyall -out valkey.crt
    ```

1. Set the ownership.

    ```console
    $ sudo chown -R valkey:valkey /etc/valkey/tls
    ```

1. Restrict private key permissions.

    ```console
    $ sudo chmod 640 /etc/valkey/tls/*.key
    ```

1. Open the Valkey configuration file.

    ```console
    $ sudo nano /etc/valkey/valkey.conf
    ```

1. Add the TLS settings.

    ```ini
    tls-port 6380
    tls-cert-file /etc/valkey/tls/valkey.crt
    tls-key-file /etc/valkey/tls/valkey.key
    tls-ca-cert-file /etc/valkey/tls/ca.crt
    tls-auth-clients no
    ```

    Save and close the file.

    * `tls-port`: Port that accepts TLS connections. Running TLS on a separate port keeps the plaintext port available on the loopback interface for local administration.
    * `tls-cert-file` and `tls-key-file`: Server certificate and private key.
    * `tls-ca-cert-file`: CA certificate that clients use to verify the server.
    * `tls-auth-clients`: When set to `no`, clients are not required to present a certificate. Set it to `yes` to require mutual TLS.

1. Restart the Valkey service to apply the changes.

    ```console
    $ sudo systemctl restart valkey
    ```

1. Verify an encrypted connection on the TLS port.

    ```console
    $ valkey-cli --tls -p 6380 --cacert /etc/valkey/tls/ca.crt PING
    ```

    Valkey responds with `PONG`.

    > [!WARNING]
    > Encrypting replication traffic with `tls-replication yes`, or disabling the plaintext port with `port 0`, requires TLS on **every** node, including Sentinel. The later sections monitor the plaintext port `6379`, and Sentinel rewrites the `replicaof` directive on each replica to the address and port it monitors. Applying either option without also configuring TLS for Sentinel breaks replication and failover. To encrypt an entire deployment, configure TLS on the Valkey servers and the Sentinel instances together, as described in the [Valkey TLS documentation](https://valkey.io/topics/encryption/).

## Configure Data Persistence

Valkey provides two persistence mechanisms that write the in-memory dataset to disk, which replaces ElastiCache snapshots. The Valkey Database (RDB) mechanism creates point-in-time snapshots at configured intervals, and the Append-Only File (AOF) logs every write operation for finer-grained durability. Enabling both provides fast restarts from the snapshot and minimal data loss from the log. Run the steps in this section on the primary and the replica.

1. Enable memory overcommit so that background saves do not fail when memory is tight. This setting also applies to the AOF rewrite and to the full synchronization a replica requests from its primary.

    ```console
    $ echo 'vm.overcommit_memory = 1' | sudo tee /etc/sysctl.d/99-valkey.conf
    ```

    > [!NOTE]
    > Without `vm.overcommit_memory = 1`, the kernel can refuse the memory allocation for the background save when the dataset is large relative to the available RAM, which causes `BGSAVE` to fail or the server to run into out-of-memory conditions.

1. Apply the setting.

    ```console
    $ sudo sysctl -p /etc/sysctl.d/99-valkey.conf
    ```

1. Verify the setting.

    ```console
    $ cat /proc/sys/vm/overcommit_memory
    ```

    The output shows `1`.

1. Disable Transparent Huge Pages (THP), which increase latency and memory usage during background saves.

    ```console
    $ echo never | sudo tee /sys/kernel/mm/transparent_hugepage/enabled
    ```

1. Verify the THP setting.

    ```console
    $ cat /sys/kernel/mm/transparent_hugepage/enabled
    ```

    The output shows `never` in brackets.

    > [!NOTE]
    > The `echo` command changes the THP setting only until the next reboot. The following steps create a systemd service that disables THP at every boot.

1. Create a systemd service file to persist the THP setting across reboots.

    ```console
    $ sudo nano /etc/systemd/system/disable-thp.service
    ```

1. Add the following service definition.

    ```ini
    [Unit]
    Description=Disable Transparent Huge Pages
    Before=valkey.service
 
    [Service]
    Type=oneshot
    ExecStart=/bin/sh -c 'echo never > /sys/kernel/mm/transparent_hugepage/enabled'
 
    [Install]
    WantedBy=multi-user.target
    ```

    Save and close the file.

1. Reload the systemd manager configuration.

    ```console
    $ sudo systemctl daemon-reload
    ```

1. Enable and start the service.

    ```console
    $ sudo systemctl enable --now disable-thp
    ```

1. Open the Valkey configuration file.

    ```console
    $ sudo nano /etc/valkey/valkey.conf
    ```

1. Add the persistence settings.

    ```ini
    save 900 1
    save 300 10
    save 60 10000
    dbfilename dump.rdb
    appendonly yes
    appendfsync everysec
    ```

    Save and close the file.

    * `save`: Creates an RDB snapshot when the specified number of keys change within the interval.
    * `dbfilename`: Name of the RDB snapshot file.
    * `appendonly`: Enables the append-only file for operation-level durability.
    * `appendfsync`: Frequency of flushing the AOF to disk. The `everysec` value flushes once per second and balances durability and performance.

    Valkey stores both files in the configured `dir` directory. The AOF uses a multi-part layout inside the `appendonlydir` subdirectory.

1. Restart the Valkey service to apply the changes.

    ```console
    $ sudo systemctl restart valkey
    ```

1. Write a test key.

    ```console
    $ valkey-cli SET persist:test "survives-restart"
    ```

1. Trigger a background snapshot.

    ```console
    $ valkey-cli BGSAVE
    ```

1. Confirm that the persistence files exist.

    ```console
    $ sudo ls /var/lib/valkey/
    ```

    The output lists the RDB file and the AOF directory:

    ```
    appendonlydir  dump.rdb
    ```

1. Restart the Valkey service to apply the changes.

    ```console
    $ sudo systemctl restart valkey
    ```

1. Confirm that the data survives.

    ```console
    $ valkey-cli GET persist:test
    ```

    Valkey returns the value from the persisted data.

## Test Valkey Operations

Valkey stores values as typed data structures, such as strings, hashes, lists, and sets, and each type has dedicated commands that the server executes atomically. Strings with an expiration suit cached values and tokens, atomic counters suit rate limiting and statistics, and hashes suit session and object caching because they let you read or update individual fields without rewriting the whole value. Run the steps in this section on the primary.

1. Store a string value.

    ```console
    $ valkey-cli SET app:greeting "hello valkey"
    ```

1. Retrieve the string value.

    ```console
    $ valkey-cli GET app:greeting
    ```

1. Set a key with a 60-second expiration.

    ```console
    $ valkey-cli SET app:token "abc" EX 60
    ```

1. Check the key's remaining time to live.

    ```console
    $ valkey-cli TTL app:token
    ```

    The output shows the seconds remaining.

1. Increment a counter.

    ```console
    $ valkey-cli INCR app:counter
    ```

1. Increment the counter by a specific amount.

    ```console
    $ valkey-cli INCRBY app:counter 9
    ```

    The output shows the incremented counter value.

1. Store a hash, which suits session and object caching.

    ```console
    $ valkey-cli HSET app:user:1 name "Ada" role "admin"
    ```

1. Retrieve the hash.

    ```console
    $ valkey-cli HGETALL app:user:1
    ```

    The output lists the hash fields and values.

1. Delete a key.

    ```console
    $ valkey-cli DEL app:greeting
    ```

1. Confirm the key's removal.

    ```console
    $ valkey-cli EXISTS app:greeting
    ```

    The output shows `0`, which confirms that the key no longer exists.

1. Inspect the memory that a key uses.

    ```console
    $ valkey-cli MEMORY USAGE app:user:1
    ```

    The output shows the memory in bytes.

## Connect an Application to Valkey

Applications connect to Valkey through a client library that speaks the RESP protocol. Because Valkey uses the same protocol as Redis OSS, existing Redis client libraries work unchanged, and Valkey-specific clients such as `valkey-py` offer the same interface. The cache-aside pattern checks Valkey first, queries the primary data source only on a cache miss, and stores the result in Valkey for later requests. The application owns the caching logic, and the expiration set on each key bounds how stale a cached value can become. Run the steps in this section on the primary.

1. Install the Python virtual environment package.

    ```console
    $ sudo apt install -y python3-venv
    ```

1. Create a virtual environment.

    ```console
    $ python3 -m venv ~/valkey-app
    ```

1. Activate the virtual environment.

    ```console
    $ source ~/valkey-app/bin/activate
    ```

1. Install the Valkey client library.

    ```console
    $ pip install valkey
    ```

1. Create the application file.

    ```console
    $ nano ~/cache_aside.py
    ```

1. Add the following code. Replace `APP_PASSWORD` with the application user's password.

    ```python
    import time
    import valkey

    client = valkey.Valkey(
        host="127.0.0.1",
        port=6379,
        username="cacheapp",
        password="APP_PASSWORD",
        decode_responses=True,
    )

    def get_product(product_id):
        key = f"app:product:{product_id}"
        cached = client.get(key)
        if cached is not None:
            return cached, "hit"
        time.sleep(0.5)  # simulate a slow database query
        value = f"Product {product_id} details"
        client.set(key, value, ex=300)
        return value, "miss"

    for _ in range(2):
        start = time.time()
        value, source = get_product(42)
        elapsed = (time.time() - start) * 1000
        print(f"{source}: {value} ({elapsed:.1f} ms)")
    ```

    * `valkey.Valkey(...)`: Connects to Valkey as the `cacheapp` user.
    * `get_product`: Returns the cached value on a hit, or queries the data source and caches the result on a miss.
    * `client.set(key, value, ex=300)`: Stores the result with a 300-second expiration.

1. Run the application.

    ```console
    $ python ~/cache_aside.py
    ```

    The first call misses the cache and runs the simulated query, while the second call returns the cached value in a fraction of the time.

1. Deactivate the virtual environment.

    ```console
    $ deactivate
    ```

## Configure Replication

Valkey replication copies the primary's dataset to one or more replicas, which replaces an ElastiCache replication group with read replicas. Replicas serve read traffic, provide redundancy, and act as promotion candidates during a failover. Replication is asynchronous, so a replica can briefly lag behind the primary. A replica connects to the primary, performs a full synchronization of the dataset, and then receives the stream of write commands as they happen.

Run the first six steps on the **primary** server, and the remaining steps on the **replica** server.

1. On the primary, open the configuration file.

    ```console
    $ sudo nano /etc/valkey/valkey.conf
    ```

1. Add the bind directive. Replace `PRIMARY_IP` with the primary server's IP address.

    ```ini
    bind 127.0.0.1 -::1 PRIMARY_IP
    ```

    Save and close the file.

1. Open the ACL file.

    ```console
    $ sudo nano /etc/valkey/users.acl
    ```

1. Add a dedicated replication user. Replace `REPLICATION_PASSWORD` with a strong password.

    ```ini
    user replicator on >REPLICATION_PASSWORD +psync +replconf +ping
    ```

    Save and close the file.

1. Allow the replica to reach the Valkey port through the firewall. Replace `REPLICA_IP` with the replica server's IP address.

    ```console
    $ sudo ufw allow from REPLICA_IP to any port 6379 proto tcp
    ```

1. Restart the Valkey service to apply the changes.

    ```console
    $ sudo systemctl restart valkey
    ```

    > [!NOTE]
    > Valkey replication fails with a `Timeout connecting to the PRIMARY` error in the replica log when the firewall blocks port `6379`. Restrict the rule to the replica's address instead of opening the port to all sources.

1. On the replica, open the configuration file.

    ```console
    $ sudo nano /etc/valkey/valkey.conf
    ```

1. Add the replication settings. Replace `PRIMARY_IP` with the primary server's IP address, `REPLICATION_PASSWORD` with the replication user's password, and `REPLICA_IP` with the replica server's address.

    ```ini
    replicaof PRIMARY_IP 6379
    masteruser replicator
    masterauth REPLICATION_PASSWORD
    replica-read-only yes
    bind 127.0.0.1 -::1 REPLICA_IP
    ```

    Save and close the file.

    * `replicaof`: Address and port of the primary server.
    * `masteruser` and `masterauth`: Credentials the replica uses to authenticate to the primary.
    * `replica-read-only`: Rejects writes sent directly to the replica, which prevents divergence from the primary.

    > [!NOTE]
    > Add the same `replicator` line to the `/etc/valkey/users.acl` file on the replica. The replica applies it when Sentinel promotes the replica to primary.

1. Allow the primary to reach the replica through the firewall. Replace `PRIMARY_IP` with the primary server's IP address.

    ```console
    $ sudo ufw allow from PRIMARY_IP to any port 6379 proto tcp
    ```

1. Restart the Valkey service on the replica.

    ```console
    $ sudo systemctl restart valkey
    ```

1. Verify the replication status on the replica.

    ```console
    $ valkey-cli INFO replication
    ```

    The output confirms the replica role and an active link to the primary:

    ```
    role:slave
    master_host:PRIMARY_IP
    master_link_status:up
    master_last_io_seconds_ago:1
    slave_read_only:1
    ```

    * `master_link_status:up`: Confirms that the replica connected to the primary. A value of `down` indicates a network, authentication, or firewall problem.

1. On the primary, confirm that the replica is attached.

    ```console
    $ valkey-cli INFO replication
    ```

    The output lists the connected replica and its offset.

1. Write a key on the primary to test replication.

    ```console
    $ valkey-cli SET repl:test "replicated-value"
    ```

1. On the replica, confirm that the key arrived.

    ```console
    $ valkey-cli GET repl:test
    ```

    The replica returns the value written on the primary:

    ```
    "replicated-value"
    ```

1. Confirm that the replica rejects direct writes.

    ```console
    $ valkey-cli SET replica:write "should-fail"
    ```

    The command fails with a `READONLY` error, which confirms read-only enforcement.

## Configure High Availability with Valkey Sentinel

Valkey Sentinel monitors the primary and its replicas, detects failures, promotes a replica to primary, and reconfigures the remaining nodes, which replaces ElastiCache automatic failover. Sentinel requires an odd number of instances, and at least three, because a failover needs agreement from a majority of the Sentinel instances. Two Sentinel instances cannot complete a failover when the primary server fails, because the single surviving instance never reaches a majority.

Run all the steps in this section on all three servers, unless a step specifies a particular server.

1. Open the ACL file on the primary and replica servers.

    ```console
    $ sudo nano /etc/valkey/users.acl
    ```

1. On both servers, add a Sentinel user to the ACL file. Replace `SENTINEL_PASSWORD` with a strong password.

    ```ini
    user sentineluser on >SENTINEL_PASSWORD allchannels +multi +slaveof +replicaof +ping +exec +subscribe +config|rewrite +role +publish +info +client|setname +client|kill +script|kill
    ```

    Save and close the file.

    Sentinel needs these commands to query server state, publish and subscribe to its coordination channel, and promote a replica during a failover.

1. Open the configuration file on the primary server.

    ```console
    $ sudo nano /etc/valkey/valkey.conf
    ```

1. Add the replication credentials so the node can synchronize after a failover demotes it to a replica. Replace `REPLICATION_PASSWORD` with the replication user's password.

    ```ini
    masteruser replicator
    masterauth REPLICATION_PASSWORD
    ```

    Save and close the file.

    > [!WARNING]
    > Configure `masteruser` and `masterauth` on **every** node, including the current primary. Sentinel demotes a recovered primary to a replica, and without these credentials the node fails to resynchronize and logs `Unexpected reply to PSYNC from primary: -NOAUTH Authentication required`.

1. Restart Valkey on the primary and the replica to apply the ACL and configuration changes.

    ```console
    $ sudo systemctl restart valkey
    ```

1. Create the Sentinel configuration file on each of the three servers.

    ```console
    $ sudo nano /etc/valkey/sentinel.conf
    ```

1. Add the following configuration. Replace `SELF_IP` with the address of the server you are configuring, `PRIMARY_IP` with the primary server's address, and `SENTINEL_PASSWORD` with the Sentinel user's password.

    ```ini
    port 26379
    bind 127.0.0.1 SELF_IP
    dir /var/lib/valkey-sentinel
    logfile /var/log/valkey/sentinel.log
    supervised systemd
    sentinel announce-ip SELF_IP
    sentinel monitor valkey-primary PRIMARY_IP 6379 2
    sentinel auth-user valkey-primary sentineluser
    sentinel auth-pass valkey-primary SENTINEL_PASSWORD
    sentinel down-after-milliseconds valkey-primary 5000
    sentinel failover-timeout valkey-primary 10000
    sentinel parallel-syncs valkey-primary 1
    ```

    Save and close the file.

    * `sentinel announce-ip`: Address this Sentinel advertises to its peers.
    * `sentinel monitor`: Names the monitored group, sets the primary's address, and sets the quorum. The quorum of `2` is the number of Sentinels that must agree the primary is unreachable.
    * `sentinel auth-user` and `sentinel auth-pass`: Credentials Sentinel uses to query the monitored servers.
    * `sentinel down-after-milliseconds`: Time without a valid reply before Sentinel marks the primary as down.
    * `sentinel failover-timeout`: Maximum time allowed for a failover attempt.
    * `sentinel parallel-syncs`: Number of replicas that resynchronize with the new primary at the same time.

    > [!NOTE]
    > Sentinel rewrites this file at runtime to record the current topology, so the file and its directory must be writable by the `valkey` user.

1. Create the Sentinel data directory.

    ```console
    $ sudo mkdir -p /var/lib/valkey-sentinel
    ```

1. Set the directory ownership.

    ```console
    $ sudo chown valkey:valkey /var/lib/valkey-sentinel /etc/valkey/sentinel.conf /var/log/valkey
    ```

1. Create a systemd service file for Sentinel.

    ```console
    $ sudo nano /etc/systemd/system/valkey-sentinel.service
    ```

1. Add the following configuration.

    ```ini
    [Unit]
    Description=Valkey Sentinel
    Documentation=https://valkey.io/topics/sentinel/
    After=network-online.target
    Wants=network-online.target

    [Service]
    Type=notify
    ExecStart=/usr/local/bin/valkey-sentinel /etc/valkey/sentinel.conf
    User=valkey
    Group=valkey
    RuntimeDirectory=valkey-sentinel
    RuntimeDirectoryMode=0755
    Restart=on-failure

    [Install]
    WantedBy=multi-user.target
    ```

    Save and close the file.

1. Allow the Sentinel port between all three servers. Run this command on each server for the other two addresses. Replace `PEER_IP` with the other server's address.

    ```console
    $ sudo ufw allow from PEER_IP to any port 26379 proto tcp
    ```

1. Allow the Valkey port on the primary and the replica for every other server that runs Sentinel. Replace `SENTINEL_IP` with the address of the Sentinel server.

    ```console
    $ sudo ufw allow from SENTINEL_IP to any port 6379 proto tcp
    ```

1. Reload the systemd manager configuration.

    ```console
    $ sudo systemctl daemon-reload
    ```

1. Enable and start Sentinel.

    ```console
    $ sudo systemctl enable --now valkey-sentinel
    ```

1. Confirm that Sentinel discovered the primary, the replica, and the other Sentinel instances.

    ```console
    $ valkey-cli -p 26379 SENTINEL master valkey-primary | paste - - | grep -E "^name|^ip|^port|^flags|^num-slaves|^num-other-sentinels|^quorum"
    ```

    The `SENTINEL master` command returns a long list of alternating field names and values. The `paste` and `grep` commands pair each field with its value and select the fields that confirm the topology.

    > [!NOTE]
    > Sentinel does not use the Valkey ACL users, so it requires no password on port `26379`. When `VALKEYCLI_AUTH` is exported in the current shell, `valkey-cli` still sends the password and prints `AUTH failed: ERR AUTH <password> called without any password configured for the default user` before the result. The command still succeeds. To suppress the message, prefix Sentinel commands with `env -u VALKEYCLI_AUTH`.

    The output reports the monitored primary, one replica, and two peer Sentinels:

    ```
    name                 valkey-primary
    ip                   PRIMARY_IP
    port                 6379
    flags                master
    num-slaves           1
    num-other-sentinels  2
    quorum               2
    ```

    * `flags master`: Sentinel considers the primary reachable. A value of `s_down` or `o_down` indicates a failure.
    * `num-slaves 1`: Sentinel discovered the replica.
    * `num-other-sentinels 2`: Sentinel discovered the two peer instances.

    > [!NOTE]
    > Sentinel accepts commands on port `26379` without a password, and the UFW rules limit that port to the three servers. To require a password, set `requirepass` in `sentinel.conf` and `sentinel sentinel-pass` to the same value on every Sentinel instance. For more information, see the [Valkey Sentinel documentation](https://valkey.io/topics/sentinel/).

1. Verify that the deployment can authorize a failover.

    ```console
    $ valkey-cli -p 26379 SENTINEL ckquorum valkey-primary
    ```

    The output confirms that enough Sentinels are available:

    ```
    OK 3 usable Sentinels. Quorum and failover authorization can be reached
    ```

1. Write a key on the primary to confirm the data present before the failover.

    ```console
    $ valkey-cli SET failover:marker "written-before-failover"
    ```

1. Stop Valkey on the primary to simulate a failure.

    ```console
    $ sudo systemctl stop valkey
    ```

1. On the Sentinel node, query Sentinel for the current primary address. Wait a few seconds for Sentinel to detect the failure and complete the promotion.

    ```console
    $ valkey-cli -p 26379 SENTINEL get-master-addr-by-name valkey-primary
    ```

    Sentinel reports the replica's address, which confirms the promotion.

1. On the promoted server, confirm the new role.

    ```console
    $ valkey-cli INFO replication
    ```

    The promoted server now accepts writes as the primary.

1. On the promoted server, check if the data survived.

    ```console
    $ valkey-cli GET failover:marker
    ```

    The promoted server retains the replicated data.

1. Start Valkey on the failed server to restore it.

    ```console
    $ sudo systemctl start valkey
    ```

1. Confirm that Sentinel reconfigured the recovered server as a replica of the new primary.

    ```console
    $ valkey-cli INFO replication
    ```

    The recovered server rejoins as a replica and synchronizes from the new primary.

    > [!NOTE]
    > Applications that must follow failovers automatically should connect through a Sentinel-aware client. Such a client queries Sentinel for the current primary address instead of connecting to a fixed address.

## Monitor Valkey

The health of a cache comes down to a few signals: memory use against `maxmemory`, the cache hit ratio, the eviction rate, replication status, and command latency. Valkey exposes these through the `INFO` command, records slow commands in the slow log, and tracks latency spikes through the latency monitor. These built-in tools replace the Amazon CloudWatch metrics that ElastiCache publishes.

1. Display the server section to confirm the version and uptime.

    ```console
    $ valkey-cli INFO server
    ```

    The output includes the version, port, and uptime:

    ```
    valkey_version:9.1.1
    tcp_port:6379
    uptime_in_seconds:217
    ```

1. Inspect memory usage.

    ```console
    $ valkey-cli INFO memory
    ```

    The output reports current usage, peak usage, the configured limit, and fragmentation:

    ```
    used_memory_human:997.77K
    used_memory_peak_human:997.77K
    maxmemory_human:512.00M
    mem_fragmentation_ratio:15.12
    ```

    * `used_memory_human`: Memory the dataset currently uses.
    * `used_memory_peak_human`: Highest memory usage since the server started.
    * `maxmemory_human`: Configured memory limit.
    * `mem_fragmentation_ratio`: Ratio of memory the operating system allocated to memory Valkey requested. Values far above `1` on a busy server indicate fragmentation.

1. Review throughput and cache effectiveness.

    ```console
    $ valkey-cli INFO stats
    ```

    The output reports connection counts, command throughput, and cache hit statistics:

    ```
    total_connections_received:5
    total_commands_processed:11
    instantaneous_ops_per_sec:0
    expired_keys:0
    evicted_keys:0
    keyspace_hits:0
    keyspace_misses:0
    ```

    * `keyspace_hits` and `keyspace_misses`: Calculate the cache hit ratio as `hits / (hits + misses)`.
    * `evicted_keys`: Number of keys removed because of the memory limit. A steadily rising value indicates that the dataset exceeds `maxmemory`.
    * `expired_keys`: Number of keys removed because their time to live elapsed.

1. Check connected clients.

    ```console
    $ valkey-cli INFO clients
    ```

    The output shows the current client count:

    ```
    connected_clients:1
    blocked_clients:0
    ```

1. Display the number of keys per database.

    ```console
    $ valkey-cli INFO keyspace
    ```

    The output lists the key count and expiration statistics:

    ```
    # Keyspace
    db0:keys=1,expires=0,avg_ttl=0,keys_with_volatile_items=0
    ```

1. Set the slow log threshold to capture commands slower than 10 milliseconds.

    ```console
    $ valkey-cli CONFIG SET slowlog-log-slower-than 10000
    ```

    The threshold uses microseconds, so `10000` equals 10 milliseconds.

1. Display the number of recorded slow commands.

    ```console
    $ valkey-cli SLOWLOG LEN
    ```

1. Review the most recent slow command entries.

    ```console
    $ valkey-cli SLOWLOG GET 1
    ```

    Each entry lists the entry ID, timestamp, execution time in microseconds, the command, and the client address:

    ```
    1) 1) (integer) 3
       2) (integer) 1786660254
       3) (integer) 4
       4) 1) "AUTH"
          2) "(redacted)"
       5) "127.0.0.1:46292"
    ```

1. Enable the latency monitor for events slower than 100 milliseconds.

    ```console
    $ valkey-cli CONFIG SET latency-monitor-threshold 100
    ```

1. Display recorded latency events.

    ```console
    $ valkey-cli LATENCY HISTORY command
    ```

    An empty result confirms that no command exceeded the threshold. When events occur, the output pairs each timestamp with the recorded latency in milliseconds.

    > [!NOTE]
    > Add `slowlog-log-slower-than 10000` and `latency-monitor-threshold 100` to `valkey.conf` to keep these settings after a restart.

??? note "Benchmark Valkey (Optional)"

    Valkey includes the `valkey-benchmark` tool, which measures throughput and latency by issuing large numbers of commands. Benchmarks establish a performance baseline for the deployment and provide a comparison against the ElastiCache node it replaces.

    > [!NOTE]
    > If you completed the failover test in the `Configure High Availability with Valkey Sentinel` section, the original replica is now the primary and the original primary is now a replica. Run the following benchmark commands on the current primary.

    1. Run a combined `SET` and `GET` benchmark. Replace `ADMIN_PASSWORD` with the administrative password.

        ```console
        $ valkey-benchmark -h 127.0.0.1 -p 6379 -a ADMIN_PASSWORD -t set,get -n 100000 -c 50 -d 100 -q
        ```

        * `-h` and `-p`: Target host and port.
        * `-a`: Authenticates with the specified password.
        * `-t set,get`: Runs only the `SET` and `GET` tests.
        * `-n 100000`: Issues 100,000 requests per test.
        * `-c 50`: Uses 50 parallel client connections.
        * `-d 100`: Sets a 100-byte value size.
        * `-q`: Prints only the summary line for each test.

        The output reports throughput and median latency for each command. The `-a` option exposes the password in the shell history and the process list, so run benchmarks on a test deployment or clear the history afterward.

    1. Measure throughput with pipelining, which batches commands into fewer network round trips.

        ```console
        $ valkey-benchmark -h 127.0.0.1 -p 6379 -a ADMIN_PASSWORD -t get -n 100000 -c 50 -P 16 -q
        ```

        Pipelining increases throughput substantially because it reduces per-command network overhead.

        > [!NOTE]
        > Benchmark results depend on CPU, memory, network, and value size. Run benchmarks from a separate client machine to include realistic network latency, and compare results against the ElastiCache node type the deployment replaces.

## Back Up and Restore Valkey

Valkey backups copy the RDB snapshot file to a separate location, which replaces managed ElastiCache snapshots. Restoring loads the snapshot into a Valkey instance. When AOF persistence is enabled, Valkey loads the AOF instead of the RDB at startup, so the restore procedure disables AOF while the snapshot loads and re-enables it afterward. Sentinel fails over to the replica when the primary stops, so the restore stops Sentinel first. Run the steps on the current primary, unless a step says otherwise.

1. Create a backup directory.

    ```console
    $ sudo mkdir -p /var/backups/valkey
    ```

1. Write a test key to include in the backup.

    ```console
    $ valkey-cli SET backup:key1 "backup-value"
    ```

1. Trigger a snapshot of the current dataset.

    ```console
    $ valkey-cli BGSAVE
    ```

    Valkey writes the snapshot in the background.

    > [!NOTE]
    > `BGSAVE` forks a child process, so it depends on the `vm.overcommit_memory` setting described in the **Configure Data Persistence** section. Apply that setting on every server that creates snapshots.

1. Confirm that the snapshot finished.

    ```console
    $ valkey-cli INFO persistence | grep rdb_bgsave_in_progress
    ```

    A value of `0` confirms that no snapshot is in progress.

1. Copy the snapshot to the backup directory with a dated filename.

    ```console
    $ sudo cp /var/lib/valkey/dump.rdb /var/backups/valkey/dump-$(date +%Y%m%d).rdb
    ```

    > [!NOTE]
    > Schedule this copy with a `cron` job and transfer the file to remote storage. A backup stored only on the Valkey server does not protect against server loss.

1. On all three servers, stop Sentinel so that it does not fail over while the primary is down.

    ```console
    $ sudo systemctl stop valkey-sentinel
    ```

1. Stop the Valkey service before restoring.

    ```console
    $ sudo systemctl stop valkey
    ```

1. Open the configuration file to disable AOF for the restore.

    ```console
    $ sudo nano /etc/valkey/valkey.conf
    ```

1. Change the `appendonly` directive to `no`.

    ```ini
    appendonly no
    ```

    Save and close the file.

    > [!WARNING]
    > Valkey loads the AOF instead of the RDB snapshot when `appendonly` is set to `yes`. Restoring a snapshot without disabling AOF first starts the server with an empty dataset.

1. Remove the existing AOF directory.

    ```console
    $ sudo rm -rf /var/lib/valkey/appendonlydir
    ```

1. Copy the backup into the data directory. Replace `BACKUP_FILE` with the name of the dated backup file, such as `dump-20261204.rdb`.

    ```console
    $ sudo cp /var/backups/valkey/BACKUP_FILE /var/lib/valkey/dump.rdb
    ```

1. Set the ownership of the restored snapshot.

    ```console
    $ sudo chown valkey:valkey /var/lib/valkey/dump.rdb
    ```

1. Start the Valkey service to load the snapshot.

    ```console
    $ sudo systemctl start valkey
    ```

1. Verify that the restored keys are present.

    ```console
    $ valkey-cli DBSIZE
    ```

1. Retrieve a specific restored key.

    ```console
    $ valkey-cli GET backup:key1
    ```

    The output shows `"backup-value"`, which confirms that Valkey loaded the snapshot.

1. Re-enable AOF at runtime, which rebuilds the append-only file from the restored dataset.

    ```console
    $ valkey-cli CONFIG SET appendonly yes
    ```

1. Open the configuration file.

    ```console
    $ sudo nano /etc/valkey/valkey.conf
    ```

1. Set `appendonly` back to `yes` so the setting survives a restart.

    ```ini
    appendonly yes
    ```

    Save and close the file.

1. Confirm that AOF is active again.

    ```console
    $ valkey-cli INFO persistence | grep aof_enabled
    ```

    The output confirms that AOF persistence is enabled.

1. On all three servers, start Sentinel again.

    ```console
    $ sudo systemctl start valkey-sentinel
    ```

1. On the replica, confirm that it resynchronized the restored data.

    ```console
    $ valkey-cli GET backup:key1
    ```

    The output shows `"backup-value"`.

## Verify the Deployment

The features configured in this article depend on each other. Replication and Sentinel rely on ACL users and firewall rules, while persistence and eviction depend on the memory and kernel settings. A layer can fail without affecting the others, such as a replica whose link to the primary is down while the primary keeps serving clients. Checking each capability end to end confirms that the layers work together. Run these checks on the current primary unless a step specifies otherwise.

> [!NOTE]
> If you completed the failover test in the `Configure High Availability with Valkey Sentinel` section, the original replica is now the primary and the original primary is now a replica. Run the following checks on the current primary.

1. Confirm that both services run.

    ```console
    $ systemctl is-active valkey valkey-sentinel
    ```

    Both services report `active`.

1. Confirm that Valkey rejects unauthenticated access. Open a new shell without `VALKEYCLI_AUTH` exported, then run the following command.

    ```console
    $ valkey-cli PING
    ```

    The command fails with a `NOAUTH Authentication required` error.

1. Confirm that the application user can write within its namespace. Replace `APP_PASSWORD` with the application password.

    ```console
    $ valkey-cli --no-auth-warning --user cacheapp --pass APP_PASSWORD SET app:verify "value"
    ```

    The output shows `OK`.

1. Confirm that the application user is denied write access outside its namespace. Replace `APP_PASSWORD` with the application password.

    ```console
    $ valkey-cli --no-auth-warning --user cacheapp --pass APP_PASSWORD SET forbidden:key "value"
    ```

    The command fails with a `NOPERM` error.

1. Confirm that the TLS port serves encrypted connections.

    ```console
    $ valkey-cli --tls -p 6380 --cacert /etc/valkey/tls/ca.crt PING
    ```

    Valkey responds with `PONG`.

1. Set a key with an expiration to confirm key expiration works.

    ```console
    $ valkey-cli SET verify:ttl "x" EX 30
    ```

1. Check the remaining time to live.

    ```console
    $ valkey-cli TTL verify:ttl
    ```

    The output shows a positive number of seconds, up to `30`.

1. Confirm the memory limit and eviction policy.

    ```console
    $ valkey-cli CONFIG GET maxmemory-policy
    ```

    ```
    1) "maxmemory-policy"
    2) "allkeys-lru"
    ```

1. Confirm that persistence is active.

    ```console
    $ valkey-cli INFO persistence | grep -E "aof_enabled|rdb_last_bgsave_status"
    ```

    The output confirms that AOF is enabled and the last snapshot succeeded.

1. Confirm the replication topology.

    ```console
    $ valkey-cli INFO replication
    ```

    ```
    role:master
    connected_slaves:1
    ```

1. Write a key on the primary, then read it on the replica to confirm that replication delivers data.

    ```console
    $ valkey-cli SET verify:repl "replicated"
    ```

    On the replica, run the following command.

    ```console
    $ valkey-cli GET verify:repl
    ```

    ```
    "replicated"
    ```

1. Confirm that Sentinel can authorize a failover.

    ```console
    $ valkey-cli -p 26379 SENTINEL ckquorum valkey-primary
    ```

    ```
    OK 3 usable Sentinels. Quorum and failover authorization can be reached
    ```

1. Confirm that monitoring statistics report activity.

    ```console
    $ valkey-cli INFO stats | grep -E "keyspace_hits|keyspace_misses"
    ```

    The output reports the cache hit and miss counters used to calculate the hit ratio.

## Migrate from Amazon ElastiCache to Valkey

Migrating from Amazon ElastiCache to Valkey replaces a managed cache with a self-hosted deployment that you configure and operate. The sections below outline how to review the existing deployment, prepare Valkey, move the data, update applications, and validate the result.

### Review the Existing ElastiCache Configuration

Document the current ElastiCache deployment so the Valkey configuration reproduces its behavior.

* **Engine and version:** Identify the cache engine and version to select a compatible Valkey release.
* **Node topology:** Record the node type, node count, and primary-replica layout.
* **Cluster mode:** Determine whether cluster mode is enabled, because it changes the keyspace and client configuration.
* **Parameter groups:** Export the parameter values that control memory limits, eviction, and persistence.
* **Access and security:** Note the users, access rules, and whether encryption in transit is enabled.
* **Endpoints:** List the primary, reader, and configuration endpoints that applications use.

### Prepare the Valkey Deployment

Map each ElastiCache setting to the equivalent Valkey configuration on the target servers.

* **Memory and eviction:** Set `maxmemory` and `maxmemory-policy` to match the node memory and the parameter group's eviction policy.
* **Access control:** Recreate ElastiCache users and rules as Valkey ACL users.
* **Encryption:** Configure Valkey TLS to match the ElastiCache in-transit encryption setting.
* **Persistence:** Enable RDB, AOF, or both to match the snapshot and durability requirements.
* **Replication and high availability:** Configure primary-replica replication and Valkey Sentinel to replace ElastiCache replication groups and automatic failover.

### Migrate Cache Data

The migration method depends on whether the workload treats the cache as disposable or as a source of record.

* **Disposable cache:** For cache-aside workloads, deploy Valkey empty and let the application repopulate it from the primary data source as cache misses occur.
* **Persistent data:** For datasets that must be preserved, export an RDB snapshot from the source and load it on the Valkey server, or use a replication-based tool that streams keys to the new instance.
* **Validation:** Compare key counts and sample values after loading to confirm the dataset transferred correctly.

### Update Application Connections

Point applications at the Valkey endpoint and align their client settings with the new deployment.

* **Endpoint:** Replace the ElastiCache endpoint with the Valkey primary address, or the Sentinel addresses for automatic failover.
* **Authentication:** Update client credentials to use the Valkey ACL username and password.
* **TLS:** Configure clients to use TLS and trust the Valkey certificate authority when encryption is enabled.
* **DNS and firewall:** Update DNS records and firewall rules so applications resolve and reach the Valkey servers.

### Validate the Migration

Confirm that Valkey serves traffic correctly before decommissioning ElastiCache.

* Compare cache hit ratios and latency against the ElastiCache baseline.
* Verify key counts, expiration behavior, and memory consumption.
* Monitor application logs for connection and authentication errors.
* Run Valkey in parallel with ElastiCache until the metrics match expectations.

### Migration Considerations

The following items require attention during the migration:

* **Cost model:** ElastiCache bills per node-hour, or per GB-hour of stored data plus compute for Serverless, with extra charges for data transfer and backup storage. A Valkey deployment costs the price of its servers, regardless of request volume.
* **Failover model:** ElastiCache manages failover automatically. Valkey requires Sentinel or an external orchestrator to detect failures and promote replicas.
* **Scaling:** ElastiCache scales nodes on demand. Valkey capacity is fixed by the server resources and requires manual scaling or clustering.
* **Monitoring:** Replace CloudWatch metrics with Valkey `INFO`, `SLOWLOG`, and latency monitoring, or an external monitoring stack.
* **Backups:** Replace managed ElastiCache snapshots with scheduled RDB and AOF backups.
* **Access control:** Replace AWS Identity and Access Management (IAM) authentication with Valkey ACL users and passwords.
* **Encryption:** Replace managed TLS certificates with self-managed certificates and a renewal process.
* **Upgrades:** ElastiCache offers the engine versions that AWS publishes, on its release schedule. Valkey lets you run any release when it ships, and you plan the upgrades and security patching yourself.
* **Network latency:** Place Valkey servers close to the application servers to match ElastiCache in-region latency.
* **Replication lag:** Account for asynchronous replication, which can briefly serve stale reads from a replica after a write.

## Conclusion

You have successfully deployed Valkey as an alternative to Amazon ElastiCache, with memory and eviction limits, access control, TLS encryption, persistence, primary-replica replication, high availability through Valkey Sentinel, monitoring, and backups. Applications connect to it with their existing Redis or Valkey client libraries. For more information about configuration, commands, and operational guidance, refer to the [official Valkey documentation](https://valkey.io/topics/).
