Key-value stores: kv, Redis™ and memcached

Jennifer

One store in the process, two servers on the network, and one line to switch between them.

November 2026, by @mplx.
Based on Jennifer 0.28.0

Powered by Jennifer's Cantrip - Markdown into slide decks, https://github.com/jennifer-language/cantrip
1 / 19

Why a key-value store

where the data livesshared with
use kv;this processtasks and modules of this run
redis.ja Redis serverevery process that connects
memcache.ja memcached serverevery process that connects
2 / 19

kv: a store in the process

def store as kv.Store init kv.open();
kv.set($store, "greeting", "hello", 1);       # expires in 1 s
kv.set($store, "hits", "0", 0);               # 0 = never
io.printf("%s, hits %d, absent %d\n", kv.get($store, "greeting"),
    kv.incr($store, "hits", 5), kv.incr($store, "nope", 1));
io.printf("add: %v %v\n", kv.add($store, "lock", "me", 30),
    kv.add($store, "lock", "you", 30));
time.sleep(time.fromMilliseconds(1100));
io.printf("later: [%s]\n", kv.get($store, "greeting"));
hello, hits 5, absent -1
add: true false
later: []
3 / 19

The handle is shared

def store as kv.Store init kv.open();
kv.set($store, "hits", "0", 0);
def tasks as list of task of int init [];
for (def i in 0..4) {
    $tasks[] = spawn {         # a copy of $store: the same map
        for (def j in 0..1000) { kv.incr($store, "hits", 1); }
        return 0;
    };
}
task.waitAll($tasks);
io.printf("hits: %s\n", kv.get($store, "hits"));
hits: 4000
4 / 19

kv: strict types, parsed values, a file

kv.set($s, "name", "ada", 0);
kv.incr($s, "name", 1);           # throws
kv.setValue($s, "config", json.decode('{"debug": true}'), 0);
def cfg as json.Value init kv.getValue($s, "config");  # no copy
kv.get($s, "config");             # throws
def f as kv.Store init kv.openFile("state.kv");   # survives the run
runtime: kv.incr: value at "name" is not a number
runtime: kv.get: "config" holds a json.Value value, not a string; ...
run 1
5 / 19

kv: what it does not do

When more than one process must agree, you need a server.

6 / 19

Redis: connecting

import "redis.j" as redis;
import "transport.j" as transport;

def opts as redis.Options init redis.Options{host: "127.0.0.1",
    port: 16379, security: transport.Security.None,
    user: "", password: "", db: 0};
def db as redis.Session init redis.connect($opts);
7 / 19

Redis: strings, TTLs, counters

redis.set($db, "greeting", "hello");                   # no TTL
redis.command($db, ["SET", "token", "abc", "EX", "60"]);
redis.command($db, ["EXPIRE", "greeting", "300"]);
io.printf("%s, ttl %d\n", redis.get($db, "greeting"),
    redis.command($db, ["TTL", "token"]).num);
io.printf("visits %d, absent [%s] %v\n", redis.incr($db, "visits"),
    redis.get($db, "nope"), redis.exists($db, "nope"));
hello, ttl 60
visits 1, absent [] false
8 / 19

Redis: hashes, lists, sets

redis.hset($db, "user:1", "name", "Ada");
redis.hset($db, "user:1", "lang", "en");
io.printf("%v %s\n", redis.hgetAll($db, "user:1"),
    redis.hget($db, "user:1", "name"));
redis.rpush($db, "queue", "job-1");
redis.rpush($db, "queue", "job-2");
io.printf("%v, next %s\n", redis.lrange($db, "queue", 0, -1),
    redis.lpop($db, "queue"));
{"name": "Ada", "lang": "en"} Ada
["job-1", "job-2"], next job-1
9 / 19

Redis: pipelines and transactions

def rs as list of redis.Reply init redis.pipeline($db, [
    ["SET", "a", "1"], ["INCR", "greeting"], ["INCR", "a"]]);
