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

1.1k Views Asked by At

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.

1

There are 1 best solutions below

0
On

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!