NEW RasterizedDB 1.1.0 is out: sharding and the gateway, the message broker, roles and row-level security, compression, .NET on NuGet, and the enterprise edition. What's new ›
DOCS / SETUP SCRIPTS / A REDIS REPLACEMENT

A Redis replacement

Runs the server as a Redis-compatible cache: any Redis client connects to port 6379 unchanged, with a memory limit and least-recently-used eviction, and optionally a snapshot to disk. Logins use the database's roles. PostgreSQL stays on 127.0.0.1 so you can manage roles and reach the same keys with KV … statements. It runs in the foreground.

Before you start

  • The server binary (see the install recipe).
  • Port 6379 free: stop any Redis on this machine, or pick another port.
  • A password for the role clients log in as, in RASTERIZEDDB_PG_PASSWORD.

Settings

bash variablePowerShell parameterDefaultWhat it does
RDB_BIN-RdbBinrasterizeddb / rasterizeddb.exeThe server binary.
RDB_DATA-Data./dataHolds the roles, and the snapshot db_kv_cache.snap when persistence is on.
RDB_KV_LISTEN-Listen127.0.0.1The Redis protocol's address. 0.0.0.0 for other machines.
RDB_KV_PORT-KvPort6379The Redis protocol's port.
RDB_KV_MAX_MEMORY-MaxMemory1gbRedis's maxmemory: 512mb, 4gb, or 0 for no limit.
RDB_KV_EVICTION-Evictionallkeys-lruRedis's maxmemory-policy: noeviction, allkeys-lru, volatile-lru, allkeys-random, volatile-random or volatile-ttl.
RDB_KV_PERSIST=1-PersistoffSave the keys every RDB_KV_SAVE_SECS (when anything changed) and at a clean stop, and load them at start.
RDB_KV_SAVE_SECS-SaveSeconds300Seconds between saves.
RDB_KV_TLS=on-TlsoffEvery TCP client must use TLS.
RDB_TLS_CERT, RDB_TLS_KEY-CertPath, -KeyPathnoneThe certificate for TLS. Without one, a self-signed certificate is made at each start.
RDB_USER-UserrasterizedThe role created on the first start, and the one AUTH <password> (without a user name) logs in as.
RDB_PG_PORT-PgPort5432The PostgreSQL port on 127.0.0.1, for administration.
RASTERIZEDDB_PG_PASSWORD$env:RASTERIZEDDB_PG_PASSWORDrequiredThe role's password, used when the data directory is first created.

--kv-auth trust (no password at all) is allowed on a loopback address only; this recipe always uses passwords.

Run it

sh
export RASTERIZEDDB_PG_PASSWORD='use-a-long-secret'
./setup.sh
# reachable from other machines, 4 GB, kept across restarts:
RDB_KV_LISTEN=0.0.0.0 RDB_KV_MAX_MEMORY=4gb RDB_KV_PERSIST=1 RDB_KV_TLS=on ./setup.sh
powershell
$env:RASTERIZEDDB_PG_PASSWORD = 'use-a-long-secret'
.\setup.ps1
.\setup.ps1 -Listen 0.0.0.0 -MaxMemory 4gb -Persist -Tls

Point applications at redis://rasterized:<password>@<host>:6379/0, or rediss://… with TLS.

Check that it works

sh
export REDISCLI_AUTH='use-a-long-secret'
redis-cli -p 6379 SET greeting hello EX 60
redis-cli -p 6379 GET greeting
redis-cli -p 6379 CONFIG GET maxmemory-policy
text
OK
"hello"
1) "maxmemory-policy"
2) "allkeys-lru"

With TLS on, add --tls --insecure (or --tls --cacert ca.pem with your own certificate). The memory limit and policy can also be changed while it runs, by a superuser role such as rasterized: CONFIG SET maxmemory 2gb.

Give each application its own role rather than sharing rasterized. Over the PostgreSQL port:

sh
PGPASSWORD='use-a-long-secret' psql "postgresql://rasterized@127.0.0.1:5432/postgres?sslmode=require" \
  -c "CREATE USER cache_app PASSWORD 'another-long-secret'"
redis-cli -p 6379 --user cache_app --askpass PING

Stop or undo

Ctrl+C stops the server cleanly; with persistence on it saves the keys first. Without persistence every key is gone when the process stops, as with a Redis that has no snapshot.

Limits

  • Strings, keys, hashes, lists, sets, sorted sets, pub/sub, MULTI/EXEC and WATCH are there. Lua scripting (EVAL, FUNCTION), streams, HyperLogLog, geo commands, BITFIELD/BITOP/BITPOS, the LFU policies, keyspace notifications, CLIENT TRACKING, WAIT, cluster mode and the append-only file are not. An unknown command gets Redis's ERR unknown command.
  • SELECT 0–15 work; the numbered databases belong to the server's default database.
  • CONFIG SET, CONFIG RESETSTAT, SAVE, BGSAVE and FLUSHALL need a superuser role (NOPERM otherwise). Every other command is open to any role that can log in.
  • Persistence is a periodic snapshot: a crash loses what changed since the last save.