io.printf("%s, %s, %d\n", $rs[0].str, $rs[1].kind, $rs[2].num);
redis.multi($db);
redis.command($db, ["SET", "stock", "10"]);        # +QUEUED
redis.command($db, ["DECRBY", "stock", "3"]);      # +QUEUED
def done as list of redis.Reply init redis.exec($db);
io.printf("stock: %d\n", $done[1].num);
OK, error, 2
stock: 7
10 / 19

Redis: pub/sub

def sub as redis.Session init redis.connect($opts);   # own socket
redis.subscribe($sub, ["news"]);
def listener as task of string init spawn {
    def m as redis.Message init redis.receiveMessage($sub);
    return "[{$m.channel}] {$m.payload}";
};
def pub as redis.Session init redis.connect($opts);
io.printf("reached %d\n", redis.publish($pub, "news", "deploy done"));
io.printf("%s\n", task.wait($listener));
reached 1
[news] deploy done
11 / 19

Redis: when it says no

redis ERR: ERR value is not an integer or out of range
redis WRONGTYPE: WRONGTYPE Operation against a key holding the wrong ...
net: net.connectWith: 127.0.0.1:16999: dial tcp 127.0.0.1:16999: connect: ...
redis WRONGPASS
redis NOAUTH
timeout: net.readBytes: read timed out
12 / 19

memcached: a narrower model

def mc as memcache.Session init memcache.connect(memcache.Options{
    host: "127.0.0.1", port: 11311});         # no auth, no TLS
memcache.set($mc, "greeting", "hello", 60);
io.printf("%s, add again: %v\n", memcache.get($mc, "greeting"),
    memcache.add($mc, "greeting", "hi", 60));
io.printf("incr absent: %d\n", memcache.incr($mc, "hits", 1));
memcache.set($mc, "stock", "2", 0);
io.printf("decr: %d\n", memcache.decr($mc, "stock", 5));
hello, add again: false
incr absent: -1
decr: 0
13 / 19

memcached: check-and-set

def it as memcache.Item init memcache.gets($mc, "stock");
memcache.set($mc, "stock", "9", 0);            # someone else writes
io.printf("cas: %s\n", memcache.cas($mc, "stock", "1", 0, $it.cas));
io.printf("multi: %v\n",
    memcache.getMulti($mc, ["greeting", "stock", "nope"]));
cas: exists
multi: {"greeting": "hello", "stock": "9"}
14 / 19

memcached: when it says no

memcache.set($mc, "big", strings.replicate("x", 2 * 1024 * 1024), 0);
memcache.set($mc, "has space", "v", 0);
memcache SERVER_ERROR: object too large for cache
memcache: key contains an illegal byte (space, control, or DEL) at ...
15 / 19

kvstore: one line picks the backend

func pick(name as string) {
    if ($name == "redis") {
        return redis.kvStore(redis.connect($ropts));
    } elseif ($name == "memcache") {
        return memcache.kvStore(memcache.connect($mopts));
    }
    return kvstore.inProcessStore();      # or fileStore("state.kv")
}
def store as kvstore.Store init pick($name);
def n as int init kvstore.incrWindow($store, "hits:{$name}", 60);
local 2  memcache 2  redis 2
16 / 19

session and ratelimit on top

def store as kvstore.Store init kvstore.inProcessStore();
def id as string init session.create($store, 1800);
def data as json.Value init session.load($store, $id);
$data = json.set($data, "/user", json.decode('"ada"'));
session.save($store, $id, $data, 1800);
def fresh as string init session.rotate($store, $id, 1800); # login
def lim as ratelimit.Limiter init ratelimit.fixedWindow($store, 3, 60);
def r as ratelimit.Result init ratelimit.check($lim, "ip:203.0.113.7");
old false, new true: {"user":"ada"}
true true true false, retry after 53 s
17 / 19

Which one?

You needTake
A cache or counter in one process, a testkv (inProcessStore)
State for a CLI tool between runskv.openFile (fileStore)
Shared cache, sessions, rate limits for a fleetmemcached or Redis
Structures, queues, pub/sub, transactionsRedis
An untrusted, unbounded key seta server with maxmemory
Data you cannot losenone of these: use sql
18 / 19

Recap

Docs: docs.jennifer-lang.dev

19 / 19