LESSON 8 OF 20

8. API Contracts, Error Handling, and Idempotency

Design reliable microservice APIs with DTOs, Problem Details, global exception handling, correlation information, and idempotency keys.

40 dk 35

Introduction

In the previous lesson, we enabled the Order service to communicate with the Catalog and Inventory services through Aspire service discovery. This lesson focuses on three concerns that are more important than simply reaching the correct service: keeping API contracts explicit and stable, reporting failures consistently across services, and preventing a repeated order request from creating a second order.

In distributed systems, an HTTP request may arrive more than once because of a network failure, a timeout, a client retry, or a double-click in the user interface. For a side-effecting operation such as POST /api/orders, this can create duplicate orders. Our Order service will therefore use DTOs, Problem Details, correlation information, and idempotency keys.

Designing API contracts with DTOs

Returning entity classes directly from an API exposes the database model as a public contract. Database fields may be revealed unnecessarily, a migration may accidentally break clients, or clients may be allowed to submit fields they should never control. Define separate request and response DTOs instead.

public sealed record CreateOrderItemRequest(
    Guid ProductId,
    int Quantity);

public sealed record CreateOrderRequest(
    Guid CustomerId,
    IReadOnlyCollection<CreateOrderItemRequest> Items);

public sealed record OrderItemResponse(
    Guid ProductId,
    int Quantity,
    decimal UnitPrice);

public sealed record OrderResponse(
    Guid Id,
    Guid CustomerId,
    string Status,
    IReadOnlyCollection<OrderItemResponse> Items,
    DateTimeOffset CreatedAt);

This separation means the client does not control fields such as Id, Status, or CreatedAt. The API can evolve independently of the current persistence model. Validation rules can also be made explicit at the boundary.

public sealed class CreateOrderRequestValidator
{
    public static Dictionary<string, string[]> Validate(CreateOrderRequest request)
    {
        var errors = new Dictionary<string, string[]>();

        if (request.CustomerId == Guid.Empty)
            errors["customerId"] = ["CustomerId is required."];

        if (request.Items is null || request.Items.Count == 0)
            errors["items"] = ["At least one order item is required."];

        if (request.Items?.Any(x => x.ProductId == Guid.Empty) == true)
            errors["items"] = ["Each item must contain a valid ProductId."];

        if (request.Items?.Any(x => x.Quantity <= 0) == true)
            errors["items"] = ["Quantity must be greater than zero."];

        return errors;
    }
}

Returning field-level error information instead of a generic “bad request” message helps clients correct the request without guessing.

Standardizing failures with Problem Details

ASP.NET Core provides the AddProblemDetails service for producing HTTP API errors in the RFC 9457 Problem Details format. Every service should use the meanings of fields such as type, title, status, detail, and instance consistently.

var builder = WebApplication.CreateBuilder(args);

builder.Services.AddProblemDetails(options =>
{
    options.CustomizeProblemDetails = context =>
    {
        var httpContext = context.HttpContext;
        context.ProblemDetails.Instance = httpContext.Request.Path;
        context.ProblemDetails.Extensions["traceId"] =
            httpContext.TraceIdentifier;

        if (httpContext.Items.TryGetValue("CorrelationId", out var value))
            context.ProblemDetails.Extensions["correlationId"] = value;
    };
});

builder.Services.AddExceptionHandler<GlobalExceptionHandler>();

Do not send exception messages directly to clients in production. SQL details, stack traces, file paths, and internal service addresses can create security risks. Return a safe, actionable message to the client and keep diagnostic details in logs and traces.

Global exception handling

Writing a separate try/catch block in every endpoint leads to inconsistent responses. Instead, implement a central IExceptionHandler that maps known domain failures to HTTP status codes.

public sealed class OrderNotFoundException(Guid orderId)
    : Exception($"Order '{orderId}' was not found.");

public sealed class OrderConflictException(string message)
    : Exception(message);

