1. The Difference Between a Working API and a Resilient API
Modern REST API development is no longer simply about creating HTTP endpoints. A production-ready API must not only produce correct results when everything works, but also behave predictably when dependencies fail or become slow.
A real production system may experience:
- Temporary SQL Server connectivity failures.
- An unavailable payment provider.
- The same order request arriving twice.
- Thousands of concurrent API requests.
- A client disconnecting before the operation finishes.
- An external service becoming dramatically slower.
- An application instance restarting during processing.
These are not exceptional situations. They are normal properties of distributed systems.
The goal of resilience is not to eliminate every failure.
The goal is to limit the impact of failures, preserve data consistency, avoid unnecessary resource consumption, make failures observable and provide a controlled recovery path.
2. What Is Resilience?
Resilience is the ability of a system to continue providing its essential functions when infrastructure, network or dependency problems occur and to recover afterward.
Availability
The system remains able to serve requests whenever possible.
Reliability
Operations remain correct and consistent. Orders aren't duplicated and stock doesn't become corrupted.
Recoverability
The application can return to normal operation after a temporary failure.
3. Example Project: Order and Inventory API
Our sample application will:
- Store product inventory.
- Accept order requests.
- Validate available stock.
- Persist orders in SQL Server.
- Prevent duplicate logical orders.
- Communicate with an external payment API.
- Handle temporary failures safely.
ResilientShop/
├── ResilientShop.Api/
├── ResilientShop.Application/
├── ResilientShop.Domain/
└── ResilientShop.Infrastructure/
4. Creating the .NET 10 API
dotnet new webapi -n ResilientShop.Api -f net10.0
cd ResilientShop.Api
dotnet add package Microsoft.EntityFrameworkCore.SqlServer
dotnet add package Microsoft.EntityFrameworkCore.Design
dotnet add package Microsoft.Extensions.Http.Resilience
dotnet add package Microsoft.AspNetCore.Authentication.JwtBearer
dotnet add package OpenTelemetry.Extensions.Hosting
dotnet add package OpenTelemetry.Instrumentation.AspNetCore
dotnet add package OpenTelemetry.Instrumentation.Http
The Microsoft HTTP resilience package provides modern resilience pipelines built on Polly-based infrastructure.
5. Protecting Data at the Database Level
CREATE TABLE Products
(
Id INT IDENTITY(1,1) PRIMARY KEY,
Name NVARCHAR(200) NOT NULL,
Price DECIMAL(18,2) NOT NULL,
StockQuantity INT NOT NULL,
RowVersion ROWVERSION NOT NULL,
CONSTRAINT CK_Products_Stock
CHECK (StockQuantity >= 0),
CONSTRAINT CK_Products_Price
CHECK (Price >= 0)
);
CREATE TABLE Orders
(
Id BIGINT IDENTITY(1,1) PRIMARY KEY,
ProductId INT NOT NULL,
Quantity INT NOT NULL,
TotalAmount DECIMAL(18,2) NOT NULL,
IdempotencyKey NVARCHAR(100) NOT NULL,
RequestHash CHAR(64) NOT NULL,
Status NVARCHAR(30) NOT NULL,
CreatedAt DATETIME2 NOT NULL
DEFAULT SYSUTCDATETIME(),
CONSTRAINT FK_Orders_Products
FOREIGN KEY (ProductId)
REFERENCES Products(Id),
CONSTRAINT UQ_Orders_Idempotency
UNIQUE (IdempotencyKey),
CONSTRAINT CK_Orders_Quantity
CHECK (Quantity > 0)
);
Critical business rules should not exist only in application code. Database constraints provide an additional line of defense.
6. EF Core Concurrency Configuration
modelBuilder.Entity<Product>()
.Property(x => x.RowVersion)
.IsRowVersion();
modelBuilder.Entity<Order>()
.HasIndex(x => x.IdempotencyKey)
.IsUnique();
SQL Server rowversion is especially useful as an optimistic concurrency token.
7. Centralized Error Handling with ProblemDetails
builder.Services.AddProblemDetails();
builder.Services
.AddExceptionHandler<GlobalExceptionHandler>();
var app = builder.Build();
app.UseExceptionHandler();
Business exceptions can be converted into appropriate HTTP responses such as 404, 409 or 422, while unexpected server errors return a generic 500 response.
Sensitive infrastructure information must remain in protected logs rather than HTTP responses.
8. Retry: Retry Only What Is Safe
Temporary HTTP failures are common, but blindly retrying every request is dangerous.
A payment POST may have succeeded even if the HTTP response never reached the caller. Repeating it can create a second payment.
builder.Services
.AddHttpClient("PaymentApi", client =>
{
client.BaseAddress =
new Uri("https://payments.example.com/");
})
.AddStandardResilienceHandler(options =>
{
options.Retry.MaxRetryAttempts = 3;
options.Retry.Delay =
TimeSpan.FromSeconds(2);
options.Retry.UseJitter = true;
options.TotalRequestTimeout.Timeout =
TimeSpan.FromSeconds(20);
options.AttemptTimeout.Timeout =
TimeSpan.FromSeconds(5);
options.Retry.DisableForUnsafeHttpMethods();
});
Automatic retries for unsafe HTTP methods should only be enabled when the downstream service provides a reliable idempotency mechanism and the operation has been designed accordingly.
9. Circuit Breaker
When a dependency is repeatedly failing, continuing to send more requests can exhaust threads, sockets and connection pools.
A circuit breaker transitions between:
- Closed – traffic flows normally.
- Open – calls fail fast temporarily.
- Half-Open – limited requests test whether the service recovered.
Instead of failing an entire order when the payment provider is temporarily unavailable,
business rules may allow the order to enter a PendingPayment state.
10. Idempotency
A client must be able to safely repeat the same logical operation after an uncertain network failure.
POST /api/orders
Idempotency-Key: 8b734f2c-example-001
{
"productId": 15,
"quantity": 2
}
The server stores the idempotency key and a hash of the logical request. The same key and same payload can return the previous result. The same key with a different payload should be treated as a conflict.
In multi-tenant platforms, uniqueness is often better represented by:
TenantId + ClientId + IdempotencyKey
11. Atomic Inventory Updates
Avoid reading stock into application memory and then updating it later. The condition and update should be evaluated atomically.
UPDATE Products
SET StockQuantity = StockQuantity - @Quantity
WHERE Id = @ProductId
AND StockQuantity >= @Quantity;
IF @@ROWCOUNT = 0
BEGIN
THROW 50001,
'Insufficient stock.',
1;
END;
Inventory modification and order creation should be part of the same transaction whenever they represent one atomic business operation.
12. Optimistic Concurrency
try
{
await db.SaveChangesAsync(ct);
}
catch (DbUpdateConcurrencyException)
{
// Another operation changed the entity.
}
A concurrency conflict isn't always something that should automatically be retried. For some business operations, returning HTTP 409 and asking the caller to reconcile the change is safer.
13. Rate Limiting
Rate limiting protects expensive or sensitive endpoints from accidental or malicious traffic spikes.
Common candidates include:
- Login
- Password reset
- Order creation
- Expensive reports
ASP.NET Core provides built-in rate-limiting middleware with fixed-window, sliding-window, token-bucket and concurrency strategies.
14. Timeout and Cancellation
Timeouts limit how long an operation is allowed to run. Cancellation tokens propagate the fact that an operation is no longer needed.
var product = await _context.Products
.AsNoTracking()
.FirstOrDefaultAsync(
x => x.Id == id,
cancellationToken);
Cancellation tokens should be propagated to database and HTTP operations where supported.
15. Liveness and Readiness Health Checks
Liveness answers whether the application process itself is alive. Readiness answers whether the instance is ready to receive real traffic.
A database failure may therefore mark readiness unhealthy without necessarily requiring the process to be restarted.
16. Observability with OpenTelemetry
A resilient system must also be observable.
The three main signals are:
- Logs – discrete application events.
- Metrics – numerical system behavior.
- Traces – the path of an individual operation across dependencies.
builder.Services.AddOpenTelemetry()
.ConfigureResource(resource =>
resource.AddService(
"ResilientShop.Api"))
.WithTracing(tracing =>
{
tracing
.AddAspNetCoreInstrumentation()
.AddHttpClientInstrumentation();
});
An exporter must also be configured to send telemetry to the chosen monitoring backend.
17. Transactional Outbox
Saving a database record and publishing a message are two separate operations. If the application crashes between them, state can become inconsistent.
The Outbox pattern writes the business record and an integration message into the same database transaction. A background worker publishes the message afterward.
CREATE TABLE OutboxMessages
(
Id UNIQUEIDENTIFIER NOT NULL PRIMARY KEY,
EventType NVARCHAR(200) NOT NULL,
Payload NVARCHAR(MAX) NOT NULL,
CreatedAt DATETIME2 NOT NULL
DEFAULT SYSUTCDATETIME(),
ProcessedAt DATETIME2 NULL
);
Outbox reduces lost-message scenarios, but consumers must still tolerate duplicate message delivery.
18. Failure Scenarios
SQL Server Is Temporarily Unavailable
Use bounded transient-failure handling, logging and a safe 503 response when appropriate.
Payment Succeeded but the Response Was Lost
Use provider idempotency keys or query the existing payment status instead of creating a new payment.
Two Customers Buy the Final Item Simultaneously
Use an atomic SQL update or suitable concurrency strategy.
A Client Floods the API
Apply rate limiting and return HTTP 429 when the policy is exceeded.
An External Service Becomes Extremely Slow
Apply attempt timeout, total timeout, circuit breaker and an appropriate fallback workflow.
19. Security Is Part of Resilience
- Authenticate and authorize every protected operation.
- Validate JWT signature, issuer, audience and expiration.
- Use HTTPS.
- Use parameterized database access.
- Validate input lengths and ranges.
- Keep secrets outside source code.
- Enforce tenant boundaries on the server.
In multi-tenant applications, never trust a TenantId merely because it was supplied by the client. Tenant context should come from a trusted authenticated identity or server-controlled mapping.
20. Test Failure, Not Only Success
| Scenario | Expected Behavior |
|---|---|
| SQL unavailable for 10 seconds | Controlled failure and recovery |
| Duplicate order request | Only one logical order |
| Two buyers, one item | At most one successful order |
| Payment API returns 503 | Resilience policy activates safely |
| Client disconnects | Cancellation propagates |
| Rate limit exceeded | HTTP 429 |
| Database unavailable | Readiness becomes unhealthy |
21. A Layered Production Strategy
Client
↓
Authentication
↓
Rate Limiting
↓
Validation
↓
API Endpoint
↓
Application Service
↓
Transaction + Idempotency
↓
Database
↓
Outbox
↓
External Integration
↓
Retry + Timeout + Circuit Breaker
↓
Logs + Metrics + Traces
No single framework or library can make a system resilient by itself. Resilience is an architectural property created by multiple defensive layers.
22. Conclusion
.NET 10 and ASP.NET Core provide strong building blocks for resilient REST APIs, but resilience is much broader than wrapping code in try-catch or increasing retry counts.
A resilient API:
- Anticipates failure.
- Preserves data integrity.
- Handles duplicate operations safely.
- Prevents slow dependencies from exhausting the entire system.
- Protects concurrent business operations.
- Makes failures observable.
- Fails in a controlled way when success isn't possible.
Developers shouldn't ask only:
“What happens when this operation succeeds?”
The more important question is:
“What happens if the operation stops halfway, runs twice concurrently, or the dependency never responds?”
An API with clear and testable answers to those questions is far more ready for production.
References and Further Reading
- Microsoft Learn – .NET HTTP Resilience
- Microsoft Learn – EF Core Concurrency Conflicts
- Microsoft Learn – ASP.NET Core Error Handling
- Microsoft Learn – ASP.NET Core Health Checks
- Microsoft Learn – ASP.NET Core Rate Limiting
- Microsoft Learn – IHttpClientFactory
- OpenTelemetry – .NET Documentation
- Microsoft – .NET Support Policy
0 Comments