Skip to content

Event Subscriptions

This guide shows you how to add Azure Service Bus event subscription capabilities to your existing .NET application.

Aspire Publish Alternative

Starting in Forge 3.3, Azure Functions subscription projects are auto-detected by Aspire publish when using the SAIF.Platform.Aspire.Hosting package. Add them with AddSubscriptionService<TProject>() in your AppHost and pipeline YAML is generated automatically. See Aspire Publish for details.

๐Ÿ“‹ Prerequisites

  • โœ… Existing SAIF API project
  • โœ… .NET 10.0 SDK
  • โœ… Docker Desktop
  • โœ… Azure DevOps access

๐Ÿš€ Quick Start

1. Add the Feature

Run the SAIF CLI from your application root:

saif new saif-feature-event-subscription

This adds:

  • YourApp.Subscriptions - Functions project
  • YourApp.ServiceBus.Seed - Test data seeder
  • Infrastructure and pipeline files

2. Wire Up AppHost

โš ๏ธ Manual step required: Add to src/YourApp.AppHost/Program.cs:

var subscription = builder.AddSubscription();

Complete example:

var builder = DistributedApplication.CreateBuilder(args);

var backend = builder.AddApi();
var subscription = builder.AddSubscription();  // ๐Ÿ‘ˆ Add this

builder.Build().Run();

โš™๏ธ Configure Subscriptions

Edit infra/sub/vars.yml with the topics and subscriptions you want to create:

application_name: YourApp
owner: Platform
project_id: it-api-exp-yourapp
function_app_project_id: it-func-yourapp
events:
  - topic: newuser # Topic name from the event service
    subscription: it-func-yourapp-newuser-subscription
  - topic: policy # Add as many topics as you need
    subscription: it-func-yourapp-policy-subscription
  - topic: accountupdated
    subscription: it-func-yourapp-accountupdated-subscription

๐Ÿ’ก Note: Subscription names must be unique within each topic. It is recommended to prefix subscription names with your function app project ID (e.g., it-func-yourapp-*), as that is guaranteed to be unique, to avoid conflicts with other applications subscribing to the same topics.

Tune Subscription Settings

Each event also accepts optional settings. Omit them to keep the current behavior.

events:
  - topic: newuser
    subscription: it-func-yourapp-newuser-subscription
    default_message_ttl: P7D
    lock_duration: PT2M
    max_delivery_count: 5
    dead_lettering_on_message_expiration: true
Setting Default Description
default_message_ttl Unset (Azure Service Bus default, effectively unlimited) ISO 8601 time-to-live for messages on the subscription. The lower of the subscription and topic values applies.
lock_duration PT1M ISO 8601 time a received message stays locked for your function before it becomes available again (maximum 5 minutes).
max_delivery_count 1 Delivery attempts before a message is dead-lettered. The default dead-letters a message after one failed attempt, so raise it if you want your function to retry on exceptions.
dead_lettering_on_message_expiration false Move expired messages to the subscription's dead-letter queue instead of discarding them. See Self-Service DLQ Access.

๐Ÿ“ฅ Consume an API-Owned Queue

Besides topic subscriptions, a function app can consume from a Service Bus queue. The queue is owned and provisioned by the API (enable_servicebus_queue and servicebus_queues in saif-api-service, see Service Bus queues). The subscriber module does not create the queue; it only grants the function app's managed identity scoped access to a queue that already exists.

For existing projects, first add queues = try(local.variables.queues, []) to the module "subscriber" call in infra/sub/sub.generated.tf. Upgrading the Terraform module alone does not update this wrapper; without the argument, the YAML list is ignored and no queue Receiver grant is created.

