I'm using ElastiCache for Redis. Why are my Redis client read requests always read from or redirected to the primary node of a shard?

3 minute read
0

I'm using Amazon ElastiCache for Redis. Why are my Redis client read requests always read from or redirected to the primary node of a shard?

Resolution

Any node in a Redis cluster can receive queries from Redis clients. When a client sends a read/write query to a replica node, the node analyzes the request to confirm whether it is a single key or multi-key operation that belongs to the same hash slot of the shard. The default behavior of replica nodes in cluster-mode enabled clusters is to redirect all client read/write requests to an authoritative primary node of the shard that belongs to the key's hash slot. The replica node serves the read request only if that shard belongs to the hash slot and a readonly command is initiated by the client. This means that the replica node processes the request only if readonly is issued by the client before the request. Otherwise, the request is redirected to the primary node of the shard that the hash slot belongs to.

Example

1.    Log in to your cluster to set a key.

172.31.21.72:6379> set key8 "This is testing for readonly"
-> Redirected to slot [13004] located at 172.31.21.72:6379
OK
172.31.21.72:6379>

2.    Connect to a replica node.

In the following example, the readonly command isn't sent, and the request is redirected to a primary node.

172.31.30.175:6379> info replication
 # Replication
 role:slave
 master_host:172.31.21.72
 master_port:6379
 master_link_status:up
 172.31.30.175:637> CLUSTER KEYSLOT key8
 (integer) 13004 
 172.31.30.175:637> get key8
 (error) MOVED 13004 172.31.21.72:6379
 172.31.30.175:637> get key8
 -> Redirected to slot [13004] located at 172.31.21.72:6379
 "This is testing for readonly"
 172.31.21.72:6379>

Note: The MOVED error shown in the preceding example occurs when the Redis cluster client isn't cluster aware and can't handle redirection requests to the primary node. For more information about the MOVED error, refer to Redis cluster specification - Redirection and resharding on the Redis.io website.

In the following example, the readonly command is sent first, so the replica node processes the request instead of redirecting it to a primary node.

172.31.30.175:6379> readonly
OK
172.31.30.175:6379> get key8
"This is testing for readonly"
172.31.30.175:6379>

The readonly command needs to be issued when the client connects to a node for the first time. The command is active only until the client reads keys from the same node. If the client connects to another replica node in the same or different shard, then you might need to issue a new readonly command.


AWS OFFICIAL
AWS OFFICIALUpdated 3 years ago