Round #296

08 May 2026, 13:08· csharp· meta/llama-3.3-70b-instruct· r13-clean-hints
Complexity
band 0
ZP / UO / OBS
4 / 0 / 0
Journey weight
284
Lightshift ΔL
+0.25

Prompt

Implement idempotency key middleware that deduplicates POST requests

Zero-point index (what the engine surfaced)

ZPI-ZPI-0002 | 2026-05-08T13:08:17Z Implement idempotency key middleware that deduplicates POST requests ZERO POINT — 4 entries (structural invariants) ● hsl(314.84, 100%, 32%) IMiddleware [contract] ● hsl(280.69, 100%, 32%) RequestDelegate [contract] ● hsl(329.61, 100%, 21%) IDistributedCache [contract] ● hsl(136.10, 100%, 31%) DbContext [contract] UNOBSERVED — 0 entries (implied truths) OBSERVED — 0 entries (explicit in request) COMPLEXITY │ 4 entries │ spread: 0° │ band: LOW

Baseline response (no ZPI)

Idempotency Key Middleware ========================== The following C# code implements idempotency key middleware to deduplicate POST requests. This middleware checks for the presence of an `Idempotency-Key` header in the request. If the key is present, it checks if a request with the same key has been processed before. If a request with the same key has been processed, it returns a cached response instead of processing the request again. ### IdempotencyKeyMiddleware.cs ```csharp using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Http.Extensions; using System; using System.Collections.Concurrent; using System.Threading.Tasks; public class IdempotencyKeyMiddleware { private readonly RequestDelegate _next; private readonly ConcurrentDictionary<string, string> _idempotencyKeys; public IdempotencyKeyMiddleware(RequestDelegate next) { _next = next; _idempotencyKeys = new ConcurrentDictionary<string, string>(); } public async Task InvokeAsync(HttpContext context) { if (context.Request.Method == "POST") { var idempotencyKey = context.Request.Headers["Idempotency-Key"].ToString(); if (!string.IsNullOrEmpty(idempotencyKey)) { if (_idempotencyKeys.TryGetValue(idempotencyKey, out var cachedResponse)) { context.Response.StatusCode = 200; await context.Response.WriteAsync(cachedResponse); return; } } } var originalResponseStream = context.Response.Body; using var responseBody = new System.IO.MemoryStream(); context.Response.Body = responseBody; await _next(context); context.Response.Body = originalResponseStream; var idempotencyKeyFromRequest = context.Request.Headers["Idempotency-Key"].ToString(); if (!string.IsNullOrEmpty(idempotencyKeyFromRequest)) { var responseContent = await new StreamReader(responseBody).ReadToEndAsync(); _idempotencyKeys.TryAdd(idempotencyKeyFromRequest, responseContent); responseBody.Position = 0; await context.Response.WriteAsync(responseContent); } } } ``` ### Startup.cs To use the middleware, add it to the pipeline in the `Startup.cs` file: ```csharp public void Configure(IApplicationBuilder app, IWebHostEnvironment env) { // ... app.UseMiddleware<IdempotencyKeyMiddleware>(); // ... } ``` ### Example Usage To test the idempotency key middleware, you can send a POST request with an `Idempotency-Key` header: ```bash curl -X POST \ http://localhost:5000/api/example \ -H 'Content-Type: application/json' \ -H 'Idempotency-Key: example-key' \ -d '{"name":"John","age":30}' ``` If you send the same request again with the same `Idempotency-Key` header, the middleware will return the cached response instead of processing the request again. Note: This implementation uses a simple in-memory cache to store the idempotency keys and responses. In a production environment, you may want to use a more robust caching solution, such as Redis or a distributed cache.

Enhanced response (with ZPI)

### Idempotency Key Middleware Implementation The following C# code implements idempotency key middleware to deduplicate POST requests. This middleware checks for a unique idempotency key in the request headers and uses a distributed cache to store the keys of processed requests. ```csharp using Microsoft.AspNetCore.Http; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; using System; using System.Threading.Tasks; public class IdempotencyKeyMiddleware { private readonly RequestDelegate _next; private readonly IDistributedCache _distributedCache; private readonly ILogger<IdempotencyKeyMiddleware> _logger; public IdempotencyKeyMiddleware(RequestDelegate next, IDistributedCache distributedCache, ILogger<IdempotencyKeyMiddleware> logger) { _next = next; _distributedCache = distributedCache; _logger = logger; } public async Task InvokeAsync(HttpContext context) { if (context.Request.Method == "POST") { var idempotencyKey = context.Request.Headers["Idempotency-Key"].ToString(); if (!string.IsNullOrEmpty(idempotencyKey)) { var cacheKey = $"idempotency:{idempotencyKey}"; var cachedValue = await _distributedCache.GetStringAsync(cacheKey); if (cachedValue != null) { _logger.LogInformation($"Idempotency key {idempotencyKey} has already been processed. Returning 409 Conflict."); context.Response.StatusCode = 409; await context.Response.WriteAsync("Conflict: Idempotency key has already been processed."); return; } try { await _next(context); await _distributedCache.SetStringAsync(cacheKey, "processed", new DistributedCacheEntryOptions { AbsoluteExpirationRelativeToNow = TimeSpan.FromHours(1) // Cache for 1 hour }); } catch (Exception ex) { _logger.LogError(ex, $"Error processing request with idempotency key {idempotencyKey}"); throw; } } else { _logger.LogInformation("Idempotency key is missing. Proceeding with request."); await _next(context); } } else { await _next(context); } } } ``` ### Registration in the DI Container To use the idempotency key middleware, you need to register it in the DI container in the `Program.cs` file: ```csharp builder.Services.AddDistributedMemoryCache(); builder.Services.AddSingleton<IdempotencyKeyMiddleware>(); var app = builder.Build(); app.UseMiddleware<IdempotencyKeyMiddleware>(); ``` ### Explanation This middleware checks for the presence of an `Idempotency-Key` header in the request. If the header is present, it checks the distributed cache for a corresponding cache key. If the cache key is found, it returns a 409 Conflict response. If the cache key is not found, it proceeds with the request and caches the idempotency key after successful processing. The `IDistributedCache` interface is used to store the idempotency keys in a distributed cache. This allows the middleware to work correctly even in a load-balanced or distributed environment. The `ILogger` interface is used to log important events, such as when an idempotency key has already been processed or when an error occurs during request processing. Note that this implementation assumes that the `Idempotency-Key` header is sent with each request. You may need to modify the implementation to suit your specific use case. Additionally, you should consider implementing a mechanism to handle cache expiration and removal of stale idempotency keys.

Grader chain

Each grader reads the same baseline + enhanced pair and casts an independent verdict. Disagreement is the framework's own signal — not noise to be averaged away.

V1claude-sonnet-4-6
Same
V4qwen2.5-coder-7b-instruct
Better

Comments

Our grader said what it said. What do you say? Comment as a guest below.

No comments yet. Be the first to say what you make of this round.

← back to all rounds