LowCodeHub.Idempotency
0.1.0
dotnet add package LowCodeHub.Idempotency --version 0.1.0
NuGet\Install-Package LowCodeHub.Idempotency -Version 0.1.0
<PackageReference Include="LowCodeHub.Idempotency" Version="0.1.0" />
<PackageVersion Include="LowCodeHub.Idempotency" Version="0.1.0" />
<PackageReference Include="LowCodeHub.Idempotency" />
paket add LowCodeHub.Idempotency --version 0.1.0
#r "nuget: LowCodeHub.Idempotency, 0.1.0"
#:package LowCodeHub.Idempotency@0.1.0
#addin nuget:?package=LowCodeHub.Idempotency&version=0.1.0
#tool nuget:?package=LowCodeHub.Idempotency&version=0.1.0
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.
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
- 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.
- 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. - 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. - 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. - 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 andIdempotent-Body-Omitted: true— the operation is never executed twice. - If the lock was lost anyway (e.g. a store outage longer than
LockDuration), nothing is stored, a warning is logged andidempotency.lock.lostis 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:
TryLockAsyncmust be atomic and may reclaim only expired records.CompleteAsyncreturnsfalsewhen the lock token no longer owns the record; it must accept anullbody (store it as "body omitted", distinct from an empty body).TryExtendLockAsyncextends a lock still owned by the token (called while the handler runs);PurgeExpiredAsyncdeletes expired rows (return 0 if the backend expires them itself).
Breaking changes since 0.0.12
IIdempotencyStore.CompleteAsyncnow returnsTask<bool>and takesbyte[]? responseBody; new required membersTryExtendLockAsync/PurgeExpiredAsync.RequireIdempotencyis generic overIEndpointConventionBuilder; the marker metadata is the publicIdempotentAttribute.- The default key scope changed from a global
"default"to per-user; existing records will not be replayed after upgrading. MapIdempotencyDiagnosticsrequires authorization by default.- 401/403/408/425/429 responses are no longer stored;
Set-Cookieis no longer replayed by default. - PostgreSQL
Schema/Tablemust now be plain identifiers (letters, digits, underscore).
License
MIT © Ahmed Abuelnour
AI agent skills
This package targets net11.0 and includes version-matched agent instructions under
skills/. After restoring your application's dependencies, install them into your
agent's skill directory:
dotnet tool install --global dotnet-package-skills --prerelease
dotnet-package-skills install
The default destination is .agents/skills/. For Claude, pass
--destination .claude/skills. Run the installer again after package upgrades.
| Product | Versions Compatible and additional computed target framework versions. |
|---|---|
| .NET | net11.0 is compatible. |
-
net11.0
- Microsoft.Data.SqlClient (>= 7.1.2)
- Npgsql (>= 10.0.3)
- StackExchange.Redis (>= 3.4.35)
NuGet packages
This package is not used by any NuGet packages.
GitHub repositories
This package is not used by any popular GitHub repositories.