# Lab 4: Fast, Resilient, and Proven

**45 minutes** · Starts from `checkpoint-3` · Ends at `checkpoint-4`

Six steps, each independently useful. If time is short, the instructor will tell you which to skip; the tests in Step 6 are never skipped.

You work in `src/Roastery.Api` and run it the same way as before:

```bash
cd src/Roastery.Api
dotnet run --launch-profile https      # https://localhost:7181
```

The finished code for every step is in the `checkpoint-4` tag. Read any file without leaving your branch with `git show checkpoint-4:<path>`, for example `git show checkpoint-4:src/Roastery.Api/Program.cs`.

!!! info `http/module-4.http`
The requests in `http/module-4.http` on `main` target the versioned routes (`/api/v1/...`) that come later. Against your own Lab 4 branch, or `checkpoint-4`, drop the `/v1` segment: the routes are still `/api/products` and `/api/orders`.
!!!

## Step 1: Output caching on the menu

Register a named policy in `Program.cs`:

```csharp
builder.Services.AddOutputCache(options =>
{
    options.AddPolicy("Products", p => p
        .Expire(TimeSpan.FromMinutes(5))
        .SetVaryByQuery("roast", "inStock")
        .Tag("products"));
});
```

Add `app.UseOutputCache();` directly after `app.UseAuthorization();`, before the `Map` calls. Then, in `Endpoints/ProductEndpoints.cs`, add `using Microsoft.AspNetCore.OutputCaching;` and apply `.CacheOutput("Products")` to the two public `GET` endpoints, `GetProducts` and `GetProduct`. Attach it to each endpoint rather than to the `products` group: the staff sub-group hangs off `products` and would inherit anything you put on the group.

In the staff `CreateProduct`, `UpdateProduct`, and `DeleteProduct` handlers, inject `IOutputCacheStore cache` and call `await cache.EvictByTagAsync("products", ct);` after the change succeeds (for update and delete, only when the product was found).

Send `GET /api/products` three times, without an `Authorization` header. The first response has no `Age` header; the next two carry `Age` and replay the stored `X-Elapsed-Ms` value unchanged, because your handler (and the timing filter around it) did not run. Then update a product as staff and confirm the next `GET` has no `Age` header again, proving the tag eviction worked.

## Step 2: HybridCache for pricing

!!! note First step to skip
If you are behind, skip this step and go straight to Step 3; it is the first cut on the [schedule](../schedule.md). Nothing later depends on it, and `checkpoint-4` has it done.
!!!

From `src/Roastery.Api`:

```bash
dotnet add package Microsoft.Extensions.Caching.Hybrid --version 10.9.0
```

Create `Services/IProductPricing.cs`, a small service that looks up one product through `HybridCache.GetOrCreateAsync` with the `products` tag:

==- `Services/IProductPricing.cs`
```csharp
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Caching.Hybrid;
using Roastery.Api.Data;
using Roastery.Api.Models;

namespace Roastery.Api.Services;

public interface IProductPricing
{
    Task<Product?> GetAsync(int productId, CancellationToken ct);
}

/// <summary>Caches product lookups used for order pricing, with stampede protection.</summary>
public class HybridCacheProductPricing(HybridCache cache, RoasteryDbContext db) : IProductPricing
{
    public async Task<Product?> GetAsync(int productId, CancellationToken ct) =>
        await cache.GetOrCreateAsync(
            $"product:{productId}",
            async token => await db.Products.AsNoTracking().FirstOrDefaultAsync(p => p.Id == productId, token),
            new HybridCacheEntryOptions { Expiration = TimeSpan.FromMinutes(5) },
            tags: ["products"],
            cancellationToken: ct);
}
```
===

Register both in `Program.cs`:

```csharp
builder.Services.AddHybridCache();
builder.Services.AddScoped<IProductPricing, HybridCacheProductPricing>();
```

