We've all heard that Redis is single-threaded. But if it's single-threaded, how does it handle multiple client connections so efficiently without the need for multiple threads or processes?
Let's talk about I/O multiplexing.
Redis uses I/O multiplexing to handle connections concurrently. Keep in mind this is concurrency and not parallelism. Now, let's say you have established a connection to a Redis server. Redis monitors your socket (via an event loop) to check if there is data to be read from the client or if there is data to be sent to the client.
Since there is an event loop responsible for monitoring client connections, Redis ensures non-blocking I/O. This implies it does not block on a single client to finish its operation (which can be a read or write, i.e., sending data to the client or receiving data from the client).
Unlike traditional databases (e.g., SQL) which use separate threads for each client, Redis doesn't. Despite this, Redis is preferred for caching (although it can be used as a primary database—if you can afford expensive in-memory storage 😅). Redis is renowned for its speed and efficiency.
In my newsletter, <Hello World!>, we'll discuss the implementation details of I/O multiplexing and why, despite this design choice, Redis is so blazingly fast.