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 / RASTERIZEDDB SERVER / KEY/VALUE CACHE (REDIS PROTOCOL)

Key/value cache (Redis protocol)

RasterizedDB has a built-in, Redis-compatible key/value store. Any Redis client can connect to it unchanged, and the same store answers KV … statements from SQL. Use it when your application needs a cache, counters, rate limits, sessions or simple queues and you would rather not run a separate Redis server next to the database.

This is not the same thing as key/value storage, which keeps a database's tables in an object store. The cache keeps keys: strings, counters, hashes, lists, sets and sorted sets, with optional lifetimes.

The store costs nothing until you use it. Nothing is allocated before the first KV statement or Redis connection, and the Redis port stays closed unless you pass --kv-port.

Turn on the Redis port

Start the server with --kv-port:

sh
RASTERIZEDDB_PG_PASSWORD=secret rasterizeddb \
    --location /var/lib/rasterizeddb \
    --protocol pgwire \
    --kv-port 6379

Then connect with any Redis client. By default the Redis port checks passwords against the database's own roles, and AUTH <password> with no user name is checked as the --pg-user role (rasterized unless you changed it):

sh
redis-cli -p 6379 -a secret PING
text
PONG

You do not need --kv-port to use the store from SQL. KV … statements work on any SQL connection whether the Redis port is open or not.

Settings

FlagDefaultWhat it does
--kv-port PORTclosedServe the Redis protocol on this TCP port.
--kv-socket PATHnoneServe the Redis protocol on a unix socket, beside --kv-port or instead of it (redis-cli -s PATH). The file's permissions and group come from --socket-mode and --socket-group. The path must fit a socket address (about 107 bytes on Linux).
--kv-addr IP127.0.0.1Address the Redis port listens on. Use 0.0.0.0 to accept remote clients.
--kv-auth password|trustpasswordpassword checks AUTH against the database's roles. trust asks for nothing and is refused on any address other than loopback, and on a unix socket whose permissions admit users outside its owner and group.
--kv-user ROLE--pg-userThe role that AUTH <password> (a password with no user name) is checked as.
--kv-tls on|offoffRequire TLS on --kv-port. See TLS.
--kv-max-memory SIZE0 (unbounded)The most the store may hold, like Redis's maxmemory: 512mb, 4gb, or a byte count.
--kv-eviction POLICYnoevictionWhat happens when the store is full, like Redis's maxmemory-policy. See Memory limit and eviction.
--kv-persistoffSave the store to disk periodically and on a clean shutdown. See Persistence.
--kv-save-interval-secs N300Seconds between periodic saves when --kv-persist is on. Must be at least 1.
--kv-threads None per CPUI/O threads for the Redis port.

Which database the Redis port serves

The Redis port serves the default database (--pg-default-db, postgres unless you changed it). Its 16 numbered Redis databases (SELECT 0 to SELECT 15) all belong to that one database.

Every database in the server has a key/value store of its own. To reach another database's store, connect to that database over SQL and use KV statements.

Authentication

The Redis port uses the database's roles: the ones CREATE ROLE makes and the PostgreSQL port checks (see Security). Both forms work:

sh
redis-cli -p 6379 --user alice --pass 'alice-password' PING
text
AUTH alice alice-password
HELLO 3 AUTH alice alice-password

Until a client authenticates it may only send AUTH, HELLO, QUIT and RESET, and its frames are capped at 10 arguments of 16 KiB each, as Redis caps unauthenticated clients.

Administrative commands

CONFIG SET, CONFIG RESETSTAT, SAVE, BGSAVE and FLUSHALL administer the server rather than the data, so they need a superuser role. On the Redis port a non-superuser gets NOPERM; from SQL they are refused like any other privileged statement. CONFIG GET and every other command is open to any role that can log in.

TLS

With --kv-tls on, every TCP client must complete a TLS handshake before its first command, as with Redis's tls-port. Plain connections to that port are dropped unanswered, and a handshake has ten seconds to finish.

The Redis port uses the same certificate and key as the PostgreSQL port (--pg-cert and --pg-key). Without them the server makes a self-signed pair at each start, so clients must either skip verification or be given a certificate you made yourself.

