skip to content

In an Aspire AppHost, what is the difference between WithReference and WaitFor, and why does a pizza-ordering API usually need both on its database?

level: middleimportance: must knowfreq 58%

answer

  1. wiring versus timing
  2. a reference relationship plus injected configuration
  3. WaitAnnotation: Running, then Healthy
  4. WaitForStart ignores health checks
  5. WaitForCompletion(dep, exitCode = 0)

basics

~20 s

WithReference tells the consumer where a dependency is by injecting its connection string or endpoints at start; WaitFor holds the consumer back until that dependency is running and healthy. Without WaitFor the API can start before PostgreSQL accepts connections.

solid answer

~40 s

`WithReference` is about **wiring**: it records a reference relationship and, when the consumer starts, injects configuration such as the database's connection string or a project's endpoints. It says nothing about timing. `WaitFor` is about **ordering**: it adds a wait annotation, so the consumer stays in the Waiting state until the dependency reaches Running and every health check registered for it reports Healthy. `AddPostgres` and `AddDatabase` register health checks, so `api.WithReference(ordersDb).WaitFor(ordersDb)` gives the API a connection string and also delays it until the database exists and accepts connections; waiting on the database also waits on its server. Aspire 9.5 added `WaitForStart`, which waits only for Running, and `WaitForCompletion(dep, exitCode = 0)` waits for a one-shot resource such as a migration runner to exit.

code

csharp · 21 lines
csharp
var builder = DistributedApplication.CreateBuilder(args);

var ordersDb = builder.AddPostgres("postgres").AddDatabase("ordersdb");
var cache = builder.AddRedis("cache");

var migrator = builder.AddProject<Projects.PizzaShop_Migrator>("migrator")
    .WithReference(ordersDb)
    .WaitFor(ordersDb);

builder.AddProject<Projects.PizzaShop_Api>("pizza-api")
    .WithReference(ordersDb)
    .WithReference(cache)
    .WaitFor(cache)
    .WaitForCompletion(migrator)
    .WithHttpHealthCheck("/health");

builder.AddProject<Projects.PizzaShop_Worker>("oven-worker")
    .WithReference(ordersDb)
    .WaitForCompletion(migrator);

builder.Build().Run();

go deeper

for a junior

Recall that WithReference passes configuration and WaitFor delays startup, and that a typical API calls both on its database.

for a middle

Explain the Waiting, Running and Healthy sequence behind WaitFor, which integrations register health checks, and how WaitForStart and WaitForCompletion differ.

for a senior

Show that you gate startup on health without mistaking it for runtime resilience, and that you pick StopOnResourceUnavailable when failing fast beats waiting forever.

for a principal

Discuss how much ordering belongs in the AppHost versus in services that tolerate dependencies arriving late, since deployed environments do not replay the local start order.

