Distributed System Lock Implementation using Redis and JAVA

The purpose of a lock is to ensure that among several application nodes that might try to do the same piece of work, only one actually does it (at least only one at a time).

Photo by Emile Perron on Unsplash

What we will learn here

  1. Create a simple wallet backend with buggy architecture and code
  2. Create the Race condition and identify the problem
  3. Solve the problem using new architecture and implementation
  4. Share the codebase with file descriptions
Application general architecture

Wallet logics

  1. Concurrent send money not possible for the same sender
  2. For concurrent request, first request will execute and the second one will get an exception
Implementation algorithm and flowchart
Step 2 : We are checking is sender has pending fund transfer or previous fund transfer is running using sender walletNo ? If running the throwing with proper error message. 
Step 4 & 5 : Here fetching some data from transactional database for data and limit validation. After that it is making sender account busy so that same sender may not come to do fund transfer again in this moment.
Step 6 & 7: In this stage it is building some database objects and saving in database.
This architecture is looking good and it’s implementation is easy.

Code for application service layer

Here, Redis key is like TRANSACTION-100010

public String set(final String key, final String value, final String nxxx, final String expx,
final int time)

Step 2:
In this step, we are trying to acquire the lock. If we failed then we will throw an exception. Here failed means, this sender is already making transactions in another node. If success then we will complete the transaction and finally we will release this this lock.

Code Description

acquireLock: It will try to acquire the lock for provided key. It will return true if acquire done otherwise false. If the key already exists it can’t acquire again until release.
releaseLock: It will release the lock for provided key

Swagger Url List

Back-end developer, Spring, JAVA, Distributed system, AWS, Google Cloud, Docker, CD/CI, Kubernetes, databases. https://www.linkedin.com/in/sajedulkarim/

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store