public sealed class GlobalExceptionHandler(
    IProblemDetailsService problemDetails,
    ILogger<GlobalExceptionHandler> logger) : IExceptionHandler
{
    public async ValueTask<bool> TryHandleAsync(
        HttpContext httpContext,
        Exception exception,
        CancellationToken cancellationToken)
    {
        var statusCode = exception switch
        {
            OrderNotFoundException => StatusCodes.Status404NotFound,
            OrderConflictException => StatusCodes.Status409Conflict,
            ArgumentException => StatusCodes.Status400BadRequest,
            _ => StatusCodes.Status500InternalServerError
        };

        if (statusCode == StatusCodes.Status500InternalServerError)
            logger.LogError(exception, "Unexpected failure. TraceId: {TraceId}",
                httpContext.TraceIdentifier);
        else
            logger.LogWarning(exception, "Business failure. TraceId: {TraceId}",
                httpContext.TraceIdentifier);

        httpContext.Response.StatusCode = statusCode;
        return await problemDetails.TryWriteAsync(new ProblemDetailsContext
        {
            HttpContext = httpContext,
            ProblemDetails = new ProblemDetails
            {
                Status = statusCode,
                Title = statusCode switch
                {
                    404 => "Resource not found",
                    409 => "Operation conflict",
                    400 => "Invalid request",
                    _ => "Server error"
                },
                Detail = statusCode == 500
                    ? "An unexpected error occurred while processing the request."
                    : exception.Message,
                Type = $"https://httpstatuses.com/{statusCode}"
            }
        });
    }
}

The middleware must be enabled in the application pipeline:

builder.Services.AddExceptionHandler<GlobalExceptionHandler>();

var app = builder.Build();
app.UseExceptionHandler();
app.MapControllers();
app.Run();

In .NET 10, exception diagnostics may be suppressed by default when an IExceptionHandler reports that an exception was handled. Review your logging policy so that handled business failures remain operationally visible. Every handled failure should still include correlation and trace information.

Adding a correlation ID

An OpenTelemetry TraceId is useful for tracing, but a separate correlation ID that travels through the client, gateway, and services is often valuable to operations teams. If a client sends X-Correlation-ID, validate and reuse it; otherwise generate a new value.

public sealed class CorrelationIdMiddleware(RequestDelegate next)
{
    public async Task InvokeAsync(HttpContext context)
    {
        const string headerName = "X-Correlation-ID";
        var incoming = context.Request.Headers[headerName].FirstOrDefault();
        var correlationId = string.IsNullOrWhiteSpace(incoming)
            ? Guid.NewGuid().ToString("N")
            : incoming.Trim();

        context.Items["CorrelationId"] = correlationId;
        context.Response.Headers[headerName] = correlationId;

        using (context.RequestServices
            .GetRequiredService<ILoggerFactory>()
            .CreateLogger("Correlation")
            .BeginScope(new Dictionary<string, object>
            {
                ["CorrelationId"] = correlationId
            }))
        {
            await next(context);
        }
    }
}

Use a delegating handler to propagate this header through service-to-service HttpClient calls. Aspire Service Defaults simplifies HttpClient, service discovery, tracing, and health-check configuration; correlation IDs are application-specific contract data and should be added separately.

public sealed class CorrelationIdHandler(IHttpContextAccessor accessor)
    : DelegatingHandler
{
    protected override Task<HttpResponseMessage> SendAsync(
        HttpRequestMessage request,
        CancellationToken cancellationToken)
    {
        var correlationId = accessor.HttpContext?
            .Items["CorrelationId"]?.ToString();

        if (!string.IsNullOrWhiteSpace(correlationId))
            request.Headers.TryAddWithoutValidation(
                "X-Correlation-ID", correlationId);

        return base.SendAsync(request, cancellationToken);
    }
}

Handling retries with an idempotency key

Idempotency means that multiple deliveries of the same logical request produce one effective result. The client sends a unique key when creating an order:

POST /api/orders
Idempotency-Key: checkout-7f3d9d8d-2d6c-4b2d-a4d5-5f5f0f5f6a21
Content-Type: application/json

The key has meaning within the boundary of the Order service. Do not automatically reuse one random key for every downstream Catalog or Inventory call. Each service should define its own idempotency policy.

In a durable implementation, store the key together with a request fingerprint, HTTP status code, response body, and creation time:

public sealed class IdempotencyRecord
{
    public long Id { get; set; }
    public required string Key { get; set; }
    public required string RequestHash { get; set; }
    public int StatusCode { get; set; }
    public required string ResponseBody { get; set; }
    public DateTimeOffset CreatedAt { get; set; }
}

