Skip to content

Event Service

This guide provides step-by-step instructions for creating a new APIM API to publish events to Azure Service Bus Topics using the SAIF platform templates.

Aspire Publish Alternative

Starting in Forge 3.3, if your project uses an Aspire AppHost, you can register event services with builder.AddEventService("events") from the SAIF.Platform.Aspire.Hosting package and generate pipeline YAML automatically. See Aspire Publish for details.

๐Ÿ”€ Choose a Publish Path

Caller Has an Entra identity? Publish path
On-prem APIs and apps (for example Guidewire) No APIM event API with an Ocp-Apim-Subscription-Key (Steps 2-4)
Forge APIs running in Azure Yes Service Bus SDK straight to the topic, authorized with authorized_apps (Publish from a Forge API)

๐Ÿ“š Useful Resources

๐Ÿ“‹ Prerequisites

  • โœ… SAIF CLI and TypeSpec installed and updated
  • โœ… Visual Studio Code with TypeSpec extension
  • โœ… Access to SAIF Azure DevOps organization
  • โœ… Permissions for creating pipelines and Azure resources

โšก Step 1: Create Your Project

To create a new event service project, run the following command in your project root directory. Pass the parameters upfront to skip the interactive prompts:

saif new saif-event-service --name <your-app-name> --owner <owner-name>

Parameters:

  • --name: Your application name (will be used in project naming)
  • --owner: The team or individual responsible for the service

๐Ÿ’ก Example

saif new saif-event-service --name myapp --owner Platform
cd <your-project-name>

This creates an event service with:

  • Project ID: events-myapp (automatically generated from "events" + name)
  • Application Name: myapp
  • Owner: Platform

The project follows the generated project layout shared by service templates. The event service adds:

  • infra/event/: Terraform for the APIM API and Service Bus topics, with generated OpenAPI specifications in infra/event/openapi/
  • src/SAIF.[AppName].TypeSpec/: the TypeSpec project that defines your API operations and event models
  • .azdo/vars/event-service.yml: pipeline variables, including secretsVariableGroupName

After generation, proceed to Step 2 to configure security keys.

๐Ÿ—๏ธ Step 2: Configure Security Keys

๐Ÿ”‘ What You Need to Provide

Your event service API requires subscription key authentication to protect your Service Bus topics. You need to bring a primary key for each environment (TEST, QA, UAT, PROD) that will serve as the authentication token for consuming applications.

โš ๏ธ Required: You must provide primary keys for each environment before deployment, or the infrastructure deployment will fail.

If you need to generate primary keys, follow the character and length requirements in Generate Keys.

  1. Configure Azure DevOps Variable Group:
  2. Navigate to Azure DevOps โ†’ Pipelines โ†’ Library
  3. There should already be a group created by the SAIF CLI named after your project ID (e.g., events-myapp), with the environment-specific variables pre-defined.
  4. Add a different primary key for each environment.
  5. Optionally add a secondary_key for each environment (for example [QA]secondary_key). When omitted, API Management generates the secondary key.

โš ๏ธ Critical: If you rename or use a different variable group, its name must match the secretsVariableGroupName value in your .azdo/vars/event-service.yml file.

๐Ÿ” Enable Crypto Registration (Optional)

If legacy .NET callers need to retrieve the subscription key and API base URL at runtime from the Environment Service, add the cryptoRegistration parameter to both .azdo/azure-pipelines.yml and .azdo/azure-pipelines-pr.yml:

extends:
  template: event-service.yml@templates
  parameters:
    # ...existing parameters
    cryptoRegistration:
      enabled: true
      systemName: 'events-myapp'   # Name of the Crypto system
      systemType: 'webapp'
      allowedSystems:              # Optional: other callers allowed to decrypt the keys
        - name: 'CCClaimDataApi'
          type: 'webapp'

After each deployment, the pipeline registers the keys in the Crypto API and stores primary_subscription_key and api_base_url in the Environment Service. secondary_subscription_key is stored only when you configure secondary_key in the variable group; APIM's generated secondary key is not registered. Only systemName can decrypt the keys unless a caller is listed in allowedSystems, and every other system is revoked on each deploy. See Enable Crypto Registration for parameters and Allow Additional Callers to Retrieve the Keys before adding entries.

