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

Image of Docusign

🛠️ Bring your solution into Docusign. Reach over 1.6M customers.

Docusign is now extensible. Overcome challenges with disconnected products and inaccessible data by bringing your solutions into Docusign and publishing to 1.6M customers in the App Center.

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

Discover a treasure trove of wisdom within this insightful piece, highly respected in the nurturing DEV Community enviroment. Developers, whether novice or expert, are encouraged to participate and add to our shared knowledge basin.

A simple "thank you" can illuminate someone's day. Express your appreciation in the comments section!

On DEV, sharing ideas smoothens our journey and strengthens our community ties. Learn something useful? Offering a quick thanks to the author is deeply appreciated.

Okay