AWS ElastiCache: How to Fix Connection Timeout in Redis?

approximately 2 minutes of reading

Creation of a Redis instance under ElastiCache is not a hard task. However, if you want to establish a fluent communication between caching layer and your EC2 instance, you may encounter a tricky situation where pinging Redis once you are ssh'ed to your instance, results in a frustrating timeout error. This article sheds some light on what could be one of potencial culprits of such a situation.

Assumptions

Let's say we have created cache.t2.small Redis instance under ElastiCache. The status indicates that it is available. As a result, sample endpoint is ready for connection.

portal-test.abcdef.ab.0001.abcd1.cache.amazonaws.com
Pinging Redis from EC2

We have ssh'ed to our EC2 instance via ubuntu@ip-172-xx-xx-xx. Now we want to simply ping our caching layer to see if a connection can be established. We do this by typing:

redis-cli -h portal-test.abcdef.ab.0001.abcd1.cache.amazonaws.com -p 6379 ping

Accodring to the official Redis documentation, the ping command:

Returns PONG if no argument is provided, otherwise return a copy of the argument as a bulk. This command is useful for:

1. Testing whether a connection is still alive.
2. Verifying the server's ability to serve data - an error is returned when this isn't the case (e.g., during load from persistence or accessing a stale replica).
3. Measuring latency.

PONG is exactly what we expect, but instead we see:

Could not connect to Redis at portal-test.abcdef.ab.0001.abcd1.cache.amazonaws.com:6379: Connection timed out
Culprit

The issue was caused by a mismatch of private IP addresses between EC2 instance and Redis. Accodring to the linked RFC 1918 (Address Allocation for Private Internets):

The Internet Assigned Numbers Authority (IANA) has reserved the following three blocks of the IP address space for private internets:

10.0.0.0 - 10.255.255.255 (10/8 prefix)
172.16.0.0 - 172.31.255.255 (172.16/12 prefix)
192.168.0.0 - 192.168.255.255 (192.168/16 prefix)

I did not notice that my EC2 instance had an IP address from the 20-bit block (172.xx.xx.xx), while Redis had na IP address from the 24-bit block (10.xx.xx.xx). This is what has caused the timeout in my particular case.

Solution

When you create Redis, simply assign it to the same VPC as your existing EC2 instance where your application lives. Also reuse the same security group where you open port 6379 (assuming you did not change the default port during creation).

Now ssh into your EC2 instance and from within type:

redis-cli -h portal-test.abcdef.ab.0001.abcd1.cache.amazonaws.com -p 6379 ping

If you get PONG, this indicates a successful connection being established.

I hope you find this article useful.


Words: 421
Published in: Amazon Web Services
Last Revision: April 20, 2023

Related Articles   📚