โœ… Success Indicators

After configuring security keys, you should have:

  • โœ… Variable group created in Azure DevOps Library
  • โœ… Primary keys added for TEST, QA, UAT, and PROD environments (marked as secret)

๐ŸŽฏ What Happens Next?

  1. Your keys are stored securely in Azure DevOps for the deployment pipeline to use
  2. Proceed to Step 3 to define your event structure with TypeSpec

๐Ÿ“ Note: All SAIF event service APIs use mandatory subscription key authentication. See Call the API for the header callers send.

๐Ÿ’ป Step 3: Define Your Events with TypeSpec

๐ŸŽฏ What is TypeSpec?

TypeSpec is a language for defining APIs and data models. It will automatically generate the OpenAPI specifications that configure your event service. Think of it as describing what your events look like so the system can create the right APIs.

๐Ÿ“‚ Open Your TypeSpec Project

cd src/SAIF.[YourAppName].TypeSpec
code .  # Opens in Visual Studio Code

๐Ÿ—๏ธ Understanding the TypeSpec Template

Here's what a complete TypeSpec service looks like with explanations:

import "@typespec/http";
import "@typespec/rest";
import "@typespec/openapi";
import "@typespec/openapi3";
import "@typespec/versioning";
import "@saif/platform-typespec";

using TypeSpec.Http;
using TypeSpec.Rest;
using SAIF.Platform;

@service({
  title: "Your Event Service",        // ๐Ÿ‘ˆ This appears in your API documentation
  version: "1.0"                    // ๐Ÿ‘ˆ Version your API for consumers
})
@useAuth(ApiKeyAuth<ApiKeyLocation.header, "Ocp-Apim-Subscription-Key">)  // ๐Ÿ‘ˆ Requires subscription key
namespace YourEventService;

// ๐Ÿ‘‡ Automatically creates REST endpoints
@autoRoute
interface UserCreatedTopic extends Topic<UserCreatedEvent> {}

// ๐Ÿ‘‡ Define your event structure - customize this for your use case
model UserCreatedEvent is Event<"UserCreated"> {
  userId: string;          // Required field
  email: string;           // Required field
  firstName?: string;      // Optional field (note the ?)
  lastName?: string;       // Optional field
}

Key Concepts:

  • ๐ŸŽฏ Each event type maps to one Service Bus topic (e.g. UserCreatedTopic โ†’ UserCreated topic)
  • ๐Ÿ” The @useAuth decorator makes subscription keys mandatory for all operations
  • โšก The @autoRoute decorator creates REST endpoints from your interface

๐Ÿ”„ Build and Validate

npm install    # Install dependencies
npm run build  # Validate and generate OpenAPI specs

โœ… Success Indicators

After building your TypeSpec definitions, you should see:

  • โœ… No compilation errors in the terminal
  • โœ… OpenAPI files generated in the openapi/ folder
  • โœ… TypeSpec validation passes without warnings

๐ŸŽฏ What Happens Next?

  1. Your TypeSpec is compiled into OpenAPI specifications
  2. These specs define your API structure for the deployment pipeline
  3. Proceed to Step 4 to deploy your event service

๐Ÿš€ Step 4: Deploy Your Event Service

๐ŸŽฏ What This Step Does

The deployment pipeline will take your TypeSpec definitions and security keys to create a fully functional event service in Azure, including the API endpoints and Service Bus topics.

  1. Navigate to Azure DevOps Pipelines
  2. Run the events-<project-name> pipeline (e.g., events-myapp)

The pipeline will:

  • โœ… Compile TypeSpec and generate OpenAPI specifications
  • โœ… Deploy OpenAPI specifications to a dedicated OpenAPI storage account
  • โœ… Deploy APIM API with auto-generated operations
  • โœ… Create Service Bus Topics for event publishing
  • โœ… Configure security policies and activate subscription keys

