Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to connect to Amazon MemoryDB for Redis from Node running in EC2/ECS?

Lately, I have struggled to connect to Amazon MemoryDB for Redis (cluster) from a Next.js app running in Amazon ECS!

At first, I thought that my VPC and/or Security Group was misconfigured, but I double-checked, and both the Redis cluster and the Next app were on the same VPC, and the Security Group allows the connections between them; I also checked that the VPC has DNS resolution enabled, and it does!

I finally managed to get it running, so I'm posting my answer here in case someone finds themselves in the same situation.

like image 288
Ahmed Kamal Avatar asked Dec 22 '25 09:12

Ahmed Kamal


1 Answers

I found out that the issue was the way I was trying to connect to the Redis cluster; I'm using ioredis and my code was something like this:

import Redis from "ioredis";

const host = process.env.REDIS_HOST;
const port = +process.env.REDIS_PORT!;

export const redis = new Redis({ host, port });

That setup resulted in Timeout errors!

After some investigation I found that I should use the Cluster constructor from ioredis and not the default Redis constructor! But still, I got an error ClusterAllFailedError: Failed to refresh slots cache.

And finally after further investigation and testing I found the right way to connect to the Redis cluster wich is as follows:

import { Cluster } from "ioredis";

const host = process.env.REDIS_HOST;
const port = +process.env.REDIS_PORT!;

export const redis = new Cluster([{ host, port }], {
  dnsLookup: (address, callback) => callback(null, address),
  redisOptions: {
    tls: {},
  },
});

Where REDIS_HOST is the endpoint of the Redis cluster on AWS and the REDIS_PORT is the cluster port!

Hope that helps you save sometime because I couldn't find this setup documented anywhere!

like image 173
Ahmed Kamal Avatar answered Dec 24 '25 05:12

Ahmed Kamal



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!