sh
RASTERIZEDDB_PG_PASSWORD=secret rasterizeddb \
    --location /var/lib/rasterizeddb \
    --protocol pgwire \
    --pg-cert /etc/rasterizeddb/server.crt \
    --pg-key /etc/rasterizeddb/server.key \
    --kv-port 6380 --kv-addr 0.0.0.0 --kv-tls on
sh
redis-cli --tls --cacert /etc/rasterizeddb/ca.crt -h db.example.com -p 6380 -a secret PING

Client libraries connect with a rediss:// URL. --kv-tls on needs --kv-port: the unix socket (--kv-socket) is always plain, since it never leaves the machine.

Use it from SQL

Prefix a Redis command with KV:

sql
KV SET session:42 '{"user":7}' EX 3600;     -- one row: OK
KV GET session:42;                            -- one row, or no rows
KV INCR page:/home:hits;                      -- one bigint row
KV HSET user:7 name 'Ada' plan 'pro';
KV HGETALL user:7;                            -- (field, value) rows
KV ZADD board 1500 ada 1320 bob;
KV ZRANGE board 0 9 REV WITHSCORES;           -- (member, score) rows
KV SCAN 0 MATCH 'session:*' COUNT 100;        -- (cursor, key) rows
KV INFO memory;                               -- (metric, value) rows

Arguments are bare words or single-quoted strings; write '' for a quote inside a string. A statement runs against Redis database 0 of the database you are connected to.

Result columns

The columns depend only on the command and its options, never on the data, so drivers and ORMs that describe a statement before running it work normally.

ReplyColumns
integer (INCR, DEL, HSET, …)value bigint
score (ZSCORE, ZINCRBY)value float8
a string, or a list of stringsvalue text, one row per element; a missing key gives no row
HGETALL, CONFIG GETfield text, value text
… WITHSCORES, ZPOPMIN, ZPOPMAXmember text, score float8
ZRANK … WITHSCORE, ZREVRANK … WITHSCORErank bigint, score float8
SCAN, HSCAN, SSCAN, ZSCANcursor text and the item columns (key, field/value, member, member/score)
INFOmetric text, value text

Binary keys and values

Values are text by default, and a value that is not valid UTF-8 is refused rather than returned mangled. For binary data, write any argument as hex bytes with x'…' (an even number of hex digits), and put BINARY after KV to get the value columns back as bytea:

sql
KV SET x'00ff10' x'deadbeef';
KV BINARY GET x'00ff10';         -- value comes back as bytea
KV BINARY HGETALL h;             -- field and value both bytea

Under BINARY, counts, scores and a scan's cursor keep their usual types.

What SQL cannot do

  • Commands that need a connection of their own are refused from SQL with a pointer to the Redis port: MULTI/EXEC and the other transaction commands, SUBSCRIBE and the other subscribe commands, SELECT, AUTH, HELLO, CLIENT, QUIT, RESET. PUBLISH and PUBSUB work from SQL.
  • MOVE and SWAPDB work across numbered databases, which SQL does not select, so they are refused.
  • A blocking pop (BLPOP, BRPOP, BLMOVE, BRPOPLPUSH) answers at once, as though its timeout had passed.

KV statements are not transactional

A KV statement takes effect when it runs. A later ROLLBACK does not undo it, in the same way that a database rollback does not undo a Redis command. For an atomic group of key/value commands, use MULTI/EXEC on the Redis port.

What the logs record

The statement log, SHOW QUERIES and pg_stat_statements record a KV statement as its command alone, for example KV SET <redacted>. A key such as session:<token> can be as secret as a value.

Memory limit and eviction

--kv-max-memory bounds the store; 0 means no limit. When the store is full, --kv-eviction decides what happens:

PolicyWhen full
noeviction (default)The write is refused with Redis's OOM command not allowed … error.
allkeys-lruEvict the least recently used key.
volatile-lruEvict the least recently used key that has a lifetime.
allkeys-randomEvict a random key.
volatile-randomEvict a random key that has a lifetime.
volatile-ttlEvict the key with a lifetime closest to expiring.