โœ… Success Indicators

A successful deployment should show:

  • โœ… All pipeline stages completed without errors
  • โœ… Green checkmarks for each deployment environment
  • โœ… No failed tasks in the pipeline logs

๐ŸŒ Access Your OpenAPI Specifications

After deployment, specifications are available at:

https://openapi.saif.com/<project-id>/<environment>/openapi.v<version-number>.yaml

๐Ÿงช Test Your API

Publish a test event to a topic. The route is /api/event/<api-name>/<topic-name> on app-int-<environment>.saif.com, and X-Event-Type names the event. The subscription key header follows the subscription key calling convention.

curl -X POST "https://app-int-test.saif.com/api/event/events-myapp/UserCreated" \
  -H "Ocp-Apim-Subscription-Key: 1234-45678" \
  -H "Content-Type: application/json" \
  -H "X-Event-Type: UserCreated" \
  -d '{"eventId": "7c9e6679-7425-40de-944b-e07fc1f90ae7", "userId": "123", "email": "user@example.com"}'

eventId is required

Every event must include an eventId you generate, unique per event, 1-128 characters (the Service Bus MessageId limit). The service returns it unchanged and sets it as the Service Bus MessageId, so you can match a publish to its delivery in the subscriber and dead-letter queue. An empty or longer eventId, or an X-Correlation-Id over 128 characters, is rejected with a 400 before anything is sent.

๐ŸŽฏ What Happens Next?

  1. Your event service is live and ready to receive requests from the API
  2. Share your OpenAPI specs with teams that need to consume your events
  3. Monitor your Service Bus topics for incoming events
  4. Distribute subscription keys securely to authorized consuming teams

๐Ÿ“Š Visual Flow

TypeSpec Definition โ†’ OpenAPI Specs โ†’ APIM API โ†’ Service Bus Topics โ†’ Event Consumers
     (Step 3)           (Pipeline)     (Azure)         (Azure)         (Your Teams)

๐Ÿ“ค Publish from a Forge API

Forge APIs running in Azure should not use the subscription key. List them in authorized_apps and they publish with their own identity, with no key to store or rotate.

Projects created before this feature need the one-time changes below first.

  1. Add the caller's project ID to infra/event/vars.yml in the event service repo:

    authorized_apps:
      - project_id: pol-api-exp-policyportal   # all topics
      - project_id: cl-api-proc-claimsync
        topics:                                # optional: restrict to specific topics
          - ClaimCreated
    
  2. Deploy the event service. Each entry is granted Azure Service Bus Data Sender on the selected topics only, never the whole namespace.

  3. Configure the caller's app settings with the namespace and topic name, then send from the caller:

    await using var client = new ServiceBusClient(
        builder.Configuration["EventService:Namespace"], new DefaultAzureCredential());
    var sender = client.CreateSender(builder.Configuration["EventService:ClaimCreatedTopic"]);
    
    var message = new ServiceBusMessage(JsonSerializer.Serialize(evt))
    {
        ContentType = "application/json",
        MessageId = evt.EventId,          // lets you find this event in the subscriber and DLQ
        CorrelationId = correlationId,
    };
    message.ApplicationProperties["EventType"] = "ClaimCreated";
    
    await sender.SendMessageAsync(message);
    

Notes:

  • Each project_id resolves to the caller's app registration service principal, {project_id}-{environment_short_name}. Deploy the caller's identity first, or the lookup fails.
  • Topic names are matched case-insensitively. An unknown topic fails the plan and lists the valid topics.
  • Publishing through the SDK skips APIM's OpenAPI validation. Set the EventType application property yourself, as APIM does from X-Event-Type.
  • Prefer registering the client with AddAzureServiceBusClient (Aspire) so it is created once and shared.
  • On-prem callers are unaffected and keep using the APIM subscription key path.

Trace SDK publishes

The Service Bus SDK propagates trace context on every message, but its spans are still experimental. To see ServiceBusSender.Send spans under your service name in Dynatrace, enable them before the first Service Bus client is created, for example at the top of Program.cs:

