DEV Community

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

Posted on

14

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

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay