A Redis-compatible in-memory data store, written from scratch in Java 25. No client library, no networking framework, no Redis source: the wire protocol, the connection handling, and the keyspace are all implemented here.
A real Redis client can connect to Slate and issue string commands. The RESP2 protocol is parsed
from raw bytes, each connection is served on its own virtual thread, and replies are byte-for-byte
what Redis would send. Keys can be given a time to live and expire on their own, both when read and
on a background cycle, so SET k v EX 10, TTL, and PERSIST behave as a client expects and memory
comes back even for keys nobody reads again. Keys can also hold lists, with LPUSH, RPUSH, LPOP,
RPOP, LRANGE, LINDEX and LSET, hashes, with HSET, HGET, HDEL, HEXISTS, HLEN and
HGETALL, and sets, with SADD, SREM, SISMEMBER, SMEMBERS and SCARD. A string holding an
integer can be counted through, with INCR, DECR, INCRBY and DECRBY, and counting never
disturbs the key's time to live. A command run against a key of the wrong type is refused with the
same WRONGTYPE error Redis gives.
Requires JDK 21 or newer. Slate is built against 25.
mvn clean verify
java -jar target/slate-0.1.0-SNAPSHOT.jar
The default port is 6379. Pass --port 6380 to move it, which is what you want if a real Redis is
already running.
Any Redis client works:
redis-cli -p 6379 set greeting hello
redis-cli -p 6379 get greeting
There is also an inline mode, so a bare terminal is enough to drive it:
$ telnet 127.0.0.1 6379
PING
+PONG
SET greeting hello
+OK
GET greeting
$5
hello
| Command | Arity | Reply |
|---|---|---|
PING [message] |
1 or 2 | +PONG, or the message as a bulk string |
ECHO message |
2 | the message as a bulk string |
SET key value [EX s | PX ms] [NX | XX] |
3 or more | +OK, or a null bulk string when NX/XX declines |
GET key |
2 | the value, or a null bulk string when absent |
DEL key [key ...] |
2 or more | how many keys were removed |
EXISTS key [key ...] |
2 or more | how many of the named keys exist |
TTL key |
2 | seconds left, -1 with no deadline, -2 when absent |
PTTL key |
2 | as TTL, in milliseconds |
PERSIST key |
2 | 1 if a deadline was removed, 0 otherwise |
TYPE key |
2 | string, list, hash, set, or none for a missing key |
LPUSH key value [value ...] |
3 or more | the list's length after the push |
RPUSH key value [value ...] |
3 or more | the list's length after the push |
LPOP key [count] |
2 or 3 | one bulk string, or an array when a count is given |
RPOP key [count] |
2 or 3 | as LPOP, from the tail |
LLEN key |
2 | the length, 0 for a missing key |
LRANGE key start stop |
4 | the elements in the inclusive range, negative indexes counting from the tail |
LINDEX key index |
3 | the element, or a null bulk string when out of range |
LSET key index value |
4 | +OK, or an error when the key or index does not exist |
HSET key field value [field value ...] |
4 or more, even | how many fields were created; an overwrite does not count |
HGET key field |
3 | the value, or a null bulk string when the key or field is absent |
HDEL key field [field ...] |
3 or more | how many of the named fields were removed |
HEXISTS key field |
3 | 1 if the field is present, 0 otherwise |
HLEN key |
2 | the number of fields, 0 for a missing key |
HGETALL key |
2 | a flat array alternating field and value, empty for a missing key |
SADD key member [member ...] |
3 or more | how many members were added; one already present does not count |
SREM key member [member ...] |
3 or more | how many of the named members were removed |
SISMEMBER key member |
3 | 1 if the member is present, 0 otherwise |
SMEMBERS key |
2 | every member as an array, empty for a missing key |
SCARD key |
2 | the number of members, 0 for a missing key |
INCR key |
2 | the new value; a missing key counts from 0, so it answers 1 |
DECR key |
2 | as INCR, one lower |
INCRBY key amount |
3 | the new value; the amount may be negative |
DECRBY key amount |
3 | as INCRBY, subtracting the amount |
Arity follows the Redis convention, where a negative number in the command table means "at least this many arguments", so the table can be checked directly against the reference implementation.
SET options may appear in any order. EX and PX are mutually exclusive, as are NX and XX;
supplying both of a pair, an unknown option, or a non-positive expiry is a syntax error rather than
a silently ignored token.
An integer, whether stored in a string or typed as an argument, is an optional minus sign followed by
digits with no leading zero. +5, 007, -0, 5, and 1.5 are not integers, and a value or amount
outside 64 bits is refused rather than clipped. A refused INCR leaves the key exactly as it was.
A virtual thread per connection, not an event loop. Redis is famously single threaded over an
event loop, which is the standard answer to the cost of an OS thread per client. Virtual threads
remove that cost, so Slate takes the plainer route: ClientHandler reads a command, runs it, and
writes the reply in a straight line, with no callbacks and no explicit state machine. When a read
parks, the runtime unmounts the carrier thread, so idle connections cost close to nothing. The
tradeoff is real, though, and it is the interesting part: commands now run concurrently, so the
keyspace has to be safe for concurrent access instead of implicitly serialised by a single thread.
Bytes, not strings. Redis keys and values are binary safe, so SET k "\xff\x00" has to survive
a round trip untouched. Bulk strings therefore carry byte[], and Key overrides equals and
hashCode over the array contents so it can be used as a map key at all. Where bytes genuinely have
to be read as text, such as a command name, the bridge is ISO-8859-1, which maps bytes 0x00
through 0xFF onto the first 256 code points one for one and so cannot lose information.
The length prefix is authoritative. A bulk string is read by consuming exactly the number of
bytes its header declares. Scanning ahead for the next CRLF looks equivalent and passes casual
testing, then silently truncates the first value that happens to contain one.
Pipelining decides when to flush. A client that pipelines sends a batch of commands before
reading any reply. Flushing after every command would put each reply in its own packet, so
ClientHandler holds the buffer while more input is already available and flushes once the batch
drains.
A framing error ends the connection. Once the byte stream stops making sense there is no safe place to resume reading, because the parser cannot know where the next command starts. Slate reports the error and hangs up, which is what Redis does. An unknown command or a bad argument count is a different matter: those are answered with an error and the connection carries on.
Error text is neutralised on the way out. A status line ends at the first CRLF, and the
"unknown command" error contains a name the client chose. Without stripping terminators from that
text, a client could splice a second, forged reply into the stream. RespWriterTest covers it.
The reply switch has no default branch. RespWriter.write is exhaustive over the sealed
RespValue hierarchy, so adding a RESP type turns every place that has not handled it into a
compile error rather than a runtime surprise.
Expiry is lazy and active, and the clock is a dependency. Slate forgets a key two ways, because either alone is inadequate. Lazily, on read: any read touching a key past its deadline removes it, so a client never sees an expired value and the check costs nothing when it is not needed. That leaks, though, because a key written and then never read again is never looked at, which is exactly how session tokens and cache entries behave. So there is also an active cycle: sample keys that carry deadlines, drop the expired ones, and go round again while the expired share stays high, which makes the work proportional to how much there is to reclaim rather than to the size of the keyspace. Keys with deadlines are tracked in a separate set, so a keyspace of a million permanent keys and a hundred expiring ones samples the hundred instead of hunting through the million.
Expiry has no timing in its tests. The store takes its clock as a Supplier<Instant> and the
sweeper's runCycle() does a whole cycle synchronously, so a test steps time forward by days and
asserts exact reclaim counts. Scheduling is a thin layer on top rather than something an assertion
has to race. TTL likewise answers from a single atomic reading of the store, so a key cannot expire
in the gap between "does it have a deadline" and "what is the deadline".
A list is a ring buffer. The list commands work at both ends and also address elements by
position, and no collection in the JDK is cheap at both: ArrayList shifts everything on a head
insert, ArrayDeque has no indexed access, and LinkedList walks the chain to index. A growable
ring buffer has constant-time ends and constant-time positions, with resizing that amortises to
constant. ListValue is not thread safe on purpose. It is only reached through the store, which holds
the key's lock for the whole operation, so a second lock inside it would add cost without adding a
guarantee.
The type is checked inside the lock. Checking a key's type before running the command would
leave a gap in which another client could replace the value with a different type. The store checks
inside the atomic step instead, and since that can only refuse by unwinding, WrongTypeException is
turned into the WRONGTYPE reply at the single place commands are dispatched. One catch site means a
command added later cannot forget it.
A count changes the shape of the reply. LPOP key answers with a bulk string and LPOP key 1
answers with an array, even though both pop one element. A client that passes a count is asking for
a collection, so reading the reply never depends on how many elements happened to be there.
A hash is a linked map, so its order is stable. Looking a field up by name is all the commands
need, so any map would do, but HGETALL has to answer in some order and a plain HashMap would
produce whatever the bucket layout gave. HashValue is a LinkedHashMap, which replies in the order
fields were first added. That is what Redis does for the small hashes that make up nearly all real
ones, down to the details: overwriting a field keeps its place, and a field deleted and added again
goes to the end. The price is a pointer pair per entry, and the return is replies a test can assert
on whole instead of sorting first.
HSET counts what it created, and arity cannot say "pairs". The reply is the number of fields
that did not exist before, so overwriting one answers 0 and a field named twice in one command
counts once. The command table can say "at least four arguments" but not "an even number", so the
pairing is checked in the handler, and a trailing field with no value is a wrong-argument-count error
rather than a field stored with an empty value.
A hash can be drained and recreated under a writer's feet. Deleting the last field removes the
key, as with lists, which opens a race that strings never had: one client drains the hash, the store
drops the key, and a second client's write lands in an object nothing can reach any more. Creating
the hash, mutating it and removing it when empty all happen inside the one compute, so that cannot
occur. It is also tested rather than argued: eight threads add and delete their own field on one
shared key thousands of times, each reading back what it just wrote. Replacing the locked path with a
check-then-act version makes that test fail, which is how it was confirmed to be able to fail at all.
A set is a linked hash set, and its order is a courtesy. SMEMBERS has to list the members in
some order, and a plain HashSet would use whatever the bucket layout gave, which shifts as the set
grows and differs between runs for the same input. Redis promises no order here and a client should not
rely on one. SetValue is a LinkedHashSet anyway, so members come back in the order they were first
added: adding a member that is already present leaves it where it was, and one removed and added again
goes to the end. It costs a pointer pair per member and makes every reply reproducible, which lets a
test assert on a whole SMEMBERS reply instead of sorting it first.
SADD and SREM count what changed, and the count has to hold under contention. SADD answers
with how many members were new, so re-adding answers 0 and a member named twice in one call counts
once. A count like that is only meaningful if each member is new to exactly one caller, so a test has
eight threads add the same two thousand members and checks that the reported counts sum to exactly two
thousand. A check-then-add that two threads could both pass reports some member as new twice, and it did
when the locked path was swapped for one. SMEMBERS is one snapshot as well: it copies inside the key's
lock, and a test has a writer add and remove a block of 64 members per call while readers check that
they only ever see none of the block or all of it. A version of SMEMBERS that read outside the lock
failed that test every run, with a ConcurrentModificationException.
A counter is a read-modify-write, and it keeps the deadline. INCR reads a number, adds to it
and writes it back, and two clients doing that at once would count once if the three steps were
separate. It runs inside one compute, the same per-key lock the other types use, but not through
the shared helper: a StringValue is immutable, so the new number has to be a new entry, and building
the entry is where the deadline gets decided. A live key's deadline is carried across, so SET hits 0 EX 60 followed by INCR hits is a sixty second window and not a permanent counter. A key that does
not exist, or whose deadline has already passed, starts from zero with no deadline at all, because an
expired key is absent and nothing of it should leak into the new one. A test has eight threads ask for
the next number sixteen thousand times between them and checks that no two were told the same one, and
a second has increments and decrements race and checks they cancel to exactly zero. Reading the entry
before taking the lock failed both, and the server-level test too, on each of five runs.
One definition of an integer. Long.parseLong is the obvious tool and accepts +5, 007, and
digits from other scripts, none of which Redis treats as an integer. It would also let INCR rewrite
a string the client stored as something else. Int64 accepts one form and reads bytes rather than
decoded text. The same parser reads a stored counter and every integer argument, so LINDEX k +1 and
SET k v EX +10 are now refused where they used to be accepted. That is a deliberate change to
existing commands, made so the server does not hold two opinions about what a number is. The amount
is read before the key is touched, so INCRBY list abc is "not an integer" and not WRONGTYPE.
Overflow is refused, and one amount cannot be negated. A sum that leaves 64 bits answers
increment or decrement would overflow and the counter keeps its value and its deadline, where
wrapping would turn the maximum into the minimum without a word. DECRBY is an increment by the
negated amount, and the most negative long has no positive counterpart: negated, it is itself, so
DECRBY k -9223372036854775808 would add instead of subtract. That amount is refused before any
arithmetic with decrement would overflow. With the guard removed, the command answered with the
minimum value instead, and the test for it fails.
mvn test
255 tests across ten classes:
RespReaderTestdrives the parser from byte arrays: both encodings, payloads containingCRLFandNUL, truncated input, bad markers, unparseable lengths, and element counts large enough to exhaust memory.RespWriterTestcompares serialised output against the exact wire bytes, including the difference between a null and an empty bulk string, and byte-counted rather than character-counted lengths.CommandRegistryTestcovers each command, case-insensitive names, arity errors, unknown commands, theSEToptions, the reply conventions forTTL,PTTL, andPERSIST, the hash family: created-field counts, unpairedHSETarguments, binary-safe fields, andWRONGTYPEin both directions, the set family: added-member counts, repeated and empty members, a drained set taking its key with it, andWRONGTYPEagainst strings, lists, and hashes, and the counters: creation at 1, steps of either sign, a deadline that survives, a stored value or an amount that is not an integer, overflow at both ends,DECRBYof the most negative amount, the amount being read before the key, andWRONGTYPEagainst every other type.KeyValueStoreTestdrives expiry against a clock it controls, so deadlines, lazy sweeping, and theNX/XXpreconditions are asserted at the exact second they take effect without sleeping. It also holds the concurrency tests for hashes and sets: concurrent writers to one key lose nothing, a write is never lost into a value another client has just drained, each member added by competing threads is reported as new exactly once, and anSMEMBERSsnapshot never shows half of anSADD. The counters get the same treatment against the clock: a deadline kept across counting, an expired key starting over from zero, refusals that leave value and deadline untouched, and eight threads incrementing one key without losing a count or being told the same number twice.Int64Testdrives the integer grammar directly: the exact ends of the 64-bit range and one step past each, the formsLong.parseLongaccepts and Redis does not, bytes outside ASCII that are never digits, and a round trip through every digit length.ListValueTestexercises the ring buffer directly: both ends, positional access, and growth past the initial capacity with the order intact.HashValueTestexercises the map behind a hash directly: whether a put created the field, where overwritten and re-added fields sit in the order, lookup by contents, and that a snapshot does not change when the hash does.SetValueTestdoes the same for the set behind a set value: whether an add created the member, where a re-added or removed-and-added member sits in the order, matching members by contents including the empty one, and that a snapshot does not change when the set does.ExpirySweeperTestruns the active cycle synchronously: that a key nobody reads is still reclaimed, that permanent keys are never sampled, that the cycle repeats while the expired share is high and stops when it is not, that its round and time ceilings hold, and that a key the lazy path already took is not counted twice.SlateServerTeststarts a real server on an ephemeral port and talks to it over a socket, so the protocol and the threading are exercised together. It includes a pipelined batch, a binary-safe round trip, the hang-up after a framing error, 200 concurrent clients each verifying its own key, a hash with CRLF and NUL in both field and value read back byte for byte, a set whose members, counts, and removal of the last member are checked reply by reply, plus a member holding CRLF and NUL, and the counters: each reply and refusal on the wire, a pipelined run answered in order, and fifty clients pipelining twentyINCRs each at one key without losing a count.
The test client returns the raw bytes of each reply rather than a parsed object, so a framing bug surfaces as a failed assertion instead of being hidden by a lenient parser shared with the server.
Slate binds the loopback address only. There is no authentication and no restriction on which commands a client may run, so anything that can reach the port can read and overwrite the entire keyspace. Reachable from this machine alone is the only safe default at this stage. Do not move it onto a routable interface before there is an auth layer.
Each phase is a self-contained slice that leaves the build green.
- Done. RESP2 codec, virtual-thread server,
PINGECHOSETGETDELEXISTS. - Done. Expiry.
SETwithEX/PX/NX/XX,TTL,PTTL,PERSIST, and both halves of how Redis forgets a key: lazily on read, and on a background sampling cycle for the keys nobody reads. - More types. Strings, lists, hashes and sets are done, with
TYPEandWRONGTYPEhandling, and so are the integer countersINCR/DECR/INCRBY/DECRBY. The list commands that rewrite a list in place (LTRIM,LINSERT,LREM) are next, then sorted sets. This is where a singleConcurrentHashMapstops being enough and multi-key commands need a real concurrency story. - Persistence. A snapshot file first, then an append-only log with selectable fsync policies, and a restart that replays it.
- Pub/sub and transactions.
SUBSCRIBE,PUBLISH,MULTI,EXEC,DISCARD,WATCH. - Replication.
REPLICAOF, a full sync followed by a live command stream to the replica. - Proving it. Throughput and latency measured against real Redis with
redis-benchmark, plus a harness that kills the server mid-write and checks that nothing already acknowledged was lost.