The files

setup.sh · Linux and macOS (Bash)DOWNLOAD ↓
#!/usr/bin/env bash
# RasterizedDB as a Redis replacement: the Redis protocol on port 6379, a
# memory limit with LRU eviction, and optional snapshots to disk. PostgreSQL
# stays on 127.0.0.1 for administration. Runs in the foreground.
#
# Every setting can be overridden from the environment, for example:
#   RDB_KV_LISTEN=0.0.0.0 RDB_KV_MAX_MEMORY=4gb RDB_KV_PERSIST=1 ./setup.sh
set -euo pipefail

RDB_BIN="${RDB_BIN:-rasterizeddb}"
RDB_DATA="${RDB_DATA:-./data}"                   # roles, and the snapshot when RDB_KV_PERSIST=1
RDB_KV_LISTEN="${RDB_KV_LISTEN:-127.0.0.1}"
RDB_KV_PORT="${RDB_KV_PORT:-6379}"
RDB_KV_MAX_MEMORY="${RDB_KV_MAX_MEMORY:-1gb}"     # 0 is unbounded
RDB_KV_EVICTION="${RDB_KV_EVICTION:-allkeys-lru}" # noeviction, allkeys-lru, volatile-lru, allkeys-random, volatile-random, volatile-ttl
RDB_KV_PERSIST="${RDB_KV_PERSIST:-0}"             # 1 saves the keys to disk periodically and at a clean stop
RDB_KV_SAVE_SECS="${RDB_KV_SAVE_SECS:-300}"
RDB_KV_TLS="${RDB_KV_TLS:-off}"                   # on: clients must use TLS (redis-cli --tls)
RDB_TLS_CERT="${RDB_TLS_CERT:-}"                  # certificate for --kv-tls on; self-signed when empty
RDB_TLS_KEY="${RDB_TLS_KEY:-}"
RDB_USER="${RDB_USER:-rasterized}"               # the role AUTH <password> logs in as
RDB_PG_PORT="${RDB_PG_PORT:-5432}"

command -v "$RDB_BIN" >/dev/null 2>&1 || { echo "error: '$RDB_BIN' not found; set RDB_BIN to the server binary" >&2; exit 1; }
: "${RASTERIZEDDB_PG_PASSWORD:?set RASTERIZEDDB_PG_PASSWORD; Redis clients send it with AUTH}"
export RASTERIZEDDB_PG_PASSWORD

mkdir -p "$RDB_DATA"
RDB_DATA="$(cd "$RDB_DATA" && pwd)"

args=(--location "$RDB_DATA" --protocol pgwire
  --pg-addr 127.0.0.1 --pg-port "$RDB_PG_PORT" --pg-user "$RDB_USER"
  --kv-addr "$RDB_KV_LISTEN" --kv-port "$RDB_KV_PORT" --kv-user "$RDB_USER" --kv-auth password
  --kv-max-memory "$RDB_KV_MAX_MEMORY" --kv-eviction "$RDB_KV_EVICTION" --kv-tls "$RDB_KV_TLS")
if [ "$RDB_KV_PERSIST" = 1 ]; then
  args+=(--kv-persist --kv-save-interval-secs "$RDB_KV_SAVE_SECS")
fi
if [ -n "$RDB_TLS_CERT" ]; then
  args+=(--pg-cert "$RDB_TLS_CERT" --pg-key "$RDB_TLS_KEY")   # the Redis port uses the PostgreSQL certificate
fi

tls=""
[ "$RDB_KV_TLS" != on ] || tls=" --tls --insecure"
echo "Redis:      redis-cli -h $RDB_KV_LISTEN -p $RDB_KV_PORT$tls --askpass PING"
echo "URL:        redis${tls:+s}://$RDB_USER:<password>@$RDB_KV_LISTEN:$RDB_KV_PORT/0"
echo "Admin SQL:  psql \"postgresql://$RDB_USER@127.0.0.1:$RDB_PG_PORT/postgres?sslmode=require\""
echo "Memory limit $RDB_KV_MAX_MEMORY, eviction $RDB_KV_EVICTION, persistence $([ "$RDB_KV_PERSIST" = 1 ] && echo on || echo off). Stop with Ctrl+C."
echo

