Member-only story

How Redis achieve concurrent operation with single thread

Namrata
3 min readJul 27, 2024

--

Redis uses I/O multiplexing to handle multiple network connections simultaneously with high efficiency. This is crucial for a high-performance database like Redis, which needs to manage many client connections concurrently without significant performance degradation.

Event Loop

Redis operates on a single-threaded event loop. This means that it uses a single thread to handle all incoming requests and outgoing responses. The event loop continuously checks for events (such as new client connections, incoming data, or completed commands) and processes them one by one.

I/O Multiplexing Mechanism

Redis uses I/O multiplexing to monitor multiple file descriptors (which represent network sockets) to see if they are ready for I/O operations (like reading or writing). This is done using system calls provided by the operating system. The specific system call used depends on the platform:

  • epoll on Linux
  • kqueue on macOS and FreeBSD
  • select on older systems or as a fallback

These system calls allow Redis to efficiently monitor many file descriptors at once without having to block on each one individually.

Non-blocking I/O

Redis uses non-blocking I/O operations. When a file descriptor is ready for reading or writing, Redis performs the I/O operation without blocking the event loop. This ensures that the event loop can continue to process other events without waiting for I/O operations to complete.

When the event loop detects that a file descriptor is ready for an I/O operation, it invokes the appropriate event handler. For example:

  • If a new client connection is ready to be accepted, Redis will accept the connection and add the new client’s socket to the list of monitored file descriptors.
  • If data is available to be read from a client, Redis will read the data, process the command, and prepare a response.

--

--

Namrata
Namrata

Written by Namrata

Engineering @Microsoft A software developer writing her daily bits . https://www.linkedin.com/in/namrataagarwal5/

No responses yet

Write a response