AppContext.SetSwitch("Azure.Experimental.EnableActivitySource", true);

The switch controls whether the SDK emits its own ServiceBusSender.Send spans. The SDK stamps each message with the sender's trace context (Diagnostic-Id) from the current activity either way, so publishing inside an existing request keeps the subscriber on the same trace. The switch is what makes the Send spans show up under your service name. Match a publish to its delivery with MessageId or CorrelationId.

Configure the sender app settings

Put the namespace and topic names in the caller's appsettings.json files, not in Terraform settings.yml (deprecated for API apps; see Settings and Secrets). Neither value is a secret.

The namespace is shared by every event service in an environment and follows saif-{env}-corp.servicebus.windows.net. The event service is internal only, so there is no external namespace. Set it per environment in appsettings.{env}.json:

appsettings.test.json
{
  "EventService": {
    "Namespace": "saif-test-corp.servicebus.windows.net"
  }
}

Topic names are the same in every environment, so set them in appsettings.json:

appsettings.json
{
  "EventService": {
    "ClaimCreatedTopic": "claimcreated"
  }
}

Create one appsettings.{env}.json per deployed environment (test, qa, uat, prod), replacing {env} in the namespace. The servicebus_topic_names output lists the valid topic names. The caller needs no connection string: DefaultAzureCredential authenticates as the app registration service principal ({project_id}-{environment_short_name}), and the Data Sender role granted to it through authorized_apps controls access.

Add authorized_apps to an existing project

The template does not update existing repos. Make these changes once in infra/event/:

  1. In event.generated.tf, confirm the event_service module version constraint allows a release that includes authorized_apps, then pass the new input:

    module "event_service" {
      # ...existing arguments
      authorized_apps = try(local.variables.authorized_apps, [])
    }
    
  2. In outputs.tf, add the outputs callers need:

    output "servicebus_namespace_fqdn" {
      description = "Service Bus namespace host name for authorized_apps publishers."
      value       = module.event_service.servicebus_namespace_fqdn
    }
    
    output "servicebus_topic_names" {
      description = "Topic names that authorized_apps publishers send to."
      value       = module.event_service.servicebus_topic_names
    }
    
  3. In vars.yml, add authorized_apps: [] (or your entries). Omitting it is also safe because of the try(..., []) fallback.

Without step 1 the setting is silently ignored. Existing deployments are otherwise unchanged until you list an app.

โš™๏ธ Tune Topic Settings

Topics accept optional message TTL and duplicate detection settings. Omit them to keep the current behavior. The template does not pass them by default; add the ones you need to the event_service module in infra/event/event.generated.tf:

module "event_service" {
  # ...existing arguments
  default_message_ttl                     = try(local.variables.default_message_ttl, null)
  requires_duplicate_detection            = try(local.variables.requires_duplicate_detection, false)
  duplicate_detection_history_time_window = try(local.variables.duplicate_detection_history_time_window, "PT10M")
}

Then set values in vars.yml:

default_message_ttl: P7D
requires_duplicate_detection: true
duplicate_detection_history_time_window: PT1H
Setting Default Description
default_message_ttl Unset (Azure Service Bus default, effectively unlimited) ISO 8601 time-to-live for messages on every topic. Subscriptions can set a shorter value with default_message_ttl.
requires_duplicate_detection false Drop a message whose MessageId was already accepted within the history window.
duplicate_detection_history_time_window PT10M ISO 8601 window for duplicate detection, from 20 seconds to 7 days. Only applies when duplicate detection is on.

Duplicate detection is create-only

Azure cannot change duplicate detection on an existing topic, so changing requires_duplicate_detection in either direction recreates every topic in the service. Recreating a topic deletes its subscriptions and all live and dead-lettered messages. The subscriptions are managed by saif-event-subscriber-service, so applying the event service alone leaves consumers disconnected. To roll it out safely:

  1. Pause publishers.
  2. Drain or triage outstanding messages, including each subscription's dead-letter queue.
  3. Apply the event service.
  4. Reapply every affected subscriber workspace so the subscriptions are recreated.
  5. Verify delivery end to end, then resume publishing.

