DynamoDb.DistributedLock 1.1.0.11

dotnet add package DynamoDb.DistributedLock --version 1.1.0.11
                    
NuGet\Install-Package DynamoDb.DistributedLock -Version 1.1.0.11
                    
This command is intended to be used within the Package Manager Console in Visual Studio, as it uses the NuGet module's version of Install-Package.
<PackageReference Include="DynamoDb.DistributedLock" Version="1.1.0.11" />
                    
For projects that support PackageReference, copy this XML node into the project file to reference the package.
<PackageVersion Include="DynamoDb.DistributedLock" Version="1.1.0.11" />
                    
Directory.Packages.props
<PackageReference Include="DynamoDb.DistributedLock" />
                    
Project file
For projects that support Central Package Management (CPM), copy this XML node into the solution Directory.Packages.props file to version the package.
paket add DynamoDb.DistributedLock --version 1.1.0.11
                    
#r "nuget: DynamoDb.DistributedLock, 1.1.0.11"
                    
#r directive can be used in F# Interactive and Polyglot Notebooks. Copy this into the interactive tool or source code of the script to reference the package.
#addin nuget:?package=DynamoDb.DistributedLock&version=1.1.0.11
                    
Install DynamoDb.DistributedLock as a Cake Addin
#tool nuget:?package=DynamoDb.DistributedLock&version=1.1.0.11
                    
Install DynamoDb.DistributedLock as a Cake Tool

๐Ÿ”’ DynamoDb.DistributedLock

All Contributors

DynamoDb.DistributedLock is a lightweight .NET library for distributed locking using Amazon DynamoDB. It is designed for serverless and cloud-native applications that require coordination across services or instances.

  • โœ… Safe and atomic lock acquisition using conditional writes
  • โœ… TTL-based expiration to prevent stale locks
  • โœ… AWS-native, no external infrastructure required
  • โœ… Simple IDynamoDbDistributedLock interface
  • โœ… IAsyncDisposable support for automatic lock cleanup
  • โœ… Retry logic with exponential backoff for handling lock contention and throttling
  • โœ… Tested and production-ready for .NET 8 and 9

๐Ÿ“ฆ Package

Package Build NuGet Downloads
DynamoDb.DistributedLock Build NuGet NuGet Downloads

๐Ÿš€ Getting Started

1. Install the NuGet package

dotnet add package DynamoDb.DistributedLock

2. Register the lock in your DI container

services.AddDynamoDbDistributedLock(options =>
{
    options.TableName = "my-lock-table";
    options.LockTimeoutSeconds = 30;
    options.PartitionKeyAttribute = "pk";
    options.SortKeyAttribute = "sk";
});

Or bind from configuration:

services.AddDynamoDbDistributedLock(configuration);

appsettings.json

{
  "DynamoDbLock": {
    "TableName": "my-lock-table",
    "LockTimeoutSeconds": 30,
    "PartitionKeyAttribute": "pk",
    "SortKeyAttribute": "sk"
  }
}

3. Use the lock

public class MyService(IDynamoDbDistributedLock distributedLock)
{
    public async Task<bool> TryDoWorkAsync()
    {
        await using var lockHandle = await distributedLock.AcquireLockHandleAsync("resource-1", "owner-abc");
        if (lockHandle == null) return false; // Lock not acquired

        // ๐Ÿ”ง Critical section - lock automatically released when disposed
        // Your protected code here...
        
        return true;
    }
}
Traditional Pattern
public class MyService(IDynamoDbDistributedLock distributedLock)
{
    public async Task<bool> TryDoWorkAsync()
    {
        var acquired = await distributedLock.AcquireLockAsync("resource-1", "owner-abc");
        if (!acquired) return false;

        try
        {
            // ๐Ÿ”ง Critical section
        }
        finally
        {
            await distributedLock.ReleaseLockAsync("resource-1", "owner-abc");
        }

        return true;
    }
}

๐Ÿ”ง Lock Handle API (v1.1.0+)

The AcquireLockHandleAsync method returns an IDistributedLockHandle that implements IAsyncDisposable for automatic cleanup. This provides several benefits:

โœ… Automatic Lock Release

await using var lockHandle = await distributedLock.AcquireLockHandleAsync("resource-1", "owner-abc");
// Lock is automatically released when the handle goes out of scope

โœ… Exception Safety

await using var lockHandle = await distributedLock.AcquireLockHandleAsync("resource-1", "owner-abc");
if (lockHandle == null) return;

throw new Exception("Oops!"); // Lock is still properly released

โœ… Lock Metadata Access

await using var lockHandle = await distributedLock.AcquireLockHandleAsync("resource-1", "owner-abc");
if (lockHandle == null) return;

Console.WriteLine($"Lock acquired for {lockHandle.ResourceId} by {lockHandle.OwnerId}");
Console.WriteLine($"Lock expires at: {lockHandle.ExpiresAt}");
Console.WriteLine($"Lock is still valid: {lockHandle.IsAcquired}");

๐Ÿ”„ Retry Configuration (v1.1.0+)

The library includes built-in retry logic with exponential backoff to handle lock contention and DynamoDB throttling. Retry is disabled by default to maintain backward compatibility.

โœ… Enable Retry Logic