As in Redis, the victim is chosen from a small sample of keys, not from an exact global order. A single value larger than the configured share of memory is still stored.

You can change both at runtime, from a Redis client or from SQL, as a superuser:

sh
redis-cli -p 6379 -a secret CONFIG SET maxmemory 1gb
redis-cli -p 6379 -a secret CONFIG SET maxmemory-policy allkeys-lru
sql
KV CONFIG SET maxmemory 1gb;
KV CONFIG GET maxmemory;

CONFIG SET also accepts save (CONFIG SET save "60 1" turns persistence on with that interval in seconds; CONFIG SET save "" turns it off). appendonly no is accepted; appendonly yes is refused. A few settings clients commonly send at start-up (maxmemory-samples, timeout, tcp-keepalive, notify-keyspace-events, lazyfree-lazy-user-del, maxclients) are accepted and ignored. CONFIG REWRITE is refused: settings changed at runtime are not written back to the command line.

Persistence

The store is a cache, so by default nothing is written to disk and a restart starts empty.

  • SAVE, BGSAVE, or KV SAVE from SQL, writes every numbered database to db_kv_cache.snap beside the database's files.
  • When the database opens and finds that file, it loads it.
  • With --kv-persist, the store also saves every --kv-save-interval-secs seconds when anything changed, and on a clean shutdown.

A save is written to a new file, synced and renamed into place, so a crash during a save leaves the previous snapshot. A damaged snapshot is refused as a whole, never half loaded. This is Redis's RDB snapshotting without an append-only file: a crash loses whatever changed since the last save.

Replication

On a node with replication on (see Replication), every write to the store, from the Redis port or from KV SQL and on any of the 16 numbered databases, is shipped to the other nodes over the same link as table data. It gets the same authentication, ordering and catch-up for a node that was away. A node applies each write to the same database's store, in the order it ran on the origin.

What travels is the effect of a command, by Redis's own propagation rules, so every node ends with the same answer:

  • a relative lifetime (EX, PX, SETEX, EXPIRE, GETEX, …) is shipped as the absolute expiry time it set;
  • SPOP ships as SREM of the members it took, and ZPOPMIN/ZPOPMAX as ZREM;
  • INCRBYFLOAT ships as SET of its result, and HINCRBYFLOAT as HSET;
  • a blocking pop ships as the LPOP, RPOP or LMOVE that happened;
  • a write that changed nothing (a failed NX, a WRONGTYPE, a DEL of a missing key) ships nothing;
  • a MULTI/EXEC block ships as one entry and is applied atomically;
  • FLUSHDB and FLUSHALL ship.

These do not replicate:

  • expiry and eviction: each node removes a key at its absolute expiry time itself, and evicts under its own memory limit. Clocks that disagree make lifetimes end at slightly different moments on each node;
  • PUBLISH: subscribers hear only messages published on their own node;
  • settings (CONFIG SET) and SAVE.

Things to know when replicating the cache:

  • Every node takes writes, and arrival order wins. Two nodes writing the same key at the same moment can be left holding different values. If that matters, write each key from one node at a time.
  • A command that fails on another node (for example a WRONGTYPE after two nodes wrote one key as different types) is counted and skipped; it never stops the stream.
  • A cache write never waits for a disk sync or for another node, whatever the replication mode says.
  • A single write whose effect would be larger than about 24 MB is refused on a replicating node.
  • A node restarted without a snapshot comes back empty and receives only the writes made after its last applied position. Replication carries what happens, not what is.
  • A node that falls further behind than the origin's replication log retention (--replication-retention-mb) has to be reseeded, as for table data.
  • Every node must run a build that understands key/value replication before key/value writes are made on a replicating node.

SHOW REPLICATION STATS reports kv_effects, kv_records, kv_applied and kv_apply_errors.

Supported commands

Replies and error messages are Redis's own (WRONGTYPE …, ERR value is not an integer or out of range, OOM command not allowed …), so client libraries recognise them. INFO and HELLO report redis_version:7.4.0, because clients such as Sidekiq check the version before using newer commands.

