Introduction
Valkey is a community fork of Redis, launched in 2024 by former contributors to preserve pure open-source licensing amid Redis Inc.'s changes. This in-memory key-value store excels at caching, user sessions, queues, and real-time databases, delivering blazing-fast performance (millions of ops/sec). Why adopt it in 2026? It's 100% Redis-compatible, free, scalable with clustering, and supports persistence (RDB snapshots, AOF logs). Unlike paid Redis Cloud, Valkey integrates seamlessly into production. This intermediate tutorial takes you from installation to a full Node.js app, covering config, persistence, and monitoring. By the end, you'll have a production-ready setup, as if mentored by a senior dev. (128 words)
Prerequisites
- Linux system (Ubuntu 22.04+) or macOS with Homebrew
- Git and build essentials:
sudo apt install build-essential - Node.js 20+ and npm for client examples
- Docker (optional for containers)
- Basic Redis knowledge (keys, hashes, lists)
Installing Valkey from the Official Repository
#!/bin/bash
# Add the official Valkey repo (Ubuntu/Debian)
curl -fsSL https://packages.valkey.io/public.key | sudo gpg --dearmor -o /usr/share/keyrings/valkey-archive-keyring.gpg
echo "deb [signed-by=/usr/share/keyrings/valkey-archive-keyring.gpg] https://packages.valkey.io/deb $(lsb_release -cs) main" | sudo tee /etc/apt/sources.list.d/valkey.list > /dev/null
sudo apt update
sudo apt install valkey-tools valkey-server -y
# Verification
valkey-server --version
valkey-cli --versionThis script adds the official Valkey repo, installs the server and CLI tools. On macOS, use brew install valkey. Avoid snaps for full config control; always test the version with --version to confirm installation.
First Use with CLI
Start Valkey with sudo systemctl start valkey-server (or brew services start valkey on macOS). Connect via valkey-cli. Test basics: SET user:1 "Alice", GET user:1 returns "Alice". Use FLUSHALL to clear. Analogy: Valkey is like a giant RAM whiteboard – ultra-fast but volatile without persistence. PING responds PONG in <1ms.
Custom Base Configuration
# Valkey production-ready configuration
# Bind to localhost only for security
bind 127.0.0.1
# Default port
port 6379
# Client timeout
timeout 0
tcp-keepalive 300
# Detailed logs
loglevel notice
logfile "/var/log/valkey/valkey-server.log"
# RDB persistence (snapshots)
save 900 1
save 300 10
save 60 10000
dbfilename dump.rdb
dir /var/lib/valkey/
# AOF enabled for durability
appendonly yes
appendfsync everysec
# Max memory 1GB, evict LRU
maxmemory 1gb
maxmemory-policy allkeys-lru
# Basic auth (change the password!)
requirepass MonSuperMotDePasse123This /etc/valkey/valkey.conf file (copy and adapt) enables RDB persistence (auto snapshots) and AOF (append logs), caps RAM at 1GB with LRU eviction. requirepass secures access. Restart with sudo systemctl restart valkey-server; pitfall: forget dir and dumps will fail.
Enabling and Testing Persistence
After config, restart and test: valkey-cli -a MonSuperMotDePasse123. Insert 1000 keys (for i in {1..1000}; do SET key$i $i; done), kill (-9) the process, restart: valkey-cli INFO persistence shows RDB/AOF active. RDB = compact snapshots (ideal for backups); AOF = incremental logs (max durability, but larger).
Persistence Test Script
#!/bin/bash
PASSWORD="MonSuperMotDePasse123"
VALKEY_CLI="valkey-cli -a $PASSWORD"
# Insert data
$VALKEY_CLI FLUSHALL
for i in {1..500}; do
$VALKEY_CLI SET test:key$i "valeur $i"
done
# Manual snapshot
$VALKEY_CLI BGSAVE
# Check memory and persistence
$VALKEY_CLI INFO persistence
$VALKEY_CLI INFO memory
# Kill and restart
sudo pkill valkey-server
sudo systemctl start valkey-server
sleep 2
# Verify recovery
RECOVERED=$($VALKEY_CLI EXISTS test:key1)
echo "Key recovered: $RECOVERED (1=yes)"
$VALKEY_CLI KEYS "test:key*" | wc -lThis script tests RDB/AOF: inserts data, snapshots, brute-force kill, restarts, verifies recovery. BGSAVE forces async snapshot. Pitfall: without appendonly yes, AOF is ignored; tune maxmemory to avoid OOM in production.
Integrating with a Node.js App
For real-world use, pick a client like @valkey/js (official). Install with npm i @valkey/js. Analogy: CLI is for dev console; client is for scalable production. Manage connection pools, retries, and pub/sub for real-time.
Complete Node.js TypeScript Client
import { createClient } from 'redis';
async function main() {
const client = createClient({
url: 'redis://localhost:6379',
password: 'MonSuperMotDePasse123',
});
client.on('error', (err) => console.error('Erreur Valkey:', err));
await client.connect();
// SET/GET basique
await client.set('user:42', JSON.stringify({ name: 'Bob', age: 30 }));
const user = await client.get('user:42');
console.log('User:', JSON.parse(user!));
// Hash pour objets complexes
await client.hSet('session:abc123', {
csrf: 'token123',
expires: Date.now() + 3600000,
});
const session = await client.hGetAll('session:abc123');
console.log('Session:', session);
// Liste pour file d'attente
await client.lPush('jobs', 'job1', 'job2');
const job = await client.lPop('jobs');
console.log('Job pop:', job);
// TTL exemple
await client.set('temp:cache', 'data', { EX: 60 });
await client.quit();
}
main().catch(console.error);This standalone TS script uses @valkey/js (Redis-compatible). Handles hashes (sessions), lists (queues), TTL (cache). Add ts-node to run; pitfall: forget connect() or error handler, and it crashes in prod. Scale with poolSize: 10.
Advanced Valkey CLI Monitoring
#!/bin/bash
PASSWORD="MonSuperMotDePasse123"
# Real-time stats
valkey-cli -a $PASSWORD --stat
# Detailed INFO
valkey-cli -a $PASSWORD INFO all | grep -E '(used_memory|connected_clients|keyspace_hits)'
# Slowlog top 10 slow queries
valkey-cli -a $PASSWORD SLOWLOG get 10
# Pub/Sub test
valkey-cli -a $PASSWORD --cluster create 127.0.0.1:6379 &
# Cleanup
valkey-cli -a $PASSWORD FLUSHDBThis script shows live metrics (--stat), slow queries, and preps clustering. Use INFO keyspace_hits for cache hit-rate (>90% ideal). Pitfall: without monitoring, memory leaks go unnoticed; cron this script every 5min.
Best Practices
- Security: Always use
requirepass+bind 127.0.0.1; TLS in prod viatls-port. - Memory:
maxmemory-policy allkeys-lfufor hot cache data; monitorused_memory. - Persistence: AOF
everysec+ weekly RDB; offsite backups. - Scaling: Cluster mode for >1GB; Sentinel for HA.
- Clients: Connection pools (5-20), exponential retries.
Common Errors to Avoid
- Forget auth:
NOAUTH Authentication required→ always use-ain CLI. - No
maxmemory: OOM killer terminates the process in prod. - Persistence off: Data lost after reboot → check
INFO persistence. - No TTL on keys: Memory bloat → use
EXPIREsystematically for caches.
Next Steps
- Official docs: valkey.io
- Cluster setup:
valkey-cli --cluster create - Alternatives: Dragonfly for Redis compat.
- Learni Dev Training on advanced NoSQL and scaling.