LowCodeHub.Idempotency 0.0.13

There is a newer version of this package available.
See the version list below for details.
dotnet add package LowCodeHub.Idempotency --version 0.0.13
                    
NuGet\Install-Package LowCodeHub.Idempotency -Version 0.0.13
                    
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="LowCodeHub.Idempotency" Version="0.0.13" />
                    
For projects that support PackageReference, copy this XML node into the project file to reference the package.
<PackageVersion Include="LowCodeHub.Idempotency" Version="0.0.13" />
                    
Directory.Packages.props
<PackageReference Include="LowCodeHub.Idempotency" />
                    
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 LowCodeHub.Idempotency --version 0.0.13
                    
#r "nuget: LowCodeHub.Idempotency, 0.0.13"
                    
#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.
#:package LowCodeHub.Idempotency@0.0.13
                    
#:package directive can be used in C# file-based apps starting in .NET 10 preview 4. Copy this into a .cs file before any lines of code to reference the package.
#addin nuget:?package=LowCodeHub.Idempotency&version=0.0.13
                    
Install as a Cake Addin
#tool nuget:?package=LowCodeHub.Idempotency&version=0.0.13
                    
Install as a Cake Tool

LowCodeHub.Idempotency

Idempotency for ASP.NET Core Minimal APIs (and MVC): requests carrying an Idempotency-Key header execute once; retries get the stored response (status, headers, body) replayed. Atomic locking across nodes, Redis / SQL Server / PostgreSQL / in-memory stores, OpenTelemetry, health checks.

NuGet License: MIT

dotnet add package LowCodeHub.Idempotency

Quick start

builder.Services.AddIdempotencySqlServer(builder.Configuration);   // or AddIdempotencyRedis / AddIdempotencyPostgreSql / AddIdempotency (in-memory)

var app = builder.Build();
app.UseAuthentication();
app.UseAuthorization();
app.UseIdempotency();                                               // after auth: keys are scoped per user

app.MapPost("/orders", CreateOrder).RequireIdempotency();          // one endpoint
app.MapGroup("/payments").RequireIdempotency(TimeSpan.FromHours(48)); // or a whole group
{ "Idempotency": { "SqlServer": { "ConnectionString": "Server=...;Database=...;" } } }

A provider method alone is enough — it registers the middleware services too. MVC actions/controllers can use [Idempotent] (or [Idempotent(expirationSeconds: 3600)]).

How it works

  1. A marked endpoint without the header returns 400. The key is combined with the caller's scope and hashed (SHA-256); the raw key is never stored or logged.
  2. A completed record is replayed (adds Idempotent-Replayed: true). A record still processing returns 409. Reusing the key for a different request (method, path, query or body) returns 422.
  3. Otherwise the lock is acquired and the handler runs. While it runs the lock is renewed every LockDuration / 3, so slow handlers are never reclaimed mid-request.
  4. The response is stored, unless it is a 5xx or a status in ReleaseOnStatusCodes (default 401, 403, 408, 425, 429): then the key is released so the client can retry. Exceptions also release the key.
  5. If the body is larger than MaxBodyCaptureSize, the request is still recorded as completed: retries get the original status code and headers with no body and Idempotent-Body-Omitted: true — the operation is never executed twice.
  6. If the lock was lost anyway (e.g. a store outage longer than LockDuration), nothing is stored, a warning is logged and idempotency.lock.lost is incremented.
Status When
original first execution, or replay
400 header missing, repeated, or longer than MaxKeyLength
409 the same key is currently being processed
413 request body larger than MaxRequestFingerprintBytes
422 key reused with a different request

Key scope

By default every authenticated user gets their own key namespace (user:{authenticationType}:{id}, using the NameIdentifier, sub or oid claim, then Identity.Name). Unauthenticated requests share one anonymous namespace — on anonymous endpoints, clients should use unguessable keys (UUIDs). Set-Cookie headers are never stored or replayed unless ReplaySetCookie is enabled.

To scope by tenant or anything else, register your own provider (scoped is fine) before AddIdempotency*:

builder.Services.AddScoped<IIdempotencyKeyScopeProvider, TenantScopeProvider>();

public sealed class TenantScopeProvider : IIdempotencyKeyScopeProvider
{
    public string GetScope(HttpContext context) =>
        $"{context.User.FindFirst("tenant_id")?.Value}:{context.User.FindFirst("sub")?.Value ?? "anonymous"}";
}

Configuration

Bind from Idempotency (all AddIdempotency*(IConfiguration) overloads do) and/or configure in code with AddIdempotency(o => ...) / services.Configure<IdempotencyOptions>(...). Options are validated at startup.

