madelson / DistributedLock

A .NET library for distributed synchronization
MIT License
1.81k stars 185 forks source link

Single-node in-memory implementation #223

Open srogovtsev opened 1 month ago

srogovtsev commented 1 month ago

Consider the following scenario: we have a system that might run in a distributed mode and in a single-node mode. There are routines that require cross-node synchronization, so we use distributed locks. We use DI and IDistributedLockProvider to separate ourselves from the implementation details (and use different stores depending on the deployment. But when we deploy the same system in a single-node, we don't need any kind of backing store, and I would assume that the same functionality can be reasonable implemented simply in-memory, based on existing .net synchronization primitives, and just injected instead (e.g., same way as AddDistributedMemoryCache implements in-memory cache for IDistributedCache).

But I would suppose that this is a very obvious idea, and it's either that I simply missed this implementation, or there's some hidden complexity/issue that I miss, and it would be recommended to use a backing store even on single-node installations.

Will be very glad to get any pointers.

madelson commented 1 month ago

Hi @srogovtsev thanks for your interest in the library.

This use-case makes sense and is something I’ve considered in the past. As far as why I haven’t built it (yet):

  1. I didn’t have a real use-case outside of unit tests, and for that there are other reasonable options such as…
  2. File-based and wait handle-based locks, which are effectively local machine scoped. Of course, the latter is mostly windows-only.
  3. The implementation is simple but not entirely trivial because I’d want to retain name-based identity, meaning that 2 different lock objects with the same name need to synchronize with each other (via underlying static data structures that can’t leak memory). Another challenge is the lack of (last time I checked) a native async RW lock implementation, which id want to support.

I would call this “process-scoped synchronization”.

If this is something you’d be interested in contributing, let me know and I can offer some guidance.

mingyangzhu commented 1 month ago

Very useful for monolithic applications that do not want to introduce external components