The APIM route sets the MessageId to your eventId, so a repeated eventId inside the window is dropped silently. The API still returns 201, and the subscriber never sees the duplicate. Use a new eventId for each distinct event. Apps that publish with the Service Bus SDK through authorized_apps are deduplicated on the MessageId they set, so give each distinct message its own MessageId too.

๐Ÿ”ญ Find Telemetry for Published Events

Event services have no app, so the APIM route produces no spans. What you see depends on how the event was published.

APIM route (legacy and on-prem apps) Service Bus SDK (Forge apps)
Publisher side One gateway log entry in the shared APIM logs, no span ServiceBusSender.Send span under the caller's service name (requires the switch above)
Message identity MessageId = your eventId; CorrelationId = X-Correlation-Id The MessageId and CorrelationId you set
Trace context to the subscriber Diagnostic-Id from your traceparent, or generated from the APIM request id when you send none Set by the SDK
Subscriber side Invoke span and function logs in the subscriber's service Same
Join key Trace ID (see below) or eventId Trace ID or MessageId

The APIM route correlates by shared trace ID, not by a connected span tree. APIM exports no span, so the trace starts at the subscriber's Invoke span. Service Bus trigger and topic details appear in the function's logs, not the trace.

Request and response bodies are never logged, because application teams own the event schemas and APIM cannot redact fields inside a body. The APIM route returns your own eventId unchanged.

Follow an APIM-published event end to end

The values below use the --env test environment; replace <api-name> and <topic> with your event service and topic.

  1. Find the gateway log entry. The entry is a GatewayLogs record in the shared APIM's logs. Use a Dynatrace Notebook (DQL section) or Logs & Events Classic in advanced mode:

    fetch logs, from:now()-3h
    | filter contains(content, "GatewayLogs") and contains(content, "<api-name>")
    | sort timestamp desc
    

    From the CLI: saif otel logs <any-service> --env test --query '<the DQL above>'. Narrow further with the eventId you sent.

  2. Read the identifiers from the entry.

    Field in the log entry What it is
    traceRecords[].metadata.eventId The eventId you sent, also the Service Bus MessageId
    traceRecords[].metadata.requestId and the X-Request-Id response header APIM request id
    requestHeaders.X-Correlation-Id The correlation id you sent
    backendRequestHeaders.BrokerProperties MessageId and CorrelationId sent to Service Bus
    backendRequestHeaders.Diagnostic-Id Trace context passed to the subscriber
  3. Find the subscriber's trace. The trace ID is the requestId with the dashes removed (or the trace ID inside your own traceparent). Dynatrace stores span trace.id as a UID, so a plain string comparison matches nothing; convert it with toUid. In the Distributed Tracing app, filter on that trace ID, or run:

    fetch spans
    | filter trace.id == toUid("<trace id>")
    

    The root is the subscriber's Invoke span, with the calls the handler makes below it.

  4. Find the subscriber's logs. Search the subscriber's function logs for the eventId. The trigger line (Trigger Details: MessageId: <eventId>, SequenceNumber: ...) shows the delivery and delivery count.

Follow an SDK-published event

Find the caller's ServiceBusSender.Send span with saif otel traces <caller-project-id> --env test, take its trace ID, and filter on it in the Distributed Tracing app as in step 3. Search the subscriber's logs by MessageId.

๐Ÿ”ง Troubleshooting

โŒ Deployment fails with "primary_key not found"

  • Solution: Add primary_key secret to Azure DevOps variable group
  • Check: Variable group name exactly matches secretsVariableGroupName in .azdo/vars/event-service.yml
  • Verify: Use environment-specific naming: [TEST]primary_key, ..., [PROD]primary_key

โŒ API calls return 401 Unauthorized

โŒ API calls return 403 Forbidden

  • Solution: Verify Service Bus topic exists and is not disabled
  • Check: Ensure topic has not been disabled due to quota limits or administrative action

โŒ TypeSpec compilation errors

  • Solution: Run npm install and verify TypeSpec syntax follows SAIF platform conventions