In today’s post, we’ll build a simple key value server; but we’ll do it in an iterative way. We’ll build it up simple
and then add safety, concurrency, and networking as we go.
Implementation
Now we’ll get started with our iterations. The finished code will be available at the end of this post.
Baseline
All of our implementations will deal with a KeyValueStorestruct. This struct will hold all of the variables that
we want to keep track of in our server.
We define data as the in-memory representation of our database. We use String keys and store String values.
Our implementation is very basic. All we’re really doing is shadowing the functionality that HashMap provides.
This is a pretty decent starting point. We can use our KeyValueStore in some basic tests:
Variants
String is pretty limiting to store as far as the value side is concerned. We can upgrade this to specifically use
data types that we will find useful via an enum:
We can swap out the value side of our data member now, too.
The implementation simply swaps the String for Value:
We’re now able to not only store strings. We can store integers, floats, binary, and booleans. This makes our key value
store a lot more versatile.
Thread Safety
We will have multiple threads of execution trying to perform actions on this structure at the same time, so we will
add some thread safety to the process now. Wrapping data in Arc will give us a thread safe, reference counting
pointer. We’re also going to need to lock this data structure for reading and for writing. We can use RwLock to
take care of that for us.
We update our data structure to include these new types:
Now our implementation functions need to change to work with these new structures. We can keep the structure of
functions the same though.
These functions are now safe, which means calling code can be multithreaded and we can guaranteed that our data
structure will be treated consistently.
Error handling
You can see that we’re using unwrap in the implementation functions, which might be ok for tests or short scripts. If
we’re going to expect to run this code in production, we’d be best replacing these with actual error handling counterparts.
In order to do that, we need to define our error domain first. We create an enum called StoreError. As we fill out
our implementation, we’ll run into a number of different error cases. We’ll use StoreError to centralise all of these
errors so we can express them clearly.
We’ve implemented PoisonError for our StoreError because the PoisonError type is an error which can be returned
whenever a lock is acquired. If something goes wrong and we’ve acquired a lock, it’s a PoisonError that’s used.
Our insert, get, and delete methods now need an upgrade. We’ll be returning Result<T, E> values from our
functions now to accomodate potential failures.
We’ve removed the use of unwrap now, swapping out to using the ? operator. This will allow us to actually handle
any failure that is bubbled out of calling code.
Using the File System
We need to be able to persist the state of our key value store out to disk for durability. In order to do this, we need
to keep track of where we’ll write the file. We add a file_path member to our structure:
Starting out this implementation simply, we just write a load and save function that we can call at any time. Before
we do this we need some extra dependencies added for serialisation:
This will allow us to reduce our internal state to JSON.
Loading the database off disk
We need to make sure that a file_path was specified. We read everything off from the file into contents as a big
string. Using serde_json::from_str we can turn that contents into the deserialised representation. From there, we
simply swap out the underlying content.
We’ve got some new errors to deal with here in IoError.
This will be used for our write implementation which looks like this:
The magic here really is the serde_json::to_string taking our internal state and writing it as json.
An example of how this looks is like this:
Networking
Finally, we’ll add some networking to the solution. A really basic network interface will allow remote clients to
perform the get, set, and delete operations for us.
The handle_client function is the heart of the server process, performing the needed processing on incoming requests
and routing them to the database instance:
Out networking “protocol” looks like this:
This is all made possible by the following:
We read in the request data from the client into request. This gets split up on white spaces into parts with command
given the first of these parts. The code is expectingcommand to be either SET, GET, or DEL that is then
handled in the following pattern match.
This function gets mounted onto the server in the main function which now looks like this:
We’re starting our server on port 7878 and handling each connection with our handle_client function.
Running this and giving it a test with telnet gives us the following:
So, it works. It’s crude and needs to be patched to be a little more production ready than this - but this is a start.
Conclusion
In this article, we walked through building a thread-safe, persistent key-value store in Rust. We started with a simple
in-memory implementation and iteratively improved it by:
Adding support for multiple data types using an enum.
Ensuring thread safety with RwLock and Arc.
Replacing unwrap with proper error handling.
Adding file persistence using JSON serialization and deserialization.
Added some basic network access
This provides a solid foundation for a more robust and scalable key-value server. Next steps could include:
Implementing advanced features like snapshots or replication.
Optimizing for performance with tools like async I/O or a custom storage engine.