exec "$RDB_BIN" "${args[@]}"
setup.ps1 · Windows (PowerShell)DOWNLOAD ↓
#Requires -Version 5.1
<#
.SYNOPSIS
  RasterizedDB as a Redis replacement: the Redis protocol on port 6379, a
  memory limit with LRU eviction, and optional snapshots to disk. PostgreSQL
  stays on 127.0.0.1 for administration. Runs in the foreground.
.EXAMPLE
  $env:RASTERIZEDDB_PG_PASSWORD = 'use-a-long-secret'
  .\setup.ps1 -MaxMemory 4gb -Persist
#>
[CmdletBinding()]
param(
    [string]$RdbBin = $(if ($env:RDB_BIN) { $env:RDB_BIN } else { 'rasterizeddb.exe' }),
    # Roles, and the snapshot when -Persist is on.
    [string]$Data = $(if ($env:RDB_DATA) { $env:RDB_DATA } else { '.\data' }),
    [string]$Listen = $(if ($env:RDB_KV_LISTEN) { $env:RDB_KV_LISTEN } else { '127.0.0.1' }),
    [int]$KvPort = $(if ($env:RDB_KV_PORT) { [int]$env:RDB_KV_PORT } else { 6379 }),
    # 0 is unbounded.
    [string]$MaxMemory = $(if ($env:RDB_KV_MAX_MEMORY) { $env:RDB_KV_MAX_MEMORY } else { '1gb' }),
    [ValidateSet('noeviction', 'allkeys-lru', 'volatile-lru', 'allkeys-random', 'volatile-random', 'volatile-ttl')]
    [string]$Eviction = $(if ($env:RDB_KV_EVICTION) { $env:RDB_KV_EVICTION } else { 'allkeys-lru' }),
    # Save the keys to disk periodically and at a clean stop.
    [switch]$Persist = ($env:RDB_KV_PERSIST -eq '1'),
    [int]$SaveSeconds = $(if ($env:RDB_KV_SAVE_SECS) { [int]$env:RDB_KV_SAVE_SECS } else { 300 }),
    # Clients must use TLS (redis-cli --tls).
    [switch]$Tls = ($env:RDB_KV_TLS -eq 'on'),
    [string]$CertPath = $env:RDB_TLS_CERT,
    [string]$KeyPath = $env:RDB_TLS_KEY,
    # The role AUTH <password> logs in as.
    [string]$User = $(if ($env:RDB_USER) { $env:RDB_USER } else { 'rasterized' }),
    [int]$PgPort = $(if ($env:RDB_PG_PORT) { [int]$env:RDB_PG_PORT } else { 5432 })
)
$ErrorActionPreference = 'Stop'

$cmd = Get-Command $RdbBin -ErrorAction SilentlyContinue
if (-not $cmd) { throw "'$RdbBin' not found; pass -RdbBin with the path of rasterizeddb.exe." }
if (-not $env:RASTERIZEDDB_PG_PASSWORD) { throw 'Set $env:RASTERIZEDDB_PG_PASSWORD; Redis clients send it with AUTH.' }

New-Item -ItemType Directory -Force -Path $Data | Out-Null
$Data = (Resolve-Path -LiteralPath $Data).Path

$serverArgs = @('--location', $Data, '--protocol', 'pgwire',
    '--pg-addr', '127.0.0.1', '--pg-port', "$PgPort", '--pg-user', $User,
    '--kv-addr', $Listen, '--kv-port', "$KvPort", '--kv-user', $User, '--kv-auth', 'password',
    '--kv-max-memory', $MaxMemory, '--kv-eviction', $Eviction, '--kv-tls', $(if ($Tls) { 'on' } else { 'off' }))
if ($Persist) { $serverArgs += @('--kv-persist', '--kv-save-interval-secs', "$SaveSeconds") }
if ($CertPath) {
    # The Redis port uses the PostgreSQL certificate.
    $serverArgs += @('--pg-cert', (Resolve-Path -LiteralPath $CertPath).Path, '--pg-key', (Resolve-Path -LiteralPath $KeyPath).Path)
}

$tlsFlags = if ($Tls) { ' --tls --insecure' } else { '' }
$scheme = if ($Tls) { 'rediss' } else { 'redis' }
Write-Host "Redis:      redis-cli -h $Listen -p $KvPort$tlsFlags --askpass PING"
Write-Host "URL:        ${scheme}://${User}:<password>@${Listen}:$KvPort/0"
Write-Host "Admin SQL:  psql `"postgresql://$User@127.0.0.1:$PgPort/postgres?sslmode=require`""
Write-Host "Memory limit $MaxMemory, eviction $Eviction, persistence $(if ($Persist) { 'on' } else { 'off' }). Stop with Ctrl+C."
Write-Host ''

& $cmd.Source @serverArgs
exit $LASTEXITCODE
✓ page rendered in 252 µs axum + tera + htmx · no other javascript