GroupCommands
StringsGET SET (with NX XX GET EX PX EXAT PXAT KEEPTTL) SETNX SETEX PSETEX GETSET GETDEL GETEX MGET MSET MSETNX INCR DECR INCRBY DECRBY INCRBYFLOAT APPEND STRLEN GETRANGE SUBSTR SETRANGE SETBIT GETBIT BITCOUNT
KeysDEL UNLINK EXISTS TOUCH EXPIRE PEXPIRE EXPIREAT PEXPIREAT (with NX XX GT LT) TTL PTTL EXPIRETIME PEXPIRETIME PERSIST TYPE RENAME RENAMENX COPY KEYS SCAN DBSIZE RANDOMKEY OBJECT MEMORY MOVE
HashesHSET HSETNX HMSET HGET HMGET HGETALL HDEL HEXISTS HLEN HKEYS HVALS HINCRBY HINCRBYFLOAT HSTRLEN HRANDFIELD HSCAN
ListsLPUSH RPUSH LPUSHX RPUSHX LPOP RPOP LLEN LRANGE LINDEX LSET LREM LTRIM LINSERT LPOS LMOVE RPOPLPUSH BLPOP BRPOP BLMOVE BRPOPLPUSH
SetsSADD SREM SMEMBERS SISMEMBER SMISMEMBER SCARD SPOP SRANDMEMBER SINTER SINTERSTORE SINTERCARD SUNION SUNIONSTORE SDIFF SDIFFSTORE SMOVE SSCAN
Sorted setsZADD (with NX XX GT LT CH INCR) ZREM ZSCORE ZMSCORE ZINCRBY ZCARD ZCOUNT ZLEXCOUNT ZRANK ZREVRANK (with WITHSCORE) ZRANGE (with BYSCORE BYLEX REV LIMIT WITHSCORES) ZREVRANGE ZRANGEBYSCORE ZREVRANGEBYSCORE ZRANGEBYLEX ZREVRANGEBYLEX ZPOPMIN ZPOPMAX ZREMRANGEBYRANK ZREMRANGEBYSCORE ZREMRANGEBYLEX ZSCAN ZUNION ZINTER ZDIFF ZUNIONSTORE ZINTERSTORE ZDIFFSTORE (with WEIGHTS AGGREGATE)
Pub/SubPUBLISH SUBSCRIBE UNSUBSCRIBE PSUBSCRIBE PUNSUBSCRIBE PUBSUB
TransactionsMULTI EXEC DISCARD WATCH UNWATCH
ConnectionPING ECHO AUTH HELLO (RESP2 and RESP3) SELECT (databases 0–15) QUIT RESET CLIENT (ID SETNAME GETNAME SETINFO INFO LIST REPLY)
ServerINFO CONFIG (GET SET RESETSTAT) COMMAND (COUNT LIST INFO DOCS GETKEYS) SAVE BGSAVE LASTSAVE FLUSHDB FLUSHALL TIME

SWAPDB is recognised and answered with an error. Any command outside this list gets Redis's ERR unknown command.

Every command is atomic on its key. Commands on several keys (MSET, RENAME, LMOVE, SINTERSTORE, ZUNIONSTORE, …) and EXEC blocks are atomic too.

A pub/sub subscriber whose queue fills up because it reads too slowly is disconnected, as Redis does past its output-buffer limit, rather than being sent a stream with gaps in it.

Use it from Rust

The Rust client has a typed API for the store: see Key/value from the Rust client.

Limits

  • Not implemented: Lua scripting (EVAL, FUNCTION), streams (XADD and the rest), HyperLogLog, geo commands, BITFIELD, BITOP, BITPOS, OBJECT FREQ and the LFU eviction policies, keyspace notifications, CLIENT TRACKING, WAIT, cluster mode, and the append-only file.
  • Persistence is snapshot-only. A crash loses changes since the last save.
  • HSCAN, SSCAN and ZSCAN return the whole structure in one page. SCAN can return more keys than COUNT, which Redis's contract allows.
  • KV statements are not part of SQL transactions.
  • From SQL, values must be UTF-8 text unless you use KV BINARY and x'…' arguments.
  • The Redis port serves only the default database; other databases' stores are reachable through SQL only.
✓ page rendered in 212 µs axum + tera + htmx · no other javascript