services.AddDynamoDbDistributedLock(options =>
{
    options.TableName = "my-lock-table";
    options.Retry.Enabled = true;              // Enable retry logic
    options.Retry.MaxAttempts = 5;             // Max retry attempts (default: 3)
    options.Retry.BaseDelay = TimeSpan.FromMilliseconds(100);  // Base delay (default: 100ms)
    options.Retry.MaxDelay = TimeSpan.FromSeconds(5);          // Max delay (default: 5s)
    options.Retry.BackoffMultiplier = 2.0;     // Exponential multiplier (default: 2.0)
    options.Retry.UseJitter = true;            // Add jitter to prevent thundering herd (default: true)
    options.Retry.JitterFactor = 0.25;         // Jitter factor as percentage (default: 0.25 = 25%)
});

โœ… Configuration via appsettings.json

{
  "DynamoDbLock": {
    "TableName": "my-lock-table",
    "Retry": {
      "Enabled": true,
      "MaxAttempts": 5,
      "BaseDelay": "00:00:00.100",
      "MaxDelay": "00:00:05",
      "BackoffMultiplier": 2.0,
      "UseJitter": true,
      "JitterFactor": 0.25
    }
  }
}

โœ… When Retry is Triggered

The retry logic automatically handles these scenarios:

  • Lock contention - When another process holds the lock (ConditionalCheckFailedException)
  • DynamoDB throttling - When requests exceed provisioned capacity (ProvisionedThroughputExceededException)
  • Internal errors - Transient DynamoDB service errors (InternalServerErrorException)
  • Rate limiting - When request rate is exceeded (RequestLimitExceededException)

โœ… Exponential Backoff Example

Attempt 1: Immediate
Attempt 2: 100ms + jitter
Attempt 3: 200ms + jitter  
Attempt 4: 400ms + jitter
Attempt 5: 800ms + jitter (capped at MaxDelay)

Note: Jitter adds randomness (configurable percentage of delay, default 25%) to prevent multiple clients from retrying simultaneously.


๐Ÿ—๏ธ Table Schema

This library supports both dedicated tables and shared, single-table designs. You do not need to create a separate table just for locking โ€” this works seamlessly alongside your existing entities.

By default, the library uses the following attributes:

  • Partition key: pk (String)
  • Sort key: sk (String)
  • TTL attribute: expiresAt (Number, UNIX timestamp in seconds)

However, the partition and sort key attribute names are fully configurable via DynamoDbLockOptions. This makes it easy to integrate into your existing table structure.

โœ… Enable TTL on the expiresAt field in your table settings to allow automatic cleanup of expired locks.


๐Ÿงช Unit Testing

Unit tests are written with:

  • โœ… xUnit v3
  • โœ… AutoFixture + NSubstitute
  • โœ… FluentAssertions (AwesomeAssertions)

The library provides DynamoDbDistributedLockAutoData to support streamlined tests with frozen mocks and null-value edge cases.


๐Ÿ”ฎ Future Enhancements

  • โฑ Lock renewal support
  • ๐Ÿ” Auto-release logic for expired locks
  • ๐Ÿ“ˆ Metrics and diagnostics support
  • ๐ŸŽฏ Health check integration

๐Ÿ“œ License

MIT

This project is licensed under the MIT License. See the LICENSE file for details.


๐Ÿค Contributing

Contributions, feedback, and GitHub issues welcome!

Contributors โœจ

Thanks goes to these wonderful people (emoji key):

<table> <tbody> <tr> <td align="center" valign="top" width="14.28%"><a href="https://github.com/ncipollina"><img src="https://avatars.githubusercontent.com/u/1405469?v=4?s=100" width="100px;" alt="Nick Cipollina"/><br /><sub><b>Nick Cipollina</b></sub></a><br /><a href="https://github.com/LayeredCraft/dynamodb-distributed-lock/commits?author=ncipollina" title="Code">๐Ÿ’ป</a></td> </tr> </tbody> </table>

This project follows the all-contributors specification. Contributions of any kind welcome!

Product Compatible and additional computed target framework versions.
.NET net8.0 is compatible.  net8.0-android was computed.  net8.0-browser was computed.  net8.0-ios was computed.  net8.0-maccatalyst was computed.  net8.0-macos was computed.  net8.0-tvos was computed.  net8.0-windows was computed.  net9.0 is compatible.  net9.0-android was computed.  net9.0-browser was computed.  net9.0-ios was computed.  net9.0-maccatalyst was computed.  net9.0-macos was computed.  net9.0-tvos was computed.  net9.0-windows was computed.  net10.0 was computed.  net10.0-android was computed.  net10.0-browser was computed.  net10.0-ios was computed.  net10.0-maccatalyst was computed.  net10.0-macos was computed.  net10.0-tvos was computed.  net10.0-windows was computed. 
Compatible target framework(s)
Included target framework(s) (in package)
Learn more about Target Frameworks and .NET Standard.

NuGet packages

This package is not used by any NuGet packages.

GitHub repositories

This package is not used by any popular GitHub repositories.

Version Downloads Last updated
1.1.0.11 9 6/10/2025
1.1.0.10 60 6/6/2025
1.1.0-beta.9 60 6/6/2025
1.1.0-beta.8 55 6/6/2025
1.1.0-beta.7 63 6/6/2025
1.0.0.6 142 5/21/2025
1.0.0.5 134 5/19/2025
1.0.0.2 180 5/16/2025
1.0.0.1 221 5/15/2025
1.0.0-beta.4 111 5/19/2025