Are your DBs really consistent ?

How to use Distributed Locking with real life examples

🔓Distributed Locking

Wake Up to the Reality of Production Environments

  • "No better place than 127.0.0.1" is a phrase that holds true when working locally, but production environments are a different story. Issues can arise when multiple instances of your application are running.

The Problem with Concurrent Requests

  • Imagine a scenario where you need to handle a payment process:

    1. Fetch user data from the DB.

    2. Check if the user is free or paid.

    3. Update the user's status in the DB if not paid.

    4. Send a response based on the user's payment status.

  • Issue: If two requests come in simultaneously—one to cancel the payment and another to mark it as paid—the system could incorrectly allow a user access to your product without payment.

concurrent request to cancel the payment

Locks to the Rescue

  • Locks ensure that only one process can access a critical section of code at a time.

    • Steps:

      1. Acquire the lock.

      2. Execute the transaction.

      3. Release the lock.

The Problem with In-Memory Locks

  • In-memory locks are limited to a single instance of your application. They don't work well in a distributed environment where multiple instances might be running.

multiple instances of our service are running

Introduction to Distributed Locking

  • Distributed locking ensures that if one instance acquires a lock, other instances cannot access the same critical section.

    • Example Key: In a payment service, the key could be "PAYMENT_" + user_id + amount, ensuring that only one action (payment or cancellation) can proceed.

Using Redis for Distributed Locking

  • Single Redis Instance:

    • Can fail, causing locks to remain unreleased.

    • Communication between master-replica can lead to inconsistent lock states.

  • Redlock Algorithm:

    • Acquires locks on multiple Redis instances with expiration times.

    • Lock is considered acquired if the majority of instances successfully lock.

    • Releases locks across all instances.

Conclusion

  • Distributed locking is crucial for ensuring data consistency in production environments with multiple application instances. The Redlock algorithm with Redis provides a robust solution.

Code with detailed explanation:-