Coder's Cat

Why Redis is Single-Threaded

2020-04-06

Redis is designed to run in a single thread, but the performance is excellent, why?

4 reasons for Redis is single-threaded

  • CPU is not bottleneck: All operations of Redis are memory-based, and CPU is not the bottleneck of Redis. In most cases, the bottleneck of Redis is most likely the size of machine memory or network bandwidth. If we want higher performance, with single-threaded Redis, we could use a cluster(multiple processes) solution.
  • Concurrency: Parallelism is not the only strategy to support multiple clients. Redis uses epoll and event-loop to implement a concurrency strategy and save much time without context switching.
  • Easy to implement: Writing a multi-threaded program can be harder. We need to add locks and sync mechanism for threads.
  • Easy to deploy: Single-threaded application could be deployed on any machine having at least a single CPU core.

Concurrency vs. Parallelism

As for the difference between concurrency and parallelism, please refer to this presentation from Rob Pike:

Concurrency vs. Parallelism
Concurrency is about dealing with lots of things at once.
Parallelism is about doing lots of things at once.

Not the same, but related.
Concurrency is about structure; parallelism is about execution.
Concurrency provides a way to structure a solution to solve a problem that may (but not
necessarily) be parallelizable.

We can use an analogy of the restaurant waiter:

What is concurrency

A waiter can provide service to several customers while he can only prepare dishes to only one customer at a time.

Because there will be some intervals between the dishes provided by the kitchen, one waiter could usually handle when the number of customers is less than 5.

What is parallelism

Suppose the kitchen could provide dishes for 20 customers at a time. If the number of customers is too large for one waiter, we need more waiters. In this scenario, multiple waiters are working at the same time; we call it parallelism.

Join my Email List for more insights, It's Free!😋

Tags: Misc