Add the queue key (the map key from the API's servicebus_queues, not the full queue name) to infra/sub/vars.yml:

events:
  - topic: newuser
    subscription: it-func-yourapp-newuser-subscription
queues:
  - intake # key from the API's servicebus_queues
  • Deploy order: apply the API first. If the queue does not exist, the subscriber plan fails with a not-found error.
  • Name: derived as lower("{project_id}-{key}-queue") from project_id. Set project_id to your own API's project ID: it is a caller-supplied input, so the module does not verify ownership and cannot stop a mistaken or malicious value from pointing at another API's queue. Restrict who can change infra/sub/vars.yml (for example with CODEOWNERS) accordingly.
  • Access: the function app's managed identity gets Azure Service Bus Data Receiver scoped to the queue (.../namespaces/<namespace>/queues/<queue>). No Sender role is granted. Service Bus has no separate RBAC scope for a queue's dead-letter subqueue, so this grant also lets the function app receive dead-lettered messages. Don't also list the same identity in the API queue's dlq_reader_identities, which would create a duplicate role assignment and fail with RoleAssignmentExists. queues can't be combined with a custom namespace_id or namespace_name: API-owned queues live in the platform namespace.
  • Binding: the module does not add an app setting for the queue name. Use the {project_id}-{key}-queue name as a constant, ideally the shared one described in Keep the queue name in one place, like the topic and subscription names in the triggers below. The trigger argument must be a compile-time constant:
[Function("IntakeTrigger")]
public void Run(
    [ServiceBusTrigger(Queues.Intake, Connection = "sbnamespace")]
    ServiceBusReceivedMessage message)
{
    // ...
}

A %Setting% expression in a trigger is resolved by the Functions host from host configuration (app settings and local.settings.json), not from the worker's appsettings.json, so a queue name kept only in appsettings.json does not resolve and the function is disabled with does not resolve to a value.

๐Ÿ’ก Note: The function app identity is granted Receiver only on its own subscriptions and the queues listed here, never on the whole namespace. When upgrading an existing workspace, the old namespace-wide grant is replaced in the same apply, so triggers may briefly fail authorization (RBAC propagation can take several minutes) until the new grants take effect.

๐ŸŽฏ Create Event Handlers

You need to create a model and trigger function for each event type in your vars.yml.

Option A: Manual POCOs (Plain Old CLR Objects)

1. Define Event Models

Create one model per event type:

src/YourApp.Subscriptions/Models/NewUserEvent.cs:

using System.Text.Json.Serialization;

namespace YourApp.Subscriptions.Models;

public class NewUserEvent
{
  [JsonPropertyName("eventId")]
  public string EventId { get; set; } = string.Empty;

  [JsonPropertyName("userId")]
  public string UserId { get; set; } = string.Empty;

  [JsonPropertyName("email")]
  public string Email { get; set; } = string.Empty;
}

๐Ÿ’ก Tip: Use [JsonPropertyName] to match the exact property names from the event publisher.

2. Create Trigger Functions

Create one trigger per event type:

src/YourApp.Subscriptions/Triggers/NewUserTrigger.cs:

using Azure.Messaging.ServiceBus;
using Microsoft.Azure.Functions.Worker;
using Microsoft.Extensions.Logging;
using System.Text.Json;
using YourApp.Subscriptions.Models;

namespace YourApp.Subscriptions.Triggers;

public class NewUserTrigger(ILogger<NewUserTrigger> logger)
{
  [Function("NewUserTrigger")]
  public void Run(
      [ServiceBusTrigger("newuser", "it-func-yourapp-newuser-subscription", Connection = "sbnamespace")]
      ServiceBusReceivedMessage message)
  {
    logger.LogInformation("Processing user event: {MessageId}", message.MessageId);

    try
    {
      var userEvent = JsonSerializer.Deserialize<NewUserEvent>(message.Body.ToString());

      if (userEvent == null)
        throw new InvalidOperationException("Invalid message format");

      // YOUR BUSINESS LOGIC HERE
      logger.LogInformation("User: {UserId}, Email: {Email}",
        userEvent.UserId, userEvent.Email);
    }
    catch (Exception ex)
    {
      logger.LogError(ex, "Error processing message");
      throw; // Re-throw for retry
    }
  }
}

Key points:

  • Topic and subscription names must match vars.yml
  • Connection is always "sbnamespace" (unless using a custom namespace and implementation)
  • Throw exceptions to trigger retries
  • Repeat this pattern for each event type

Option B: Generate Models with Kiota

Instead of manually creating POCOs, you can generate type-safe models from OpenAPI specifications using Kiota.

Benefits

  • Type-safe models automatically generated from OpenAPI specs
  • Reduced manual maintenance and errors
  • Built-in JSON serialization/deserialization
  • Keeps models in sync with event schemas
  • Automatic regeneration on build when OpenAPI spec changes

Configure Kiota Reference

The template includes a commented-out KiotaReference in the .csproj file. To enable it:

  1. Open src/YourApp.Subscriptions/YourApp.Subscriptions.csproj

  2. Uncomment the KiotaReference section at the bottom of the file:

<ItemGroup>
  <KiotaReference Include="KiotaGenerated" OpenApi="https://openapi.saif.com/{event-service-project-id}/{environment}/{openapi-spec-file-name}.yaml">
    <NamespaceName>YourApp.Subscriptions</NamespaceName>
  </KiotaReference>
</ItemGroup>

Replace:

  • {event-service-project-id} with the event service's project ID (e.g., it-api-sys-testeventing)
  • {environment} with test, qa, uat or prod
  • {openapi-spec-file-name} with the spec filename (commonly openapi or openapi.v1)

KiotaReference item metadata such as NamespaceName maps to kiota generate options; see the SAIF.Platform.Kiota.HttpClientLibrary reference for the full property-to-option mapping, such as IncludePath for generating only some routes. ๐Ÿ’ก Tip: You can find the correct OpenAPI URL by checking the event service's documentation or asking the event service team.

  1. Remove or comment out the pre-created Models files:

The template creates a Models folder by default. Since Kiota will generate models in the KiotaGenerated/Models folder, you can either:

  • Delete the src/YourApp.Subscriptions/Models folder, or
  • Keep it for any custom models you want to create manually alongside the generated ones

  • Build the project to generate models:

cd src/YourApp.Subscriptions
dotnet build

The models will be automatically generated in the KiotaGenerated/Models folder during build.

Use Generated Models in Triggers

Create one trigger per event type:

src/YourApp.Subscriptions/Triggers/NewUserTrigger.cs:

using Azure.Messaging.ServiceBus;
using Microsoft.Azure.Functions.Worker;
using Microsoft.Extensions.Logging;
using Microsoft.Kiota.Serialization.Json;
using YourApp.Subscriptions.Models;

namespace YourApp.Subscriptions.Triggers;

public class NewUserTrigger(ILogger<NewUserTrigger> logger)
{
  [Function("NewUserTrigger")]
  public void Run(
      [ServiceBusTrigger("newuser", "it-func-yourapp-newuser-subscription", Connection = "sbnamespace")]
      ServiceBusReceivedMessage message)
  {
    logger.LogInformation("Processing user event: {MessageId}", message.MessageId);

    try
    {
      // Deserialize using Kiota's JsonParseNodeFactory
      using var stream = new MemoryStream(message.Body.ToArray());
      var parseNode = new JsonParseNodeFactory().GetRootParseNode("application/json", stream);
      var userEvent = parseNode.GetObjectValue(NewUserEvent.CreateFromDiscriminatorValue);

      if (userEvent == null)
        throw new InvalidOperationException("Invalid message format");

      // YOUR BUSINESS LOGIC HERE
      logger.LogInformation("User: {UserId}, Email: {Email}",
        userEvent.UserId, userEvent.Email);
    }
    catch (Exception ex)
    {
      logger.LogError(ex, "Error processing message");
      throw; // Re-throw for retry
    }
  }
}

Updating Models

When your OpenAPI spec changes, the models will be automatically regenerated on the next build. Simply run dotnet build and the KiotaReference in your .csproj file ensures models stay in sync with the OpenAPI spec without manual intervention.

๐Ÿ’ก Best Practice: Always use the latest published OpenAPI spec URL (e.g., from https://openapi.saif.com/...) to ensure your models match the current event schema.


Comparison: Manual vs. Kiota

Aspect Manual POCOs Kiota Generated (KiotaReference)
Setup Time Fast (write class) Fast (uncomment config in .csproj)
Maintenance Manual updates needed for each model Automatic regeneration on build
Type Safety Basic Enhanced with factories
Schema Validation None OpenAPI validation
Multiple Events Write each model separately All models generated automatically
Workflow Manual coding Build triggers generation
Best For Simple events, prototyping Multiple events, production, complex schemas

Integrating with Cosmos DB

If you need to interact with the event data in your application, storing the data in the API's Cosmos DB may be a viable solution. Here's a brief example of how to do that.

  1. Add Cosmos DB to your project if not already done. Follow Add Cosmos DB NoSQL guide on how to get it set up before proceeding to step 2.

  2. In the AppHost builder, make sure the subscription variable is created before the database variable, then add subscription as an argument to .AddCosmosDb():

...
var subscription = builder.AddSubscription();

var (cosmosdb, database) = builder.AddCosmosDb(backend, subscription);
...
  1. In the Subscription builder, add the Cosmos DB context for dependency injection:
...
builder
  .AddAzureDefaults()
  .AddServiceDefaults()
  .AddCosmosDbServices(); // ๐Ÿ‘ˆ Add this
...
  1. Create mappers to convert event models to the existing Cosmos DB entities. Here is an hand-written mapper example (you can also use libraries like AutoMapper, Mapperly, etc.):
public static class NewUserEventMapper
{
  public static Data.NewUserEvent ToEntity(this Models.NewUserEvent userEvent, string partitionKey)
  {
    return new Data.NewUserEvent
    {
      Id = userEvent.EventId,
      EventId = userEvent.EventId,
      UserId = userEvent.UserId,
      Email = userEvent.Email,
      PartitionKey = partitionKey
    };
  }
}
  1. In your trigger, inject the Cosmos DB context and use it in the function to save the event data:
public class NewUserEventTrigger(ILogger<NewUserEventTrigger> logger, EmmjohContext dbContext)
{
  [Function("NewUserTrigger")]
  public void Run(
      [ServiceBusTrigger("newuser", "it-func-yourapp-newuser-subscription", Connection = "sbnamespace")]
      ServiceBusReceivedMessage message, CancellationToken cancellationToken)
  {
    ...
    try {
      using var stream = new MemoryStream(message.Body.ToArray());
      var parseNode = await new JsonParseNodeFactory().GetRootParseNodeAsync("application/json", stream);
      var newUserEvent = parseNode.GetObjectValue(Models.NewUserEvent.CreateFromDiscriminatorValue);

      // Add to DbContext and save to Cosmos DB
      var entity = newUserEvent.ToEntity(partitionKey: newUserEvent.Email);
      dbContext.NewUserEvents.Add(entity);

      logger.LogInformation("Saving changes to Cosmos DB...");
      await dbContext.NewUserEvents.SaveChangesAsync(cancellationToken);

      logger.LogInformation("Successfully stored new user event {EventId} to Cosmos DB", newUserEvent.EventId);

      // Other business logic
      ...
    }
    ...
  }
}

๐Ÿงช Test Locally

  1. Run the AppHost (F5 in Visual Studio or dotnet run in terminal):

  2. Aspire dashboard opens showing:

  3. Service Bus emulator

  4. Your subscription function
  5. Service Bus seeder (runs automatically)
  6. Cosmos DB emulator (if integrating)
  7. Cosmos DB seeder (if integrating, may need to manually run depending on setup)

  8. Check logs for message processing:

[servicebus-seed] Seeded 5 messages to 'newuser' topic
[subscriptions] Processing user event: abc-123
[subscriptions] User: user123, Email: john@example.com

If integrating Cosmos DB, check logs for writing changes to the database:

[subscriptions] Saving changes to Cosmos DB...
[subscriptions] Executed CreateItem (284.6743 ms, 7.43 RU) ActivityId='52a0be67-604e-4a52-9133-173b942c1bb9', Container='NewUserEvents', Id='?', Partition='?'
[subscriptions] Successfully stored new user event abc-123 to Cosmos DB

Optional: Customize Test Data

Edit src/YourApp.ServiceBus.Seed/DataSeed.cs to send custom test messages. Add a seeding method for each event type you configured in vars.yml.

๐Ÿš€ Deploy

  1. Commit and push:
git add .
git commit -m "Add event subscription feature"
git push
  1. Run pipeline in Azure DevOps:
  2. Pipeline name: {project-id}-sub
  3. Example: it-api-exp-myapp-sub

The pipeline deploys:

  • Azure Function App
  • Service Bus subscriptions
  • Application Insights

  • Verify in Azure Portal:

  • Function App is running

  • Service Bus subscriptions exist
  • Functions appear in Function App

  • Monitor in Dynatrace:

  • All logs are automatically sent to Dynatrace
  • View structured logs with your event data
  • Monitor function performance and errors
  • Access at: Dynatrace Portal

๐Ÿ’ก Tip: Use structured logging (as shown in examples) for better Dynatrace integration. Log properties appear as filterable fields in Dynatrace.

๐Ÿ” Self-Service DLQ Access

You can grant Entra ID groups or user principals access to browse and manage dead-letter queue (DLQ) messages in Service Bus Explorer (Azure Portal) without requiring manual portal steps or platform team intervention.

Two Access Tiers

Tier Role Environments Capability
Readers Azure Service Bus Data Receiver Non-production only (enforced) Peek/receive DLQ messages in Service Bus Explorer
Managers Azure Service Bus Data Owner All environments including prod Peek, complete, dead-letter, and requeue messages

Data Receiver includes receive

The Azure Service Bus Data Receiver role is not peek-only โ€” it includes receive, which can consume/complete messages. Reader access is blocked in production by the saif-event-subscriber-service module when is_production = true โ€” even if a prod key appears in dlq_readers, no reader role assignments will be created.

Configuring DLQ Access

Configure dlq_readers and dlq_managers in your feature-event-subscription-dlq-vars.yaml file as maps keyed by environment short name. Each environment maps to a list of identity entries. Each entry requires a name (descriptive label) and either an object_id or group_name:

dlq_readers:
  test:
    - name: "Claims Dev Team"
      object_id: "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx"
  qa:
    - name: "Claims Dev Team"
      object_id: "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx"
    - name: "QA Testers"
      group_name: "Claims-QA-Readers"
  uat:
    - name: "QA Testers"
      group_name: "Claims-QA-Readers"
  # Reader access is always blocked in prod by the template.
  # You may omit the prod key here as a documentation convention, but it has no effect.

dlq_managers:
  test:
    - name: "Ops Team"
      group_name: "Claims-Ops"
  qa:
    - name: "Ops Team"
      group_name: "Claims-Ops"
  uat:
    - name: "Ops Team"
      group_name: "Claims-Ops"
  prod:
    - name: "Ops Team"
      group_name: "Claims-Ops"

The template automatically filters the list based on var.environment_short_name at plan time โ€” only identities for the current environment are passed to the module. For dlq_readers, production is always blocked regardless of what keys are present in the YAML. Don't list the function app's own managed identity in dlq_readers: it already holds Receiver on each of its subscriptions, so the plan fails with a precondition error. For dlq_managers, all environment keys including prod are applied as configured.

Field Description Required
name Descriptive label for the identity entry (used as the Terraform state key โ€” must be unique within the environment) Yes
object_id Entra ID object ID of a group or user principal One of these
group_name Display name of an Entra ID security group (looked up automatically; see constraints) is required

Group membership and group_name lookups

You manage membership of the groups you reference, and group_name matches only uniquely named Entra ID security groups. Prefer object_id; see Entra Security Groups for Access Grants for the lookup constraints and how to find an object ID.

New projects

Projects created with saif new saif-feature-event-subscription (or dotnet new) get feature-event-subscription-dlq-vars.yaml and feature-event-subscription-dlq.tf automatically โ€” no manual steps needed.

Existing projects (created before this feature)

If your project was created before DLQ access support was added, add these three files manually:

1. Create infra/sub/feature-event-subscription-dlq-vars.yaml:

dlq_readers:
  test: []
  qa: []
  uat: []

dlq_managers:
  test: []
  qa: []
  uat: []
  prod: []

2. Create infra/sub/feature-event-subscription-dlq.tf:

locals {
  feature_event_subscription_dlq_vars_yaml = file("${path.module}/feature-event-subscription-dlq-vars.yaml")
  feature_event_subscription_dlq_vars_data = yamldecode(local.feature_event_subscription_dlq_vars_yaml)

  # Production blocking is enforced by the saif-event-subscriber-service module via is_production.
  feature_event_subscription_dlq_readers = {
    for r in try(local.feature_event_subscription_dlq_vars_data["dlq_readers"][var.environment_short_name], []) :
    r["name"] => {
      object_id  = try(r["object_id"], null)
      group_name = try(r["group_name"], null)
    }
  }

  feature_event_subscription_dlq_managers = {
    for r in try(local.feature_event_subscription_dlq_vars_data["dlq_managers"][var.environment_short_name], []) :
    r["name"] => {
      object_id  = try(r["object_id"], null)
      group_name = try(r["group_name"], null)
    }
  }
}

3. Add DLQ identity parameters to your module "subscriber" call in sub.generated.tf:

is_production           = var.is_production
dlq_reader_identities   = local.feature_event_subscription_dlq_readers
dlq_manager_identities  = local.feature_event_subscription_dlq_managers

Browsing DLQ Messages in the Azure Portal

Once your role assignment is deployed, navigate to the subscription in the Azure Portal:

Azure Portal โ†’ Service Bus namespace โ†’ Topics โ†’ select topic โ†’ Subscriptions โ†’ select subscription โ†’ Service Bus Explorer โ†’ Dead-letter tab

Switch to Microsoft Entra authentication

SAIF Service Bus namespaces have local (SAS key) authentication disabled. The Service Bus Explorer defaults to SAS key mode and will show an error banner. You must click "Switch to Microsoft Entra authentication" in the top-right of the explorer before you can peek or receive messages.

This is a one-time click per browser session โ€” it is a portal UI preference and cannot be automated.

After switching, use Peek from start or Peek next messages to browse DLQ messages without consuming them. Receive mode will consume the message from the DLQ โ€” use it only if you intend to remove the message.

๐Ÿ”ง Troubleshooting

Messages not being received

  • โœ… Verify subscription exists in Azure Portal
  • โœ… Check Function App is running (view in Dynatrace)
  • โœ… Ensure topic names match exactly

Deserialization errors

  • โœ… Check JsonPropertyName attributes match publisher schema
  • โœ… View error logs in Dynatrace with full stack traces
  • โœ… Log raw message to see actual JSON:
    logger.LogInformation("Raw: {Body}", message.Body.ToString());
    

Local testing: Service Bus not starting

  • โœ… Ensure Docker Desktop is running
  • โœ… Restart Docker Desktop
  • โœ… Re-run AppHost

Deployment fails

  • โœ… Check pipeline logs in Azure DevOps
  • โœ… Verify vars.yml syntax is correct
  • โœ… Ensure all required variables are set

Function App deploy fails: service_plan_id is required

Terraform fails with The argument "service_plan_id" is required, but no definition was found against azurerm_linux_function_app. Your team's opt-in Elastic Premium Functions plan hasn't been enabled yet. For the full symptom, cause, and fix, see Function App deploy fails: service_plan_id is required.

Messages in dead letter queue

  • โœ… Check Dynatrace for exception logs and traces
  • โœ… Verify event model matches message schema
  • โœ… Filter Dynatrace logs by MessageId for detailed investigation
  • โœ… Configure DLQ access to browse dead-letter messages in Service Bus Explorer

Viewing Logs and Monitoring

All function logs are automatically sent to Dynatrace:

  • Filter by function name, severity, or custom properties
  • View distributed traces across services
  • Set up alerts for errors or performance issues
  • Access: Dynatrace Portal

๐Ÿ“š Resources