Redis distributed lock using AWS Lambda, Node.js & SQL

Suman Dev
2 min readNov 15, 2020

Redis distributed locks are a very useful primitive in many environments where different processes must operate with shared resources in a mutually exclusive way.

In this story, I'll be focusing on configuring redlock in AWS Lambda so that you can implement Redis distributed lock in your serverless app.

First, you need to make a brief knowledge about how distributed lock works.

  1. You can refer the official document in redis website.

2. If you want to go deep in this, then you must refer to Martin Kleppmann blog.

3. If you are in a hurry, then you can refer to this short blog.

After getting an idea about this, next step was the implementation.

In my scenario, I have already created a redis in AWS ElastiCache, so that i can use this url and port for creating redis client.

First you need to install redlock and redis module in AWS Lambda.

var redis = require('redis');var Redlock = require('redlock');const redisOptions = {host: "url",port: "port"};var client = redis.createClient(redisOptions);client.on('connect', function (result) {console.log("connected");});async () => {try {var sql = "update query";var ttl = 4000; //msvar redlock = new Redlock([client],{driftFactor: 0.01,retryCount: 10,retryDelay: 200,});await redlock.lock(sql, ttl).then(function (lock) {// do sql updatesreturn lock.unlock().catch(function (err) {console.error(err);});});} catch (err) {console.log(err);}};

I have applied lock on sql queries and it can be unlocked using lock.unlock().

This sample code is based on my requirement. You can modify according to your scenario.

--

--