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
- ๐ Useful Resources
- ๐ Prerequisites
- โก Step 1: Create Your Project
- ๐๏ธ Step 2: Configure Security Keys
- ๐ป Step 3: Define Your Events with TypeSpec
- ๐ Step 4: Deploy Your Event Service
- ๐ค Publish from a Forge API
- โ๏ธ Tune Topic Settings
- ๐ญ Find Telemetry for Published Events
- ๐ง Troubleshooting
- ๐ Related Documentation
๐ 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¶
- SAIF CLI Documentation
- TypeSpec Documentation
- TypeSpec Official Documentation
- Azure API Management Documentation
- Azure Service Bus Documentation
๐ 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:
Parameters:
--name: Your application name (will be used in project naming)--owner: The team or individual responsible for the service
๐ก Example¶
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 ininfra/event/openapi/src/SAIF.[AppName].TypeSpec/: the TypeSpec project that defines your API operations and event models.azdo/vars/event-service.yml: pipeline variables, includingsecretsVariableGroupName
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.
๐ Generate and Configure Primary Key (Recommended)¶
If you need to generate primary keys, follow the character and length requirements in Generate Keys.
- Configure Azure DevOps Variable Group:
- Navigate to Azure DevOps โ Pipelines โ Library
- 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. - Add a different primary key for each environment.
- Optionally add a
secondary_keyfor 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?¶
- Your keys are stored securely in Azure DevOps for the deployment pipeline to use
- 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¶
๐๏ธ 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โUserCreatedtopic) - ๐ The
@useAuthdecorator makes subscription keys mandatory for all operations - โก The
@autoRoutedecorator creates REST endpoints from your interface
๐ Build and Validate¶
โ 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?¶
- Your TypeSpec is compiled into OpenAPI specifications
- These specs define your API structure for the deployment pipeline
- 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.
- Navigate to Azure DevOps Pipelines
- 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:
๐งช 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?¶
- Your event service is live and ready to receive requests from the API
- Share your OpenAPI specs with teams that need to consume your events
- Monitor your Service Bus topics for incoming events
- 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.
-
Add the caller's project ID to
infra/event/vars.ymlin the event service repo: -
Deploy the event service. Each entry is granted Azure Service Bus Data Sender on the selected topics only, never the whole namespace.
-
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_idresolves 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
EventTypeapplication property yourself, as APIM does fromX-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:
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:
Topic names are the same in every environment, so set them in appsettings.json:
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/:
-
In
event.generated.tf, confirm theevent_servicemoduleversionconstraint allows a release that includesauthorized_apps, then pass the new input: -
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 } -
In
vars.yml, addauthorized_apps: [](or your entries). Omitting it is also safe because of thetry(..., [])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:
- Pause publishers.
- Drain or triage outstanding messages, including each subscription's dead-letter queue.
- Apply the event service.
- Reapply every affected subscriber workspace so the subscriptions are recreated.
- 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.
-
Find the gateway log entry. The entry is a
GatewayLogsrecord 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 descFrom the CLI:
saif otel logs <any-service> --env test --query '<the DQL above>'. Narrow further with theeventIdyou sent. -
Read the identifiers from the entry.
Field in the log entry What it is traceRecords[].metadata.eventIdThe eventIdyou sent, also the Service BusMessageIdtraceRecords[].metadata.requestIdand theX-Request-Idresponse headerAPIM request id requestHeaders.X-Correlation-IdThe correlation id you sent backendRequestHeaders.BrokerPropertiesMessageIdandCorrelationIdsent to Service BusbackendRequestHeaders.Diagnostic-IdTrace context passed to the subscriber -
Find the subscriber's trace. The trace ID is the
requestIdwith the dashes removed (or the trace ID inside your owntraceparent). Dynatrace stores spantrace.idas a UID, so a plain string comparison matches nothing; convert it withtoUid. In the Distributed Tracing app, filter on that trace ID, or run:The root is the subscriber's
Invokespan, with the calls the handler makes below it. -
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_keysecret to Azure DevOps variable group - Check: Variable group name exactly matches
secretsVariableGroupNamein.azdo/vars/event-service.yml - Verify: Use environment-specific naming:
[TEST]primary_key, ...,[PROD]primary_key
โ API calls return 401 Unauthorized¶
- Solution: Follow 401 SubscriptionKeyInvalid to check the key value and header
โ 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 installand verify TypeSpec syntax follows SAIF platform conventions
๐ Related Documentation¶
- Event Orchestration Example - Working example of the saga pattern for distributed event-driven transactions