Dev Learning Lab

The labs on this site need JavaScript to run. The same content is written out below.

Learn › Database › Scaling and distribution

Redis single-threaded execution

If one command is slow, everyone waits

Why it exists — If frequently read values are fetched from the database every time, the disk and query costs add up, and if each application server keeps them in its own memory, the servers see different values when there are several of them. Redis is an in-memory store that several servers connect to together over the network. It returns a value directly from a single key, which is lighter than a database query, and lets all servers see the same value.

Where it's used today — It is commonly used as a cache that keeps product information or query results for a few minutes to reduce database queries, as a session store where several servers see the same login information, and as a counter that counts views or likes with INCR. Original data that must not be lost and searches that mix several conditions stay in the relational database, and Redis usually holds values that can be created again.

Redis runs commands one at a time, in order, on a single thread. That is why each command runs without anything cutting in, even without locks, but if one command takes a long time, every command behind it has to wait in line.

Checked against real execution · The eight combinations were run five times each on Redis 8.10.2, and the execution order (SLOWLOG), the waiting, and the INCR values were compared; the times on the screen are measured values from one of those runs. The commands sent by the Java code on the screen were checked by running it with Spring Data Redis 4.1.1

Concepts in this lab

Redis
A key-value store that keeps data in memory. It provides not only strings but also data structures such as lists, hashes, sets, and sorted sets. It is very fast because it works in memory, and it is used for caches, session stores, distributed locks, leaderboards, rate limiting, and more. It runs commands one after another on a single thread.
Cache
Storing frequently used data or computed results ahead of time in a place that can be accessed quickly, and reusing them. Responses get faster and the load on the source drops, because the source (usually a database) is not queried every time. In return, you must manage the problem of stale values that remain when the source changes.
Atomicity and CAS (compare-and-swap)
Where it's used today — The request counter built with AtomicInteger and AtomicLong, and ConcurrentHashMap putting the first value into an empty slot, use CAS. The version comparison in JPA optimistic locking (UPDATE … WHERE version = ?) uses the same idea in the database.
Atomicity is the property that an operation made of several steps runs as one, with no gap for anything to cut in. CAS (compare-and-swap) performs "change to the new value only if the current value equals the value I read" as a single atomic operation, which makes safe updates possible without locks. AtomicInteger and similar classes use it.
Event loop
Where it's used today — Netty, the default server of WebFlux, and Node.js and Redis work with this structure. If you must make a blocking call in an event loop, you hand it off to a separate thread, such as Reactor's Schedulers.boundedElastic().
This is a structure in which a small number of threads detect the I/O events that occur on many connections and process them in turn. There is no thread per connection, so one thread takes care of many connections. If you run a long task or a blocking call on such a thread, processing stops for every connection that the thread is responsible for.

Try these

Running with the default settings

  1. Redis receives the commands of several clients, puts them in a single line, and one thread runs them one by one from the front. The next command starts only after the current one has finished. The times below were measured on a real Redis.
  2. Service A GET product:1: The reply came 0.146ms after sending. It ran on the server for 0.004ms.
  3. Service B GET product:2: The reply came 0.123ms after sending. It ran on the server for 0.001ms.
  4. Admin KEYS user:*: It ran on the server for 242.2ms. While this command runs, Redis cannot run any other command. The sender needed 553.9ms to receive the whole reply.
  5. Service A GET product:3: The reply came 240.5ms after sending. It ran on the server for only 0.003ms, and the rest is the time it waited for the preceding KEYS user:* command to finish.
  6. Service B SET cart:9 v: The reply came 240.3ms after sending. It ran on the server for only 0.005ms, and the rest is the time it waited for the preceding KEYS user:* command to finish.
  7. Service A GET product:4: The reply came 0.147ms after sending. It ran on the server for 0.001ms.

Result of this run

Code

// Only the needed parts are kept. redis is the StringRedisTemplate from Spring

// Services A and B: ordinary cache lookups
String v = redis.opsForValue().get("product:1");

// Admin script
Set<String> keys = redis.keys("user:*");          // scans all the keys at once

Assumptions of this model

The times on the screen are not examples but values measured on a real Redis 8.10.2. Keys user:1 to user:1000000 and a list events of 500,000 elements were put into a Redis in a Docker container (default settings), and the commands were sent in the order above over three connections (service A, service B, and the admin or batch) from another container on the same Docker network (verify/net/redis_run.js). GET product:3 and SET cart:9 were sent 2ms after the command that cuts in (20ms after for SCAN). "Time to the reply" was measured by the sender, and "time run on the server" and the order of execution are the values recorded in the SLOWLOG of Redis. Each combination was run five times, and the screen shows the values of the run whose longest reply time of services A and B was the middle one (the third) of the five. This verification environment had other jobs running at the same time, so the values varied widely. Over the five runs, KEYS user:* ran on the server for 191 to 393ms, and the GET and SET sent meanwhile waited 189 to 388ms. LRANGE events 0 -1 ran for 20 to 50ms, and the commands sent meanwhile waited 18 to 47ms. SCAN finished in 1,000 calls every time, one call ran for 0.3 to 0.7ms on average (the longest single call was 10.3ms), and the longest reply of a service command during the scan was 0.2 to 2.1ms. With no command cutting in, the service commands got their replies in 0.1 to 0.4ms. In all five runs, GET product:3 and SET cart:9 got no reply before KEYS or LRANGE finished running, and view:1 was exactly 12 after the two INCR commands. The value after two connections sent INCR to the same key 20,000 times each, all at once, was also exactly 40,000. The Java code on the screen was run separately with Spring Data Redis 4.1.1 (Lettuce 7.5.2), and the commands the server received were confirmed to be GET, INCR, KEYS user:*, SCAN 0 MATCH user:* COUNT 1000 (1,000 calls), and LRANGE events 0 -1. The times depend on the data size, the machine, and the load at that moment. Since Redis 6, several threads can be used for network I/O (this run used the default, io-threads 1), but running commands is still done by one thread.

Previous lab: Partitioning · Next lab: NoSQL and the document model

Concepts in this lab

What this lab shows

Settings

Code


      
    

Diagram

Run comparison

Try these