Hi, I’m Dung Huynh Duc . Nice to meet you.

About Me

With over a decade of experience under my belt as a full-stack developer, I've had the opportunity to spearhead project teams at tech startups in Vietnam, Thailand, Japan and Singapore. Additionally, I have worked as a freelance engineer for various companies based in Asia Pacific, Europe, and North America.

Presently, I serve the role of a Senior Full Stack Software Engineer at ACX. I am consistently committed to exploring and acquiring knowledge on emerging and popular technologies.

redis
aws
Amazon ElastiCache

#TIL 26 - How to connect to Redis on AWS (Amazon ElastiCache)

blog_hero_#TIL 26 - How to connect to Redis on AWS (Amazon ElastiCache)
import Redis, { RedisOptions } from 'ioredis';

const parseRedisCredentials = (url: string, opts: RedisOptions = {}): RedisOptions => {
	const { port, hostname, password, pathname } = new URL(url);
	const db = pathname.startsWith('/') ? Number(pathname.split('/')[1]) : 0;
	const baseOpts = {
		port: Number(port),
		host: hostname,
		password,
		db,
	};
	if (!url.startsWith('rediss://')) {
		const { tls: _, ...rest } = opts;
		return { ...baseOpts, ...rest };
	}

	return { ...baseOpts, ...opts };
};

export const redisClient = new Redis(
	parseRedisCredentials(process.env.REDIS_CONNECTION ?? 'redis://localhost:6379', {
		lazyConnect: true,
		connectTimeout: 15000,
		retryStrategy: (times) => Math.min(times * 30, 1000),
		reconnectOnError(error) {
			const targetErrors = [/READONLY/, /ETIMEDOUT/];
			logger.warn(`Redis connection error: ${error.message}`, error);
			return targetErrors.some((targetError) => targetError.test(error.message));
		},
	}),
);