DEV Community

Cover image for A simple distributed lock implementation using Redis
Sibelius Seraphini for Woovi

Posted on

15

A simple distributed lock implementation using Redis

When you want to make sure only one process modifies a given resource at a time you need a lock.
When you have more than one pod running in production to your server in your Kubernetes, you can't lock only in memory, you need a distributed lock.

Implementation using redlock

import Redis from 'ioredis';
import Redlock from 'redlock';

const redis = new Redis(config.REDIS_HOST);

export const redlock = new Redlock([redis], {
  retryCount: 15,
});

export const lock = async (key: string, duration: number) => {
  try {
    const lockAcquired = await redlock.acquire([key], duration);

    return {
      unlock: async () => {
        try {
          await lockAcquired.release();
        } catch (err) {
        }
      },
    };
  } catch (err) {
    return {
      error: 'Unable to get lock',
      unlock: () => {},
    };
  }
};
Enter fullscreen mode Exit fullscreen mode

Usage

const { error, unlock } = await lock('lockKey');

  // error trying to get
  if (error) {
    return { success: false, error: String(error) };
  }

  try {
    // modify a shared resource

    await unlock();

    return result;
  } catch (err) {
    await unlock();

    return { success: false, error: String(err) };
  }
Enter fullscreen mode Exit fullscreen mode

Use cases

You can use a distributed lock to update the balance of a ledger account.
You can use it to avoid two processes consuming the same API at the same time.

In Conclusion

Distributed locks are one of many possible approaches to handle concurrency to shared resources. You could use a conditional put. Use a queue to process just one event at a time.
Investigate and discover what is the best solution for your specific scenario.


Woovi is an innovative startup revolutionizing the payment landscape. With Woovi, shoppers can enjoy the freedom to pay however they prefer. Our cutting-edge platform provides instant payment solutions, empowering merchants to accept orders and enhance their customer experience seamlessly.

If you're interested in joining our team, we're hiring! Check out our job openings at Woovi Careers.


Photo by Mackenzie Marco on Unsplash

Image of Stellar post

From Hackathon to Funded - Stellar Dev Diaries Ep. 1 🎥

Ever wondered what it takes to go from idea to funding? In episode 1 of the Stellar Dev Diaries, we hear how the Freelii team did just that. Check it out and follow along to see the rest of their dev journey!

Watch the video

Top comments (0)

Jetbrains image

Build Secure, Ship Fast

Discover best practices to secure CI/CD without slowing down your pipeline.

Read more

👋 Kindness is contagious

Dive into this thoughtful article, cherished within the supportive DEV Community. Coders of every background are encouraged to share and grow our collective expertise.

A genuine "thank you" can brighten someone’s day—drop your appreciation in the comments below!

On DEV, sharing knowledge smooths our journey and strengthens our community bonds. Found value here? A quick thank you to the author makes a big difference.

Okay