Menu

Distributed Locking in .NET: How to Implement It with Redis and PostgreSQL
📰

Distributed Locking in .NET: How to Implement It with Redis and PostgreSQL

DEV Community: redis·Anton Martyniuk·4 days ago
#tczoyxL1
#devtoredis#devto#dev#shipment#lock
Long article (895 words) — no AI summary yet.
Reading 0:00
15s threshold

A customer gets two "Your shipment is on its way" emails.

The carrier sends two trucks to the same warehouse for the same parcel.

You open the code and the dispatch handler looks perfectly safe.

It even wraps the whole operation in a SemaphoreSlim , so only one request can dispatch a shipment at a time.

Then you notice the deployment changed last week.

The API now runs on two instances behind a load balancer.

A SemaphoreSlim only protects one process.

The second instance has its own semaphore, and it has no idea the first one exists.

This bug shows up the moment you scale out, and it doesn't show up in any test that runs on a single machine.

The fix is a lock that lives outside your process: a distributed lock .

Today, I want to show you how to implement distributed locks in .NET with the DistributedLock library, first with Redis and then with PostgreSQL.

I built a working project with two API instances and you can run it yourself.

In this post, we will explore:

Why lock and SemaphoreSlim Stop…

Continue reading — create a free account

Join HashtagPLUS to read full articles, follow hashtags, vote, and join the conversation.