Question: How can you read from a replica in a Redis cluster?
Answer
In a Redis cluster, you can read from replicas (previously known as slaves) to distribute the read load and reduce pressure on the master. This is especially helpful when you have read-heavy applications.
To read from a replica, you need to use the READONLY
command. This command modifies the state of the connection so that it is redirected to the closest replica, rather than the master.
However, please note that there's a possibility the data you're reading from the replica may be stale. This is because replication is asynchronous in Redis, meaning there can be a slight delay between when data is written to the master and when it's replicated to its replicas.
Here's an example of how to use the READONLY
command:
import redis # Connect to your Redis cluster r = redis.Redis( host="localhost", port=6379, password=None ) # Enter READONLY mode r.execute_command("READONLY") # Now when you perform read commands, they will be directed to the nearest replica: value = r.get("my_key")
You can return to reading from the master by using the READWRITE
command:
r.execute_command("READWRITE")
Note: The Python redis client has built-in support for executing arbitrary commands with execute_command()
, which allows you to use commands like READONLY
and READWRITE
that aren't explicitly supported by the library.
Was this content helpful?
Other Common Redis Questions (and Answers)
- What is the default port used by Redis?
- How to start Redis server?
- Is Redis persistent?
- How fast is Redis?
- How to install Redis on Mac?
- How to check if Redis is running?
- How to restart Redis?
- Does Redis persist data?
- How to install Redis on Ubuntu?
- How to stop Redis server?
- How to see Redis version?
- Does Redis have tables?
Free System Design on AWS E-Book
Download this early release of O'Reilly's latest cloud infrastructure e-book: System Design on AWS.
Switch & save up to 80%
Dragonfly is fully compatible with the Redis ecosystem and requires no code changes to implement. Instantly experience up to a 25X boost in performance and 80% reduction in cost