Implementing Redis in Java using RESP and virtual threads
Building a Redis-compatible server in Java: the RESP protocol, sealed types, expiry, blocking lists and streams.
Redis is one of those tools I used for years without knowing how it worked. Then I worked through the "Build Your Own Redis" challenge on CodeCrafters and implemented a Redis-compatible server in Java. It speaks the real Redis protocol, so the official redis-cli can talk to it.
It supports PING, ECHO, SET with expiry, GET, lists (RPUSH, LPUSH, LRANGE, LLEN, LPOP, blocking BLPOP) and streams (XADD, XRANGE, XREAD). Here's how it fits together.
The pipeline
Every request goes through the same four steps:
Server server = new Server(6379, (in, out) -> {
RespValue request = decoder.decode(in); // bytes -> RESP value
RedisCommand command = parser.parse(request); // RESP value -> typed command
RespValue response = handler.execute(command);// run it against the store
encoder.encode(response, out); // RESP value -> bytes
out.flush();
});Keeping these separate made each piece easy to test and easy to change.
Speaking RESP
Redis clients talk RESP (REdis Serialization Protocol). It is a simple, line-based format where the first byte says what comes next:
+OK\r\nis a simple string-ERR message\r\nis an error:42\r\nis an integer$5\r\nhello\r\nis a bulk string (length-prefixed, so it's binary safe)*2\r\n...is an array of two more values
A command like SET name aryan arrives as an array of bulk strings:
*3\r\n$3\r\nSET\r\n$4\r\nname\r\n$5\r\naryan\r\nI modeled RESP values with a sealed interface, which modern Java makes very pleasant:
public sealed interface RespValue permits
IntegerValue, SimpleString, SimpleError, BulkString, ArrayValue, NullValue {}Because the hierarchy is sealed, the encoder can use a pattern-matching switch and the compiler checks that every type is handled:
public void encode(RespValue value, OutputStream out) throws IOException {
switch (value) {
case SimpleString v -> encodeSimpleString(v, out);
case SimpleError v -> encodeSimpleError(v, out);
case BulkString v -> encodeBulkString(v, out);
case IntegerValue v -> encodeIntegerValue(v, out);
case ArrayValue v -> encodeArrayValue(v, out);
default -> throw new UnsupportedOperationException();
}
}The decoder is recursive. Reading an array means reading its length, then calling decode that many times. Bulk strings use readNBytes(length) instead of scanning for \r\n, which is what makes them safe for arbitrary binary data.
Commands as records
Once decoded, commands become typed records. Again a sealed interface:
public sealed interface RedisCommand permits
PingCommand, EchoCommand, GetCommand, SetCommand,
RPushCommand, LPushCommand, LRangeCommand, LLenCommand, LPopCommand, BLPopCommand,
TypeCommand, XAddCommand, XRangeCommand, XReadCommand {}
public record BLPopCommand(String key, long timeoutMs) implements RedisCommand {}The parser does all of the validation (argument counts, numbers, options like PX), so the handler only sees well-formed commands. Adding a command means adding a record, and the compiler points at every switch that needs a new case.
The store
The data lives in a ConcurrentHashMap<String, StoredValue>, where a stored value carries an optional expiry time:
public record StoredValue(RedisValue value, Long expiresAt) {
public boolean isExpired() {
return expiresAt != null && System.currentTimeMillis() >= expiresAt;
}
}Expiry is lazy: nothing deletes keys on a timer. When a key is read and it has expired, it is removed and treated as missing. It's simple and correct from the client's point of view. Real Redis adds a second, active strategy that samples random keys with a TTL and evicts expired ones, so memory doesn't fill with keys nobody reads again.
Lists and blocking pops
Lists are Deque<byte[]>. The interesting command is BLPOP key timeout: pop from the list, or wait until something is pushed or the timeout passes.
I implemented it with Java's oldest concurrency tool, wait and notifyAll on the store's monitor:
public synchronized Optional<byte[]> blpop(String key, long timeoutMs) throws InterruptedException {
long deadline = System.nanoTime() + TimeUnit.MILLISECONDS.toNanos(timeoutMs);
while (true) {
// ... if the list has an element, pop it and return
if (timeoutMs == 0) wait(); // block forever
else {
long remaining = deadline - System.nanoTime();
if (remaining <= 0) return Optional.empty();
wait(TimeUnit.NANOSECONDS.toMillis(remaining));
}
}
}RPUSH and LPUSH call notifyAll() after adding elements, which wakes every waiting client to re-check its list. The while loop matters: a woken thread must check again, because another client may have taken the element first (and spurious wakeups are allowed).
Streams
Streams were the most fun. A stream is an append-only log where every entry has an ID like 1526919030474-0 (milliseconds, then a sequence number). I store entries in a ConcurrentSkipListMap, which keeps them sorted and makes XRANGE a subMap call.
XADD supports three ID styles:
An explicit ID, which must be greater than the last one.
1526919030474-*, where the server picks the next sequence for that millisecond.*, where the server uses the current time and picks the sequence.
Concurrency model
Each client connection runs on its own virtual thread. The Connection loop just calls the request handler until the client disconnects:
try (var in = new BufferedInputStream(socket.getInputStream());
var out = new BufferedOutputStream(socket.getOutputStream())) {
while (true) eventHandlers.onMessage().handle(in, out);
}Real Redis is single threaded with an event loop, which is why its commands are atomic for free. With many threads I have to earn atomicity myself, which is where the synchronized methods and compute calls come in.
What I'd improve
Stream IDs should not be strings. In a skip list of strings,
"10-0"sorts before"9-0". A smallrecord StreamId(long ms, long seq) implements Comparable<StreamId>fixes ordering and makes ID validation simpler.One big lock is simple, not fast. Synchronizing on the whole store makes
BLPOPeasy to reason about but serializes all list writes. A condition per key would let unrelated lists proceed in parallel.Pipelining. Clients can send many commands without waiting for replies. Buffering responses and flushing once per batch would cut syscalls a lot.
Persistence. RDB snapshots or an append-only file are the obvious next stage.
Building it taught me why Redis made the choices it did. Single-threaded execution, a dead simple protocol and lazy plus active expiry are all trade-offs I ran into myself, and each one makes more sense now.
Discussion(0)
Loading comments…