protected override void OnModelCreating(ModelBuilder modelBuilder)
{
    modelBuilder.Entity<IdempotencyRecord>()
        .HasIndex(x => x.Key)
        .IsUnique();
}

The processing flow should be:

  1. Reject a request with 400 Bad Request if the endpoint requires an idempotency key and the header is missing.

  2. Calculate a hash from the normalized request body.

  3. If the key already exists, compare the request hash. Return 409 Conflict if the same key is used with a different payload.

  4. If the same key and payload were completed previously, return the stored status code and response body.

  5. If the same key is currently being processed, use a distributed lock or a database state field. An in-memory ConcurrentDictionary is not enough for multiple instances.

  6. Choose the transaction boundary for the order and idempotency record carefully. The unique index is the final protection against a race condition.

A simplified endpoint can look like this:

app.MapPost("/api/orders", async (
    HttpContext httpContext,
    CreateOrderRequest request,
    OrderDbContext db,
    CancellationToken cancellationToken) =>
{
    var key = httpContext.Request.Headers["Idempotency-Key"]
        .FirstOrDefault();

    if (string.IsNullOrWhiteSpace(key))
    {
        httpContext.Response.StatusCode = 400;
        return Results.Problem(
            title: "Idempotency-Key is required",
            detail: "The order request must contain a unique key.",
            statusCode: 400);
    }

    var hash = RequestHash.Calculate(request);
    var previous = await db.IdempotencyRecords
        .SingleOrDefaultAsync(x => x.Key == key, cancellationToken);

    if (previous is not null)
    {
        if (previous.RequestHash != hash)
            return Results.Conflict(new
            {
                title = "The idempotency key was used for another request",
                correlationId = httpContext.Items["CorrelationId"]
            });

        return Results.Content(
            previous.ResponseBody,
            "application/json",
            Encoding.UTF8,
            previous.StatusCode);
    }

    var order = await OrderApplication.CreateAsync(
        request, db, cancellationToken);
    var response = OrderMapper.ToResponse(order);
    var responseBody = JsonSerializer.Serialize(response);

    db.IdempotencyRecords.Add(new IdempotencyRecord
    {
        Key = key,
        RequestHash = hash,
        StatusCode = StatusCodes.Status201Created,
        ResponseBody = responseBody,
        CreatedAt = DateTimeOffset.UtcNow
    });

    await db.SaveChangesAsync(cancellationToken);
    return Results.Created($"/api/orders/{order.Id}", response);
});

In a production implementation, also handle a unique-index violation when two requests pass the initial lookup concurrently. The database preserves uniqueness; after the violation, load the existing record and return its stored response when the hashes match.

Common mistakes

  • Returning entities directly: This couples the public contract to the database and may expose sensitive fields.
  • Returning 500 for every failure: Separate validation errors, missing resources, business conflicts, and unexpected failures.
  • Publishing raw exception messages: Internal implementation details must not be exposed in production.
  • Relying only on log text: Add correlation IDs, trace IDs, and relevant request metadata to logging scopes.
  • Keeping idempotency only in memory: This fails after a restart or when multiple instances process requests.
  • Accepting a different payload for the same key: This hides client errors and can create inconsistent behavior.
  • Keeping records forever: Define a TTL, cleanup, or archival policy based on the business requirement.

Practice exercise

Complete the Order service POST /api/orders endpoint with the following requirements:

  1. Separate CreateOrderRequest and OrderResponse DTOs from persistence entities.

  2. Add AddProblemDetails and UseExceptionHandler.

  3. Implement a central handler for an order-not-found exception and a conflict exception.

  4. Generate an X-Correlation-ID and return it in the response header.

  5. Reject requests without an Idempotency-Key.

  6. Return the original response without creating a second order when the same key and body are submitted again.

  7. Ensure that reusing the same key with a different body returns a Problem Details-style 409 response.

Conclusion

Reliable microservice communication is more than sending an HTTP request to the correct address through service discovery. DTOs protect service boundaries, Problem Details creates predictable errors, global exception handling centralizes behavior, and correlation information makes requests observable across services. Idempotency keys make side-effecting operations such as order creation safe against network retries and repeated client submissions.

In the next lesson, we will improve the resilience of these contracts with timeouts, retries, circuit breakers, and related policies. The services will then have both explicit contracts and controlled behavior when temporary network failures occur.

Sources