Events with Cosmos DB Example¶
Demonstrates event-driven architecture patterns using Azure Functions, Service Bus, and Cosmos DB, orchestrated locally with Aspire and the Cosmos DB and Service Bus emulators.
📋 Overview¶
This example shows how to:
- Build event-driven systems with Azure Service Bus topics and subscriptions
- Fan one topic out to several subscriptions, each handled by its own function
- Store events in Cosmos DB with Entity Framework Core
- Run the Cosmos DB and Service Bus emulators with Aspire, including Data Explorer
- Read events and peek Service Bus subscriptions from a documented API with Scalar
🏗️ Architecture¶
flowchart TB
subgraph AppHost["Aspire AppHost"]
Seed["servicebus-seed<br/>(manual start)"] --> Topic
subgraph SB["Service Bus emulator"]
Topic["Topic: accountcreation"]
Topic --> SubA["it-func-Sample-accountcreation-subscription"]
Topic --> SubB["it-func-Sample-badgeprinting-subscription"]
Policy["Topic: policyevent"]
end
SubA --> Subs["Sample.Subscriptions<br/>(Azure Functions)"]
SubB --> Subs
Policy --> Subs
Subs --> Cosmos
API["Sample<br/>(API)"] --> Cosmos
API -. peek .-> SB
Scalar["Scalar"] --> API
subgraph Cosmos["Cosmos DB emulator"]
AccountCreation["AccountCreationEvents"]
Badge["BadgePrinting"]
PolicyEvents["PolicyEvents"]
end
end
🧩 Components¶
| Project | Description |
|---|---|
Sample |
API that reads stored events and peeks Service Bus subscriptions |
Sample.Subscriptions |
Azure Functions processing Service Bus messages |
Sample.Data |
Cosmos DB models and Entity Framework context |
Sample.AppHost |
Aspire orchestration with emulators, Data Explorer, and Scalar |
Sample.Data.Seed |
Database seeding utility (manual start) |
Sample.ServiceBus.Seed |
Service Bus message seeding utility (manual start) |
🔑 Key Features¶
- Service Bus Fan-Out: One
accountcreationtopic feeds two subscriptions, one per function - Cosmos DB Storage: One container per event type, partitioned by
/PartitionKey - Azure Functions Triggers: Service Bus triggers deserialize with Kiota models and store events through EF Core
- Local Emulators: Cosmos DB and Service Bus run in containers with dynamic host ports
- Cosmos Data Explorer: Browse containers and documents from the Aspire dashboard
- Scalar API Reference: Interactive API docs served from the static OpenAPI spec, shown as a child of the API resource
- Service Bus Peek: API endpoints that peek subscriptions without consuming messages
📊 Event Types¶
| Event | Container | Trigger | Description |
|---|---|---|---|
AccountCreationEvent |
AccountCreationEvents |
AccountCreationEventTrigger |
Account creation events |
BadgePrintingEvent |
BadgePrinting |
BadgePrintingEventTrigger |
Same shape plus IsBadgePrinting (default false) |
PolicyEvent |
PolicyEvents |
PolicyEventTrigger |
Insurance policy lifecycle events |
AccountCreationEventTrigger and BadgePrintingEventTrigger both read the accountcreation topic through separate subscriptions, so each message is delivered to both. The badge printing message carries no IsBadgePrinting value, so the stored value is always false.
📂 Project Structure¶
foundry/dotnet/events-with-cosmos/
├── Sample.sln
├── Sample.AppHost/
│ ├── AppHost.cs # Aspire orchestration, Scalar, containers
│ ├── servicebus.json # Emulator topics and subscriptions
│ └── ResourceBuilders/ # Generated resource builders
├── Sample/
│ ├── Endpoints/
│ │ ├── EventEndpoints.cs # Event query API
│ │ └── ServiceBusEndpoints.cs # Service Bus peek API
│ ├── openapi/openapi.v1.yaml # OpenAPI spec served to Scalar
│ └── Sample.http # Ready-to-run requests
├── Sample.Subscriptions/
│ ├── AccountCreationSubTrigger.cs # Account creation handler
│ ├── BadgePrintingSubTrigger.cs # Badge printing handler
│ ├── PolicyEventSubTrigger.cs # Policy event handler
│ └── Mappers/ # Kiota model to entity mappers
├── Sample.Data/
│ ├── Models.cs # Event models
│ └── SampleContext.cs # EF Core context
├── Sample.Data.Seed/ # DB seeding
└── Sample.ServiceBus.Seed/ # Message seeding
🚀 Getting Started¶
Prerequisites¶
- .NET 10.0 SDK
- Aspire CLI 13.6 or later
- Docker Desktop (for the Cosmos DB and Service Bus emulators)
Running the Example¶
The dashboard link is printed on startup. Host ports for the emulators, the Scalar reference, and Data Explorer are dynamic and change on every restart, so open them from the dashboard.
Seeding Data¶
The seed projects do not start automatically. In the dashboard, start them manually, in this order:
- Start
cosmosdb-database-seedto create the database and containers. - Start
servicebus-seedto send five messages toaccountcreationand five topolicyevent.
The function app and API wait for the Cosmos DB database, not for the seeds, so they run before any seed starts.
Explore the Emulators¶
| Resource | Where to find it |
|---|---|
| Cosmos DB Data Explorer | Data Explorer link on the Cosmos DB emulator resource |
| Service Bus emulator | Admin link (health endpoint); the emulator has no web UI, so peek messages through the API |
| Scalar API reference | scalar resource, nested under the API resource |
Note
Service Bus tools that rely on the Azure management plane, such as the VS Code Service Bus extension, can't list topics on the emulator. Use the peek endpoints below instead.
If you use a client library or tool against the emulator, use this connection string format with the dynamic AMQP port from the dashboard:
Endpoint=sb://localhost:<port>;SharedAccessKeyName=RootManageSharedAccessKey;SharedAccessKey=SAS_KEY_VALUE;UseDevelopmentEmulator=true;
Warning
If you change servicebus.json, delete the persistent sbnamespace-* containers so the emulator picks up the new topics and subscriptions.
📡 API Endpoints¶
The API is anonymous and intended for local development. Use Sample/Sample.http with the REST Client extension in VS Code, or Scalar from the dashboard. Run a list request first in Sample.http so the by-id requests can reuse its response.
| Endpoint | Method | Description |
|---|---|---|
/api/events/account-creation |
GET | List account creation events |
/api/events/account-creation/{id} |
GET | Get an account creation event by ID |
/api/events/account-creation/by-email/{email} |
GET | Get account creation events by email |
/api/events/policy |
GET | List policy events |
/api/events/policy/{id} |
GET | Get a policy event by ID |
/api/events/policy/by-policy/{policyNum} |
GET | Get policy events by policy number |
/api/events/debug/db-connection |
GET | Check Cosmos DB connectivity |
/api/servicebus/accountcreation |
GET | Peek the account creation subscription |
/api/servicebus/badgeprinting |
GET | Peek the badge printing subscription |
/openapi/v1.yaml |
GET | OpenAPI document used by Scalar |
The peek endpoints accept count (1-100, default 10), fromSequenceNumber, and deadLetter=true to read the dead-letter queue. Peeking never locks or removes messages. The function triggers consume messages almost immediately, so the active queue is usually empty after a seed. To see messages waiting, stop function-app before running servicebus-seed. Messages that fail three delivery attempts move to the dead-letter queue.
💡 Use Cases¶
- Audit Logging: Immutable event log for compliance
- Event Sourcing: Rebuild state from event history
- CQRS: Separate read/write models with events
- Integration Events: Cross-service communication
🔗 Related Documentation¶
📍 Source Code¶
Location: foundry/dotnet/events-with-cosmos/