Option Default Description
HeaderName Idempotency-Key Request header carrying the key
MaxKeyLength 256 Longer keys return 400
DefaultExpiration 24h How long a completed response is replayable (per endpoint: RequireIdempotency(TimeSpan))
LockDuration 5 min Lock lifetime; renewed every third of it while the handler runs
MaxBodyCaptureSize 256 KB Larger bodies are not stored (status + headers are)
MaxRequestFingerprintBytes 256 KB Larger request bodies return 413
EnforceRequestFingerprint true Reject key reuse with a different request (422)
AllowedMethods POST, PATCH, PUT Other methods pass through
ReleaseOnStatusCodes 401, 403, 408, 425, 429 Non-5xx statuses that are not stored
ReplaySetCookie false Store and replay Set-Cookie
CleanupInterval 15 min Purge interval for SQL stores (null disables)
CleanupBatchSize 1000 Rows deleted per purge batch

Storage

Method Section Notes
AddIdempotency() Idempotency In-memory; single node / development only
AddIdempotencyRedis(...) Idempotency:Redis ConnectionString or ConnectionMultiplexer, KeyPrefix (default idempotency:); expiry via Redis TTL
AddIdempotencySqlServer(...) Idempotency:SqlServer ConnectionString, Schema (dbo), Table (IdempotencyRecords)
AddIdempotencyPostgreSql(...) Idempotency:PostgreSql ConnectionString, Schema (public), Table (idempotency_records)

The SQL stores register a background worker that deletes expired rows every CleanupInterval. Each provider registers a readiness health check (idempotency-redis / idempotency-sqlserver / idempotency-postgresql); the SQL checks also fail when the configured table does not exist.

Database schema

The package never creates tables itself. The embedded scripts create the default table names:

Provider Embedded resource prefix
SQL Server LowCodeHub.Idempotency.Repositories.SqlServer.Scripts.
PostgreSQL LowCodeHub.Idempotency.Repositories.PostgreSql.Scripts.
// LowCodeHub.Migration.SqlServer (use the PostgreSql prefix with LowCodeHub.Migration.PostgreSql)
builder.Services.AddSqlServerMigrations(m => m.AddTarget<IIdempotencyScriptScanner>(o =>
{
    o.ConnectionString = builder.Configuration.GetConnectionString("Idempotency")!;
    o.Directories = ["LowCodeHub.Idempotency.Repositories.SqlServer.Scripts."];
}));

If you configure a custom Schema/Table, generate the DDL instead (constraint and index names follow the table name):

migrationBuilder.Sql(SqlIdempotency.BuildSqlServerSchema("sales", "OrderIdempotency"));   // EF Core migration
migrationBuilder.Sql(SqlIdempotency.BuildPostgreSqlSchema(pgOptions));

SqlIdempotency.SqlServerResources / PostgreSqlResources + ReadFromResource(...) return the embedded scripts for EF Core or other tools.

Admin diagnostics

app.MapIdempotencyDiagnostics();                                    // GET /admin/idempotency, requires an authenticated user
app.MapIdempotencyDiagnostics("/ops/idempotency", authorizationPolicy: "Ops");

Returns record metadata only (never bodies). Query: keyPrefix, state, createdAfter, createdBefore, maxResults (1–1000). Authorization is required by default (needs AddAuthorization() + UseAuthorization()); chain .AllowAnonymous() only on trusted networks.

Observability

Meter and ActivitySource LowCodeHub.Idempotency:

Metric Description
idempotency.requests.total Requests on idempotent endpoints
idempotency.cache.hit / .miss / .conflict / .fingerprint_mismatch Replays / first executions / 409s / 422s
idempotency.lock.lost Locks lost before the response could be stored
idempotency.store.errors Store failures
idempotency.request.duration (ms) Middleware duration

Activities: idempotency.check, idempotency.store.

Custom store

Implement IIdempotencyStore and register it before AddIdempotency() (which uses TryAdd). Contract essentials:

  • TryLockAsync must be atomic and may reclaim only expired records.
  • CompleteAsync returns false when the lock token no longer owns the record; it must accept a null body (store it as "body omitted", distinct from an empty body).
  • TryExtendLockAsync extends a lock still owned by the token (called while the handler runs); PurgeExpiredAsync deletes expired rows (return 0 if the backend expires them itself).

Breaking changes since 0.0.12

  • IIdempotencyStore.CompleteAsync now returns Task<bool> and takes byte[]? responseBody; new required members TryExtendLockAsync / PurgeExpiredAsync.
  • RequireIdempotency is generic over IEndpointConventionBuilder; the marker metadata is the public IdempotentAttribute.
  • The default key scope changed from a global "default" to per-user; existing records will not be replayed after upgrading.
  • MapIdempotencyDiagnostics requires authorization by default.
  • 401/403/408/425/429 responses are no longer stored; Set-Cookie is no longer replayed by default.
  • PostgreSQL Schema/Table must now be plain identifiers (letters, digits, underscore).

License

MIT © Ahmed Abuelnour

Product Compatible and additional computed target framework versions.
.NET net10.0 is compatible.  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
0.1.0 143 11/15/2026
0.0.13 140 10/22/2026
0.0.12 799 7/9/2026
0.0.11 143 6/23/2026
0.0.10 130 6/21/2026
0.0.4 122 5/18/2026
0.0.3 128 5/12/2026
0.0.2 137 4/23/2026
0.0.1 140 3/26/2026