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.


This content originally appeared on DEV Community and was authored by Sibelius Seraphini

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: () => {},
    };
  }
};

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) };
  }

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


This content originally appeared on DEV Community and was authored by Sibelius Seraphini


Print Share Comment Cite Upload Translate Updates
APA

Sibelius Seraphini | Sciencx (2024-06-19T12:14:24+00:00) A simple distributed lock implementation using Redis. Retrieved from https://www.scien.cx/2024/06/19/a-simple-distributed-lock-implementation-using-redis/

MLA
" » A simple distributed lock implementation using Redis." Sibelius Seraphini | Sciencx - Wednesday June 19, 2024, https://www.scien.cx/2024/06/19/a-simple-distributed-lock-implementation-using-redis/
HARVARD
Sibelius Seraphini | Sciencx Wednesday June 19, 2024 » A simple distributed lock implementation using Redis., viewed ,<https://www.scien.cx/2024/06/19/a-simple-distributed-lock-implementation-using-redis/>
VANCOUVER
Sibelius Seraphini | Sciencx - » A simple distributed lock implementation using Redis. [Internet]. [Accessed ]. Available from: https://www.scien.cx/2024/06/19/a-simple-distributed-lock-implementation-using-redis/
CHICAGO
" » A simple distributed lock implementation using Redis." Sibelius Seraphini | Sciencx - Accessed . https://www.scien.cx/2024/06/19/a-simple-distributed-lock-implementation-using-redis/
IEEE
" » A simple distributed lock implementation using Redis." Sibelius Seraphini | Sciencx [Online]. Available: https://www.scien.cx/2024/06/19/a-simple-distributed-lock-implementation-using-redis/. [Accessed: ]
rf:citation
» A simple distributed lock implementation using Redis | Sibelius Seraphini | Sciencx | https://www.scien.cx/2024/06/19/a-simple-distributed-lock-implementation-using-redis/ |

Please log in to upload a file.




There are no updates yet.
Click the Upload button above to add an update.

You must be logged in to translate posts. Please log in or register.