In `CreateOrder` (`Endpoints/OrderEndpoints.cs`, add `using Roastery.Api.Services;`), inject `IProductPricing pricing` and replace the `db.Products` dictionary lookup with a call per line. The products that come back are cached, no-tracking copies, so changing their `StockQuantity` does nothing when you call `SaveChangesAsync`. Load the tracked entities just before saving and decrement those instead:

==- `CreateOrder` with cached pricing
```csharp
var errors = new Dictionary<string, string[]>();
var priced = new Dictionary<int, Product>();
foreach (var (line, i) in request.Lines.Select((l, i) => (l, i)))
{
    var product = await pricing.GetAsync(line.ProductId, ct);
    if (product is null)
        errors[$"Lines[{i}].ProductId"] = ["Unknown product."];
    else if (product.StockQuantity < line.Quantity)
        errors[$"Lines[{i}].Quantity"] = [$"Only {product.StockQuantity} in stock."];
    else
        priced[line.ProductId] = product;
}
if (errors.Count > 0) return TypedResults.ValidationProblem(errors);

// ... customerId and the new Order as before, using priced[l.ProductId].Price for UnitPrice ...

// Decrement stock on the tracked entities.
var trackedIds = order.Lines.Select(l => l.ProductId).ToList();
var tracked = await db.Products.Where(p => trackedIds.Contains(p.Id)).ToListAsync(ct);
foreach (var line in order.Lines)
    tracked.First(p => p.Id == line.ProductId).StockQuantity -= line.Quantity;

db.Orders.Add(order);
await db.SaveChangesAsync(ct);
```
===

Finally, in the three staff product handlers, inject `HybridCache hybrid` (`using Microsoft.Extensions.Caching.Hybrid;`) and add `await hybrid.RemoveByTagAsync("products", ct);` next to the output-cache eviction. The two caches are separate stores, so evicting one does not touch the other.

## Step 3: Order-ready notifications in the background

