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:
RASTERIZEDDB_PG_PASSWORD=secret rasterizeddb \
--location /var/lib/rasterizeddb \
--protocol pgwire \
--kv-port 6379Then 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):
redis-cli -p 6379 -a secret PINGPONGYou 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
| Flag | Default | What it does |
|---|---|---|
--kv-port PORT | closed | Serve the Redis protocol on this TCP port. |
--kv-socket PATH | none | Serve 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 IP | 127.0.0.1 | Address the Redis port listens on. Use 0.0.0.0 to accept remote clients. |
--kv-auth password|trust | password | password 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-user | The role that AUTH <password> (a password with no user name) is checked as. |
--kv-tls on|off | off | Require TLS on --kv-port. See TLS. |
--kv-max-memory SIZE | 0 (unbounded) | The most the store may hold, like Redis's maxmemory: 512mb, 4gb, or a byte count. |
--kv-eviction POLICY | noeviction | What happens when the store is full, like Redis's maxmemory-policy. See Memory limit and eviction. |
--kv-persist | off | Save the store to disk periodically and on a clean shutdown. See Persistence. |
--kv-save-interval-secs N | 300 | Seconds between periodic saves when --kv-persist is on. Must be at least 1. |
--kv-threads N | one per CPU | I/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:
redis-cli -p 6379 --user alice --pass 'alice-password' PINGAUTH alice alice-password
HELLO 3 AUTH alice alice-passwordUntil 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.
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 onredis-cli --tls --cacert /etc/rasterizeddb/ca.crt -h db.example.com -p 6380 -a secret PINGClient 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:
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) rowsArguments 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.
| Reply | Columns |
|---|---|
integer (INCR, DEL, HSET, …) | value bigint |
score (ZSCORE, ZINCRBY) | value float8 |
| a string, or a list of strings | value text, one row per element; a missing key gives no row |
HGETALL, CONFIG GET | field text, value text |
… WITHSCORES, ZPOPMIN, ZPOPMAX | member text, score float8 |
ZRANK … WITHSCORE, ZREVRANK … WITHSCORE | rank bigint, score float8 |
SCAN, HSCAN, SSCAN, ZSCAN | cursor text and the item columns (key, field/value, member, member/score) |
INFO | metric 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:
KV SET x'00ff10' x'deadbeef';
KV BINARY GET x'00ff10'; -- value comes back as bytea
KV BINARY HGETALL h; -- field and value both byteaUnder 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/EXECand the other transaction commands,SUBSCRIBEand the other subscribe commands,SELECT,AUTH,HELLO,CLIENT,QUIT,RESET.PUBLISHandPUBSUBwork from SQL. MOVEandSWAPDBwork 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:
| Policy | When full |
|---|---|
noeviction (default) | The write is refused with Redis's OOM command not allowed … error. |
allkeys-lru | Evict the least recently used key. |
volatile-lru | Evict the least recently used key that has a lifetime. |
allkeys-random | Evict a random key. |
volatile-random | Evict a random key that has a lifetime. |
volatile-ttl | Evict 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:
redis-cli -p 6379 -a secret CONFIG SET maxmemory 1gb
redis-cli -p 6379 -a secret CONFIG SET maxmemory-policy allkeys-lruKV 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, orKV SAVEfrom SQL, writes every numbered database todb_kv_cache.snapbeside 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-secsseconds 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; SPOPships asSREMof the members it took, andZPOPMIN/ZPOPMAXasZREM;INCRBYFLOATships asSETof its result, andHINCRBYFLOATasHSET;- a blocking pop ships as the
LPOP,RPOPorLMOVEthat happened; - a write that changed nothing (a failed
NX, aWRONGTYPE, aDELof a missing key) ships nothing; - a
MULTI/EXECblock ships as one entry and is applied atomically; FLUSHDBandFLUSHALLship.
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) andSAVE.
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
WRONGTYPEafter 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.
| Group | Commands |
|---|---|
| Strings | GET 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 |
| Keys | DEL 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 |
| Hashes | HSET HSETNX HMSET HGET HMGET HGETALL HDEL HEXISTS HLEN HKEYS HVALS HINCRBY HINCRBYFLOAT HSTRLEN HRANDFIELD HSCAN |
| Lists | LPUSH RPUSH LPUSHX RPUSHX LPOP RPOP LLEN LRANGE LINDEX LSET LREM LTRIM LINSERT LPOS LMOVE RPOPLPUSH BLPOP BRPOP BLMOVE BRPOPLPUSH |
| Sets | SADD SREM SMEMBERS SISMEMBER SMISMEMBER SCARD SPOP SRANDMEMBER SINTER SINTERSTORE SINTERCARD SUNION SUNIONSTORE SDIFF SDIFFSTORE SMOVE SSCAN |
| Sorted sets | ZADD (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/Sub | PUBLISH SUBSCRIBE UNSUBSCRIBE PSUBSCRIBE PUNSUBSCRIBE PUBSUB |
| Transactions | MULTI EXEC DISCARD WATCH UNWATCH |
| Connection | PING ECHO AUTH HELLO (RESP2 and RESP3) SELECT (databases 0–15) QUIT RESET CLIENT (ID SETNAME GETNAME SETINFO INFO LIST REPLY) |
| Server | INFO 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 (XADDand the rest), HyperLogLog, geo commands,BITFIELD,BITOP,BITPOS,OBJECT FREQand 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,SSCANandZSCANreturn the whole structure in one page.SCANcan return more keys thanCOUNT, which Redis's contract allows.KVstatements are not part of SQL transactions.- From SQL, values must be UTF-8 text unless you use
KV BINARYandx'…'arguments. - The Redis port serves only the default database; other databases' stores are reachable through SQL only.