## Two different questions A resource graph has to answer two separate questions for every dependency of the pizza-ordering API: 1. **Where is it?** The API needs the PostgreSQL connection string and the Redis address. 2. **When may I start?** The API should not begin serving orders while PostgreSQL is still initializing. `WithReference` answers the first question and `WaitFor` the second. Mixing them up is the most common AppHost mistake in interviews. ## What `WithReference` does `api.WithReference(ordersDb)` does two things: - It adds a **reference relationship** between the two resources, which the dashboard shows in the resource graph. - It registers an environment callback. When the API process is about to start, the callback resolves the database's connection string and writes it into the API's environment, keyed by the resource name. For a project or other endpoint resource the callback injects its endpoint URLs instead. What it does **not** do is delay anything. If PostgreSQL's container is still pulling its image or initializing its data directory, the API starts anyway with a perfectly valid connection string and its first queries fail. The exact variable names a reference produces, and how a client integration reads them, belong to the integrations topic; the point here is that a reference is wiring only. ## What `WaitFor` does `api.WaitFor(ordersDb)` adds a `WaitAnnotation` of type *wait until healthy* and a WaitFor relationship. The orchestrator then: 1. Keeps the API in the **Waiting** state. 2. Waits for the database resource to reach **Running**. 3. Waits for every health check associated with that resource to report **Healthy**. 4. Starts the API. `AddPostgres` registers an Npgsql health check on the server, and `AddDatabase` registers one on the database, which only passes after the server has run `CREATE DATABASE` for it. Because `ordersdb` is a child of `postgres`, `WaitFor(ordersDb)` also adds a wait on the parent server automatically. For a project dependency, `WaitFor` waits only for Running unless the project has a health check attached in the AppHost, typically `WithHttpHealthCheck("/health")`. `WaitFor` also has an overload taking a `WaitBehavior`. `WaitOnResourceUnavailable` keeps waiting if the dependency fails and is the default while the dashboard is enabled; `StopOnResourceUnavailable` makes the wait throw a `DistributedApplicationException` instead, so the dependent fails fast, and it becomes the default when the dashboard is disabled. A resource cannot wait for itself or for its own parent; `WaitFor` throws a `DistributedApplicationException` in both cases. ## The other wait methods | Method | Releases the dependent when | Typical use | |---|---|---| | `WaitFor(dep)` | `dep` is Running and its health checks are Healthy | databases, caches, brokers | | `WaitForStart(dep)` (9.5+) | `dep` is Running; health checks ignored | a dependency whose health needs the dependent first | | `WaitForCompletion(dep, exitCode = 0)` | `dep` has exited with the expected code | a migration or seed project | `WaitForCompletion` is documented as a local-development feature with no effect at deployment time. `WithExplicitStart()` is a different tool: it stops a resource from starting automatically at all, leaving it to be started from the dashboard or CLI. ## Why the API wants both For the pizza-ordering API the usual shape is `WithReference(ordersDb).WithReference(cache).WaitFor(ordersDb)`, and `WaitFor(cache)` if the API cannot start without Redis. The reference gives the API its configuration; the wait removes a burst of startup failures and misleading error logs during local runs. Neither replaces resilience in the service itself: `WaitFor` gates startup only, so a database that restarts later still produces failures the code must handle. ## Reading it in the dashboard The dashboard makes the difference visible. A resource held by `WaitFor` shows the **Waiting** state, while a resource that only has references starts at once and its first log lines show connection errors. Useful checks when a resource never leaves Waiting: - Open the dependency's details and look at its health check results; an unhealthy check, not a missing container, is the usual cause. - Look for a wait cycle, where two resources wait on each other's health; `WaitForStart` on one side breaks it. - For a project dependency, confirm that the `WithHttpHealthCheck` path really exists in the running service; a 404 keeps the dependent waiting. Interviewers often follow up by asking what happens with no waits at all. Every resource then starts as soon as the orchestrator can launch it, in parallel, which is fast but noisy and makes first-request failures look like application bugs.

  • If the API calls WaitFor(ordersDb), does it also need WaitFor(postgres)?
    No. When the dependency is a child resource, `WaitFor` adds a wait on its parent automatically, so waiting on the database also waits on the PostgreSQL server. The database's own health check passes only once the server is up and the database has been created.
  • When would you choose WaitForStart over WaitFor?
    When the dependency's health check cannot pass until the dependent itself is running, or when you only care that the process has started. `WaitForStart`, added in 9.5, releases the dependent at Running and ignores the dependency's health checks, so it avoids a startup deadlock between two resources.
  • Does WaitFor remove the need for retries in the API?
    No. `WaitFor` only orders startup in the AppHost's run. Once the API is running, a database restart or a network fault still reaches the code, so the service keeps its own resilience and treats a failed connection as a normal event.

WithReference is writing the customer's address on the delivery ticket; WaitFor is not letting the driver leave until the pizza is out of the oven. An address alone does not make the pizza ready.

  • WithReference also makes the API wait until the database is ready.
  • WaitFor only checks that the container process started, never its health checks.
  • WaitForCompletion is the call that waits for a database to become healthy.
  • You must WaitFor the PostgreSQL server as well as the database, or the API starts early.
  • With WaitFor in the AppHost, the service no longer needs to handle a dependency going down.

Assumes Aspire 13.6; WaitFor and WaitForCompletion arrived in Aspire 9.0 and WaitForStart in 9.5, so 8.x AppHosts had no startup ordering at all.