---
title: Event Service
description: Create an APIM API that publishes events to Azure Service Bus topics.
moved_from:
  - guides/development/eventing/event-service.md
---

# 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.

!!! tip "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](../deploy/aspire-publish.md) for details.

[TOC]

## 🔀 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](#publish-from-a-forge-api)) |

## 📚 Useful Resources

- [SAIF CLI Documentation](../../learn/install-saif-cli.md)
- [TypeSpec Documentation](../apis/typespec.md)
- [TypeSpec Official Documentation](https://typespec.io/)
- [Azure API Management Documentation](https://docs.microsoft.com/en-us/azure/api-management/)
- [Azure Service Bus Documentation](https://docs.microsoft.com/en-us/azure/service-bus-messaging/)

## 📋 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](../../learn/project-templates.md#provide-parameters-upfront):

```bash
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

```bash
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](../../learn/project-templates.md#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.

### 🔑 Generate and Configure Primary Key (Recommended)

If you need to generate primary keys, follow the character and length requirements in [Generate Keys](../identity/configuration/subscription-key-auth.md#generate-keys).

1. **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_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`:

```yaml
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](../identity/configuration/subscription-key-auth.md#enable-crypto-registration) for parameters and [Allow Additional Callers to Retrieve the Keys](../identity/configuration/subscription-key-auth.md#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](../identity/configuration/subscription-key-auth.md#step-5-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

```bash
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:

```typescript
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

```bash
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](../identity/configuration/subscription-key-auth.md#step-5-call-the-api).

```bash
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"}'
```

!!! note "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](#add-authorized_apps-to-an-existing-project) first.

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

    ```yaml
    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](#configure-the-sender-app-settings) with the namespace and topic name, then send from the caller:

    ```csharp
    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`:

```csharp
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](../config/settings-and-secrets.md)). 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`:

```json title="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`:

```json title="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:

    ```hcl
    module "event_service" {
      # ...existing arguments
      authorized_apps = try(local.variables.authorized_apps, [])
    }
    ```

2. In `outputs.tf`, add the outputs callers need:

    ```hcl
    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`:

```hcl
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`:

```yaml
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`](event-subscription.md#tune-subscription-settings). |
| `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. |

!!! warning "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](#trace-sdk-publishes)) |
| 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

- **Solution**: Follow [401 SubscriptionKeyInvalid](../identity/configuration/subscription-key-auth.md#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 install` and verify TypeSpec syntax follows SAIF platform conventions

---

## 📚 Related Documentation

- [Event Orchestration Example](../examples/event-orchestration.md) - Working example of the saga pattern for distributed event-driven transactions