Create `Background/OrderReadyNotifier.cs` (namespace `Roastery.Api.Background`) containing `OrderReadyMessage` and `OrderReadyNotifier` from the concepts page, with `using System.Threading.Channels;` at the top of that file too (the Web SDK's implicit usings do not include it). Register the channel and the service in `Program.cs` (add `using System.Threading.Channels;` and `using Roastery.Api.Background;`):

```csharp
builder.Services.AddSingleton(Channel.CreateBounded<OrderReadyMessage>(
    new BoundedChannelOptions(100) { FullMode = BoundedChannelFullMode.Wait }));
builder.Services.AddHostedService<OrderReadyNotifier>();
```

In `ChangeStatus`, inject `Channel<OrderReadyMessage> notifications` (and add the same two `using`s to `OrderEndpoints.cs`). The order only carries a `CustomerId`, so look up the email after saving:

```csharp
order.Status = target;
await db.SaveChangesAsync(ct);

if (target == OrderStatus.Ready)
{
    var email = await db.Customers.Where(c => c.Id == order.CustomerId)
                                  .Select(c => c.Email).FirstAsync(ct);
    await notifications.Writer.WriteAsync(new OrderReadyMessage(order.Id, email), ct);
}
```

Advance an order to `Ready` as staff, `Pending` → `Roasting` → `Ready` (order 1 starts `Pending`, or place a new one first). The `PUT` returns at once, and the `Order {id} is ready; notifying ...` log line appears just after it, written by the background service; its 500 ms delay stands in for the real send.

## Step 4: A resilient payment client

Start the fake provider in a **second terminal** from the repo root, and leave the API running in the first:

```bash
cd src/Roastery.Payments
dotnet run --launch-profile https      # plain `dotnet run` picks the http profile on :5281
```

It listens on `https://localhost:7281` and returns `503` for roughly 30% of requests, logging `Simulated failure charging ...` each time.

Back in `src/Roastery.Api`:

```bash
dotnet add package Microsoft.Extensions.Http.Resilience --version 10.9.0
```

Add the provider's address to `appsettings.json`, as a new top-level section after `Jwt` (mind the comma):

```json
"Payments": {
  "BaseUrl": "https://localhost:7281"
}
```

Create `Payments/PaymentClient.cs`. A non-success status that survives the retries becomes an exception, so the order is never saved:

==- `Payments/PaymentClient.cs`
```csharp
namespace Roastery.Api.Payments;

public record ChargeRequest(decimal Amount, string Currency = "USD");
public record ChargeReceipt(string ReceiptId, decimal Amount, DateTimeOffset ChargedAt);

public class PaymentDeclinedException(string reason) : Exception(reason);

/// <summary>Typed client for the (deliberately flaky) Roastery.Payments service.</summary>
public class PaymentClient(HttpClient http, ILogger<PaymentClient> log)
{
    // Virtual so tests can substitute a client that never calls the network.
    public virtual async Task<ChargeReceipt> ChargeAsync(decimal amount, CancellationToken ct)
    {
        var response = await http.PostAsJsonAsync("/charge", new ChargeRequest(amount), ct);
        if (!response.IsSuccessStatusCode)
        {
            log.LogError("Payment failed with {Status} after resilience pipeline", response.StatusCode);
            throw new PaymentDeclinedException($"Payment provider returned {(int)response.StatusCode}.");
        }
        return (await response.Content.ReadFromJsonAsync<ChargeReceipt>(cancellationToken: ct))!;
    }
}
```
===

Register it in `Program.cs` (`using Roastery.Api.Payments;`). The fallback matches the checkpoint, so a missing config key still points at the local provider:

```csharp
builder.Services.AddHttpClient<PaymentClient>(client =>
        client.BaseAddress = new Uri(builder.Configuration["Payments:BaseUrl"] ?? "https://localhost:7281"))
    .AddStandardResilienceHandler();
```

In `CreateOrder` (add `using Roastery.Api.Payments;` to `OrderEndpoints.cs` too), inject `PaymentClient payments` and charge after computing `order.Total`, before the tracked-stock decrement and `SaveChangesAsync`:

```csharp
// Charge through the resilient payment client before committing the order.
await payments.ChargeAsync(order.Total, ct);
```

Place several orders as a customer. Every one succeeds, but some take a little longer (up to a couple of seconds, depending on the jittered backoff): in the Payments terminal you see `Simulated failure charging ...`, and in the API terminal a Polly warning `Resilience event occurred. EventName: 'OnRetry'` followed by a successful retry.

Then stop the payments process (Ctrl+C) and place one more order. The handler retries three times with exponential backoff (roughly 5 to 15 seconds in total, because the backoff is jittered; you will see three `OnRetry` events), then the `HttpRequestException` reaches the global exception handler and you get a `500` ProblemDetails response. Nothing maps payment failures to a friendlier status yet; a `PaymentDeclinedException` handler returning `502` is a good exercise if you finish early.

!!! info Why the circuit breaker does not open here
The standard handler's breaker only evaluates once it has seen at least 100 calls in a 30-second window, so a few manual requests never trip it. It is there for real traffic; you would need a load tool to watch it open.
!!!

Restart the payments service before moving on.

## Step 5: Health and telemetry

From `src/Roastery.Api`:

```bash
dotnet add package Microsoft.Extensions.Diagnostics.HealthChecks.EntityFrameworkCore --version 10.0.11
```

Register the checks with the other services, before `builder.Build()`:

```csharp
builder.Services.AddHealthChecks().AddDbContextCheck<RoasteryDbContext>();
```

Then replace the old hand-written `app.MapGet("/health", ...)` line:

```csharp
app.MapHealthChecks("/health");
app.MapHealthChecks("/alive", new() { Predicate = _ => false });
```

Next, add OpenTelemetry. The starter does not have it; you create `Observability/Telemetry.cs` with an `AddRoasteryTelemetry()` extension and call `builder.AddRoasteryTelemetry();` in `Program.cs` (`using Roastery.Api.Observability;`). It wires tracing and metrics for ASP.NET Core and `HttpClient`, plus runtime metrics and OpenTelemetry logging. `snippets/otel.cs` has the same block annotated. It exports over OTLP only when `OTEL_EXPORTER_OTLP_ENDPOINT` is set, which the Aspire dashboard does for you in Module 5.

```bash
dotnet add package OpenTelemetry.Extensions.Hosting --version 1.18.0
dotnet add package OpenTelemetry.Exporter.OpenTelemetryProtocol --version 1.18.0
dotnet add package OpenTelemetry.Instrumentation.AspNetCore --version 1.18.0
dotnet add package OpenTelemetry.Instrumentation.Http --version 1.18.0
dotnet add package OpenTelemetry.Instrumentation.Runtime --version 1.18.0
```

==- `Observability/Telemetry.cs`
```csharp
using OpenTelemetry.Metrics;
using OpenTelemetry.Resources;
using OpenTelemetry;
using OpenTelemetry.Trace;

namespace Roastery.Api.Observability;

public static class Telemetry
{
    public static WebApplicationBuilder AddRoasteryTelemetry(this WebApplicationBuilder builder)
    {
        builder.Logging.AddOpenTelemetry(logging =>
        {
            logging.IncludeFormattedMessage = true;
            logging.IncludeScopes = true;
        });

        builder.Services.AddOpenTelemetry()
            .ConfigureResource(r => r.AddService("roastery-api"))
            .WithMetrics(metrics => metrics
                .AddAspNetCoreInstrumentation()
                .AddHttpClientInstrumentation()
                .AddRuntimeInstrumentation())
            .WithTracing(tracing => tracing
                .AddAspNetCoreInstrumentation()
                .AddHttpClientInstrumentation());

        // Export only when an OTLP endpoint is configured (the Aspire dashboard sets it in Module 5).
        if (!string.IsNullOrWhiteSpace(builder.Configuration["OTEL_EXPORTER_OTLP_ENDPOINT"]))
            builder.Services.AddOpenTelemetry().UseOtlpExporter();

        return builder;
    }
}
```
===

There is no EF Core instrumentation in this setup; database calls show up in traces only through the ASP.NET Core request span around them.

Hit `/health` and `/alive`. With the API running, rename `roastery.db` in `src/Roastery.Api` and hit `/health` again; it should report `Unhealthy` (status `503`) while `/alive` still says `Healthy`. Rename it back afterward.

## Step 6: Integration tests

Create the test project from the repo root:

```bash
dotnet new xunit -n Roastery.Tests -o src/Roastery.Tests -f net10.0   # -f matters if a .NET 11 preview SDK is installed
rm src/Roastery.Tests/UnitTest1.cs                 # otherwise you run 5 tests, not 4
dotnet add src/Roastery.Tests reference src/Roastery.Api
dotnet add src/Roastery.Tests package Microsoft.AspNetCore.Mvc.Testing --version 10.0.11
dotnet add src/Roastery.Tests package Microsoft.EntityFrameworkCore.Sqlite --version 10.0.11
dotnet sln src/Roastery.slnx add src/Roastery.Tests   # optional: lets your IDE see the project
```

Add `public partial class Program { }` at the bottom of the API's `Program.cs`. Top-level statements generate an `internal` `Program` class; this makes it public so `WebApplicationFactory<Program>` can reference it from the test project.

Create three files in `src/Roastery.Tests`:

- **`TestAuthHandler.cs`**: the handler from the concepts page (keep its `using` lines: the test project is not a Web SDK project, so none of the ASP.NET Core namespaces are implicit), plus `AsStaff()` / `AsCustomer(int id)` extensions on `HttpClient` that set the `X-Test-User` header.
- **`AlwaysApprovePaymentClient.cs`**: a `PaymentClient` subclass that overrides `ChargeAsync` to approve instantly, for the factory to register in place of the real one.
- **`RoasteryFactory.cs`**: a `WebApplicationFactory<Program>` that swaps in in-memory SQLite, the payment client, and the test auth scheme.

==- `TestAuthHandler.cs` client extensions
```csharp
public static class TestClientExtensions
{
    public static HttpClient AsStaff(this HttpClient client)
    {
        client.DefaultRequestHeaders.Remove("X-Test-User");
        client.DefaultRequestHeaders.Add("X-Test-User", "staff");
        return client;
    }

    public static HttpClient AsCustomer(this HttpClient client, int customerId)
    {
        client.DefaultRequestHeaders.Remove("X-Test-User");
        client.DefaultRequestHeaders.Add("X-Test-User", $"customer:{customerId}");
        return client;
    }
}
```
===

==- `AlwaysApprovePaymentClient.cs`
```csharp
using Roastery.Api.Payments;

namespace Roastery.Tests;

/// <summary>A payment client that never fails, so tests are deterministic.</summary>
public class AlwaysApprovePaymentClient() : PaymentClient(
    new HttpClient { BaseAddress = new Uri("http://payments.test") },
    new Microsoft.Extensions.Logging.Abstractions.NullLogger<PaymentClient>())
{
    public override Task<ChargeReceipt> ChargeAsync(decimal amount, CancellationToken ct) =>
        Task.FromResult(new ChargeReceipt($"test-{Guid.NewGuid():N}", amount, DateTimeOffset.UtcNow));
}
```
===

==- `RoasteryFactory.cs`
```csharp
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Mvc.Testing;
using Microsoft.Data.Sqlite;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.DependencyInjection.Extensions;
using Roastery.Api.Data;
using Roastery.Api.Payments;

namespace Roastery.Tests;

public class RoasteryFactory : WebApplicationFactory<Program>
{
    private SqliteConnection _connection = null!;

    protected override void ConfigureWebHost(IWebHostBuilder builder)
    {
        builder.UseEnvironment("Testing");

        builder.ConfigureServices(services =>
        {
            // Swap the SQLite file for a private in-memory database kept open for the app's lifetime.
            services.RemoveAll<DbContextOptions<RoasteryDbContext>>();
            services.RemoveAll<RoasteryDbContext>();
            _connection = new SqliteConnection("DataSource=:memory:");
            _connection.Open();
            services.AddDbContext<RoasteryDbContext>(o => o.UseSqlite(_connection));

            // Replace the typed payment client.
            services.RemoveAll<PaymentClient>();
            services.AddScoped(_ => (PaymentClient)new AlwaysApprovePaymentClient());

            // Add a test auth scheme and make it the default.
            services.AddAuthentication(TestAuthHandler.SchemeName)
                .AddScheme<AuthenticationSchemeOptions, TestAuthHandler>(TestAuthHandler.SchemeName, _ => { });

            var provider = services.BuildServiceProvider();
            using var scope = provider.CreateScope();
            var db = scope.ServiceProvider.GetRequiredService<RoasteryDbContext>();
            db.Database.EnsureCreated();
            Seed.RunAsync(db).GetAwaiter().GetResult();
        });
    }

    protected override void Dispose(bool disposing)
    {
        base.Dispose(disposing);
        if (disposing) _connection?.Dispose();
    }
}
```
===

A few things in that factory are deliberate:

- **`UseEnvironment("Testing")`** keeps the app out of `Development`, so the startup block in `Program.cs` that migrates the file database and seeds Identity users never runs. The factory creates the schema itself with `EnsureCreated()` and calls `Seed.RunAsync` so products, customers, and orders 1 and 2 exist.
- **`AddAuthentication("Test")`** registers the test scheme and makes it the default, so the `X-Test-User` header decides who the caller is, and the real `Staff` and `OwnsOrder` policies run against that identity.
- **`RemoveAll<PaymentClient>()`** drops the typed-client registration and puts `AlwaysApprovePaymentClient` in its place. Its `ChargeAsync` override returns a fake receipt without touching the network, which is why `PaymentClient.ChargeAsync` is `virtual`. Forget `virtual` and the subclass only *hides* the method; the handler still calls the real one, which tries to `POST` to `http://payments.test` and turns the order into a `500`.

Add the four tests in `OrderApiTests.cs`. Each one names the rule it proves; read the assertions before you run them:

| Test | Request | Expected |
|---|---|---|
| `Anonymous_can_read_menu` | `GET /api/products`, no identity | `200` |
| `Customer_cannot_change_order_status` | `AsCustomer(1)`, `PUT /api/orders/1/status` | `403` |
| `Staff_can_change_order_status` | `AsStaff()`, order 1 `Pending → Roasting` | `200` |
| `Illegal_transition_returns_409_problem` | `AsStaff()`, order 2 `→ PickedUp` | `409` + `application/problem+json` |

==- `OrderApiTests.cs`
```csharp
using System.Net;
using System.Net.Http.Json;
using Microsoft.AspNetCore.Mvc.Testing;
using Xunit;

namespace Roastery.Tests;

public class OrderApiTests(RoasteryFactory factory) : IClassFixture<RoasteryFactory>
{
    private HttpClient NewClient() =>
        factory.CreateClient(new WebApplicationFactoryClientOptions { AllowAutoRedirect = false });

    [Fact]
    public async Task Anonymous_can_read_menu()
    {
        var response = await NewClient().GetAsync("/api/products");
        Assert.Equal(HttpStatusCode.OK, response.StatusCode);
    }

    [Fact]
    public async Task Customer_cannot_change_order_status()
    {
        var client = NewClient().AsCustomer(1);
        var response = await client.PutAsJsonAsync("/api/orders/1/status", new { status = "Roasting" });
        Assert.Equal(HttpStatusCode.Forbidden, response.StatusCode);
    }

    [Fact]
    public async Task Staff_can_change_order_status()
    {
        var client = NewClient().AsStaff();
        var response = await client.PutAsJsonAsync("/api/orders/1/status", new { status = "Roasting" });
        Assert.Equal(HttpStatusCode.OK, response.StatusCode);
    }

    [Fact]
    public async Task Illegal_transition_returns_409_problem()
    {
        var client = NewClient().AsStaff();
        var response = await client.PutAsJsonAsync("/api/orders/2/status", new { status = "PickedUp" });
        Assert.Equal(HttpStatusCode.Conflict, response.StatusCode);
        Assert.Equal("application/problem+json", response.Content.Headers.ContentType?.MediaType);
    }
}
```
===

Run them from the repo root:

```bash
dotnet test src/Roastery.Tests
```

!!! success
If all four pass, you have proof that your authorization rules and your domain rules hold across the real pipeline. That proof is what lets you refactor tomorrow.
!!!

## Stretch goals

- Add `GET /api/orders/{id}/events` that streams status changes with `TypedResults.ServerSentEvents(...)`, fed by a second channel. Watch it in the browser.
- Load-test the menu with `k6` or `bombardier` before and after output caching and compare requests per second.
- Add a test that places an order and asserts stock was decremented, using `TimeProvider` to pin `PlacedAt`. `AlwaysApprovePaymentClient` already approves the charge without a network call.
- Add an `IExceptionHandler` that turns `PaymentDeclinedException` and `HttpRequestException` from the payment client into a `502` ProblemDetails.

## Common pitfalls

- **Cache never hits.** The request carries an `Authorization` header (correct behavior: authenticated requests are not cached), or `.CacheOutput("Products")` is missing from that endpoint.
- **Payments calls fail immediately.** The payments service is running on the `http` profile (`:5281`). Restart it with `dotnet run --launch-profile https`.
- **Tests see a redirect instead of the real status.** Create the client with `AllowAutoRedirect = false`.
- **Tests do not compile with `CS1503` in `TestAuthHandler`.** You passed `Scheme` (an `AuthenticationScheme` object) to `ClaimsIdentity` or `AuthenticationTicket`; both need the string `SchemeName`.
- **`dotnet test` reports five tests.** Delete the template's `UnitTest1.cs`.
- **Background service disappears.** An exception escaped `ExecuteAsync`. Check the `try/catch` around each message.
- **`No service for type IOutputCacheStore`.** `AddOutputCache()` is missing.

## Checkpoint

```bash
git add -A && git commit -m "Lab 4 complete"
# or: git checkout checkpoint-4
```

Next: [Module 5: Aspire, Containers, and Shipping](../module-5-shipping/concepts.md)
