Introduction
In this final lesson, we will evaluate the distributed application built throughout the course through one complete business workflow. The goal is not to add another service, but to prove that the existing parts work together predictably. Catalog provides product data, Order manages the order lifecycle, and Inventory owns stock and reservations. SQL Server stores durable data, Redis supports fast access and short-lived caching, and RabbitMQ allows services to share events without creating unnecessary direct coupling. The Aspire AppHost starts and connects these resources through one application model and makes their behavior visible through the Dashboard.
By the end of the lesson, we will follow a request from product selection through order creation, stock reservation, and event publication. We will then introduce failures deliberately and inspect how they appear in logs, traces, health checks, and resource status. Finally, we will create a production-readiness checklist that must be reviewed before moving from local development to a production environment.
Application topology
Clear ownership is essential in the final workflow. Catalog owns product names, prices, and active status. Order owns order headers and lines; it copies the product price into the order line when the order is created so that historical orders are not changed by later Catalog updates. Inventory owns stock quantities and reservations. Order should not query Inventory tables directly. Instead, it should use an explicit HTTP contract or an event-based interaction through RabbitMQ.
| Component | Responsibility | Role in the flow |
|---|---|---|
| Catalog | Product and price data | Product validation |
| Order | Order lifecycle | Order creation and state management |
| Inventory | Stock and reservations | Determine stock availability |
| SQL Server | Durable storage | Catalog, Order, and Inventory data |
| Redis | Fast access | Product or stock read caching |
| RabbitMQ | Asynchronous events | OrderCreated or OrderAccepted events |
1. Define the final topology in AppHost
The AppHost makes the resources and dependencies required by the application explicit. The following example preserves the naming approach used throughout the course. In a real solution, the exact project types or integration packages may differ. The important point is that resource names match the connection names expected by the consuming services.
var builder = DistributedApplication.CreateBuilder(args);var sql = builder.AddSqlServer("sql")
.AddDatabase("catalogdb");
var orderDb = sql.AddDatabase("orderdb");
var inventoryDb = sql.AddDatabase("inventorydb");
var redis = builder.AddRedis("cache");
var rabbit = builder.AddContainer("messaging", "rabbitmq", "4-management")
.WithHttpEndpoint(targetPort: 15672, name: "management");
var catalog = builder.AddProject<Projects.CatalogService>("catalog")
.WithReference(sql)
.WithReference(redis)
.WaitFor(sql);
var inventory = builder.AddProject<Projects.InventoryService>("inventory")
.WithReference(inventoryDb)
.WithReference(redis)
.WithReference(rabbit)
.WaitFor(inventoryDb)
.WaitFor(rabbit);
var order = builder.AddProject<Projects.OrderService>("order")
.WithReference(orderDb)
.WithReference(catalog)
.WithReference(inventory)
.WithReference(rabbit)
.WaitFor(orderDb)
.WaitFor(catalog)
.WaitFor(inventory)
.WaitFor(rabbit);
builder.Build().Run();WithReference allows services to receive connection information and service-discovery configuration. WaitFor prevents a dependent resource from starting before its dependency is ready. This reduces startup race conditions, but it is not a complete production resilience strategy. Services must still handle lost connections, restarts, and temporary failures.
For SQL Server, a real system may use one SQL Server instance with several databases, or a separate database server per service. The choice should consider data isolation, operational cost, and team ownership. The key rule is that one service must not directly access another service's tables.
2. Complete the order creation flow
The end-to-end flow can be divided into four stages:
- The client asks Catalog to validate the product identifier.
- Order creates an order draft, copies the current product price into the order line, and stores the initial state as
Pending. - Order asks Inventory to reserve stock. If the reservation succeeds, Inventory persists the reserved quantity.
- Order changes the order state to
Acceptedand publishes anOrderAcceptedevent through RabbitMQ.
A simple request model may look like this:
public sealed record CreateOrderRequest(
Guid ProductId,
int Quantity,
string CustomerId);The Order endpoint should not contain the entire workflow in one method. Product validation, price snapshot creation, stock reservation, and event publication should be separate application-level steps. This makes error behavior, logging fields, and test cases easier to understand.
app.MapPost("/orders", async (
CreateOrderRequest request,
OrderApplicationService service,
CancellationToken cancellationToken) =>
{
var result = await service.CreateAsync(request, cancellationToken);
return result.Match(
success => Results.Created($"/orders/{success.OrderId}", success),
failure => Results.Problem(
title: failure.Title,
detail: failure.Detail,
statusCode: failure.StatusCode));
});The application service should first validate that the quantity is positive and the customer identifier is acceptable. The next step is retrieving the product from Catalog. The call should use the logical service name provided by service discovery rather than a hard-coded localhost address. The service then writes the order to its own database. Stock reservation is performed in a separate transaction boundary. A single SQL transaction should not span the Order and Inventory services.
3. Successful and failed paths
Successful path
For a successful request, the Dashboard should show the client or API request followed by spans for Order, Catalog, and Inventory. The Order database write completes, Inventory records a successful reservation, and a RabbitMQ publisher span is created. Logs should contain shared correlation or trace information. The expected final state is Accepted for the order and Reserved for the inventory reservation.
Product not found
If Catalog cannot find the product, Order must not accept the order. The API should return an appropriate result such as 404, or the domain-specific problem response defined by the service contract. Logging only “request failed” is not sufficient. The product identifier, order correlation information, and Catalog result should be recorded as structured fields. Sensitive customer data must not be written to logs.
Insufficient stock
Inventory may reject the reservation with 409 Conflict or a defined domain error code. If Order has already stored the order as Pending, it should transition the order to Rejected. That transition must be idempotent. Repeating the same failed request or retrying a message should not create a second side effect.
RabbitMQ unavailable
If the broker becomes unavailable after the order is accepted, the database state and the published event can diverge. This is where the Outbox approach from the earlier lesson becomes important. The order and its outbox record are written in the same Order database transaction. A separate publisher worker sends unprocessed outbox records to RabbitMQ and marks them as processed only after successful publication. When the broker is temporarily unavailable, the API does not always need to fail the business operation. Depending on the contract, the order can remain in an intermediate state such as AcceptedPendingNotification.
4. Validate Redis usage
Redis can reduce read pressure for Catalog product queries or Inventory stock views. However, the cache must not become the system's only source of truth. Catalog may read a product from SQL Server and write the successful result to Redis using a key containing the product identifier and version. When the product changes, the key should be invalidated or replaced according to the chosen cache policy.
var cacheKey = $"catalog:product:{productId}";
var cached = await cache.GetStringAsync(cacheKey, cancellationToken);
if (cached is not null)
{
return JsonSerializer.Deserialize<ProductDto>(cached)!;
}
var product = await db.Products
.AsNoTracking()
.SingleOrDefaultAsync(x => x.Id == productId, cancellationToken);
if (product is null)
{
return null;
}
var dto = product.ToDto();
await cache.SetStringAsync(
cacheKey,
JsonSerializer.Serialize(dto),
new DistributedCacheEntryOptions
{
AbsoluteExpirationRelativeToNow = TimeSpan.FromMinutes(5)
},
cancellationToken);
return dto;A common mistake is using a stale cached price as the authoritative order price. During order creation, the price should be validated according to the business rule and copied into the order line. Cache hit rate, cache failures, and invalidation behavior should be measured rather than assumed.
5. Observe the flow in the Dashboard
Before sending the first request, start the AppHost and verify that every resource appears in the Dashboard. SQL Server, Redis, RabbitMQ, Catalog, Inventory, and Order should be visible. If a resource remains in Starting for too long, inspect its health check, container logs, and connection settings.
- Call the Catalog endpoint with a valid product identifier.
- POST a valid product and quantity to the Order endpoint.
- Confirm that the services are healthy in the Resources view.
- Follow the same request across Order, Catalog, and Inventory in the Traces view.
- Filter Structured logs by order identifier and trace identifier.
- Review HTTP duration, error counts, and message-publication metrics.
Next, stop the RabbitMQ container and repeat the flow. The expected behavior is a controlled error or pending state according to the resilience policy defined by the application. Returning a raw exception, exposing a stack trace, or producing an unexplained 500 response is not production-ready behavior.
6. Production-readiness checklist
| Area | Review question |
|---|---|
| Data ownership | Does each service use only its own database and contracts? |
| Resilience | Are timeout, retry, and circuit-breaker limits defined? Are retries idempotent? |
| Messaging | Are Outbox, duplicate messages, poison messages, and dead-letter handling defined? |
| Health | Are readiness and liveness separated? Do critical dependencies have health checks? |
| Observability | Can logs, traces, and metrics be correlated with shared identifiers? |
| Security | Are secrets excluded from source code? Do services authenticate each other? |
| Deployment | Are container images versioned, scanned, and built reproducibly? |
| Data operations | Have migrations, backups, restores, and data-loss scenarios been tested? |
| Operations | Are alert thresholds, runbooks, and rollback plans available? |
The Aspire AppHost provides a shared resource graph for local development, observation, and deployment artifacts. It does not replace a production runtime, a secret manager, or a complete operations platform. Production environments still require separate decisions about network policies, identity, persistent storage, scaling, backups, alerting, and incident response.
Short practice exercise
Run the AppHost and validate three scenarios: a successful order with a valid product and sufficient stock, a rejected order for a missing product, and a broker failure while RabbitMQ is unavailable. For each scenario, record the expected HTTP response, order state, Dashboard trace behavior, and relevant structured-log fields. Finally, mark every item in the production-readiness table as “complete,” “partial,” or “missing.” For two missing items, write one concrete next step.
Conclusion
An end-to-end order flow demonstrates that microservice architecture is more than splitting an application into separate projects. The real result depends on data ownership, explicit contracts, controlled failure behavior, idempotency, reliable messaging, cache policy, and observability working together. Aspire's AppHost lets us view this system as one application model, define its dependencies, and inspect its runtime behavior through the Dashboard. Production readiness does not mean only that the application starts locally. It means the system behaves clearly under failure, avoids corrupting data during retries, leaves useful diagnostic evidence, and can be operated by a team.
Sources
- https://learn.microsoft.com/en-us/dotnet/aspire/
- https://learn.microsoft.com/en-us/dotnet/aspire/architecture/overview
- https://learn.microsoft.com/en-us/dotnet/aspire/service-discovery/overview
- https://learn.microsoft.com/en-us/dotnet/aspire/fundamentals/health-checks
- https://learn.microsoft.com/en-us/dotnet/aspire/fundamentals/telemetry
- https://learn.microsoft.com/en-us/dotnet/aspire/database/sql-server-integrations
- https://learn.microsoft.com/en-us/dotnet/aspire/fundamentals/dashboard/explore