---
id: notification-api
name: Notification API
version: 1.0.0
summary: |
  Internal background worker that consumes order commands from Kafka, renders
  MJML email templates, and submits mail over SMTP via MailKit.
owners:
  - platform-engineering-team
badges:
  - content: Internal
    backgroundColor: gray
    textColor: gray
  - content: Event-driven
    backgroundColor: orange
    textColor: orange
styles:
  icon: /icons/languages/dotnet.svg
receives:
  - id: PlaceOrderCommand
    version: 1.0.0
    group: Order Email Requests
    from:
      - id: bookworm.{env}.finance.place-order
        version: 1.0.0
  - id: CancelOrderCommand
    version: 1.0.0
    group: Order Email Requests
    from:
      - id: bookworm.{env}.finance.cancel-order
        version: 1.0.0
  - id: CompleteOrderCommand
    version: 1.0.0
    group: Order Email Requests
    from:
      - id: bookworm.{env}.finance.complete-order
        version: 1.0.0
specifications:
  - type: asyncapi
    path: asyncapi-v1.yml
    name: AsyncAPI V1
repository:
  language: C#
  url: "https://github.com/foxminchan/BookWorm"
---

## Service Responsibility & Boundary

Notification API is an internal background worker within the [[domain|platform]] domain that consumes order lifecycle commands from [[service|order-orchestration]] over Kafka, renders MJML email templates, and submits MIME messages over SMTP to [[service|sendgrid-api]] (or a local test inbox in development). It owns no relational database, maintains no email outbox, and publishes no reply events—calling domains retain full ownership of business outcomes.

## Service Profile

| Property                                  | Value                                                                                                                                                                                        |
| :---------------------------------------- | :------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| **Bounded Context / Domain**              | [[domain\|platform]]                                                                                                                                                                         |
| **Owner Team**                            | [[team\|platform-engineering-team]]                                                                                                                                                          |
| **Runtime Style**                         | Async Worker (Kafka Consumer & SMTP Client)                                                                                                                                                  |
| **Public / Gateway Exposure**             | Internal Only (not routed via API Gateway)                                                                                                                                                   |
| **Authentication & Authorization Policy** | Internal worker; Azure Managed Identity for cache access and runtime secret configuration for SMTP credentials                                                                               |
| **Owned Data Store(s)**                   | Redis (24-hour message-ID deduplication cache) — no SQL database or outbox                                                                                                                   |
| **Key Resilience / Idempotency Pattern**  | 24-hour message-ID idempotency guard, bounded SMTP retry pipeline, Kafka listener cooldowns, and dead-letter routing on [[channel\|bookworm.&#123;env&#125;.notification.dead-letter-queue]] |

## Contracts & Data Ownership

Notification API consumes [[command|PlaceOrderCommand]], [[command|CompleteOrderCommand]], and [[command|CancelOrderCommand]] partitioned by Order ID. Blank recipient email addresses are skipped safely without error or retry.

:::warning
SMTP acceptance from the mail provider confirms only submission—not inbox arrival—and Notification does not ingest bounce or delivery webhooks. Additionally, because [[service|order-orchestration]] retries [[command|PlaceOrderCommand]] with a new message ID on basket-cleanup timeouts, retries can send an additional placement email.
:::

<MessageTable format="all" limit={10} showChannels={true} />

<Accordion title="Privacy & Retry Semantics">
	- **PII minimization:** Email credentials reside in runtime secrets, recipient metadata is
	redacted in structured logs, and rendered HTML bodies are never logged. - **Dead-letter routing:**
	Transient SMTP failures trigger client retries followed by Kafka listener backoff; exhausted
	messages route to [[channel|bookworm.&#123;env&#125;.notification.dead-letter-queue]].
</Accordion>

## Architecture Visualizations & Specifications

### Notification Delivery Context

<MermaidFileLoader file="mermaids/NotificationAPI-diagram-1.mmd" />

### Service Interactions

<NodeGraph />

## Attached Resources & Related Docs

- [[doc|platform/006-api-and-contracts]] — Consolidated service, HTTP, gRPC, and Kafka contract directory.
- [[service|sendgrid-api]] — External SMTP email delivery boundary.
- [[service|order-orchestration]] — Upstream Finance workflow producing order email commands.
- [[flow|notification-delivery]] — End-to-end notification rendering and submission flow.


 ## Raw Schema:asyncapi-v1.yml

asyncapi: 3.1.0
info:
  title: Notification service integration messages
  version: 1.0.0
  description: |
    Kafka consumer contract for the BookWorm Notification host. Finance publishes
    order-placement, cancellation, and completion commands. Notification does
    not publish application-level acknowledgment, delivery, or failure events.

    Payload schemas describe camelCase JSON data inside BookWorm's
    CloudEvents-compatible envelope, not the complete transport envelope.
    Message identities are the BookWorm.Contracts types shown below.
    Topic names come from IntegrationMessageOwner and KafkaTopicRouter.

    Order handlers skip null, empty, or whitespace-only email addresses. Otherwise
    they render Orders/OrderEmail via MjmlTemplateRenderer and submit through
    MailKit over SMTP with a configured resilience pipeline. Development uses
    MailPit; other environments use the configured email provider. SMTP
    acceptance is not confirmation of final recipient delivery.

    A missing broker connection disables event-bus registration. Exhausted
    listener retries use the native dead-letter topic
    bookworm.{env}.notification.dead-letter-queue. Repeated commands, including
    Finance's placement retries, can produce duplicate emails.
defaultContentType: application/cloudevents+json
channels:
  placeOrder:
    address: bookworm.{env}.finance.place-order
    description: Finance requests order placement; Notification consumes the same command to send a new-order email.
    parameters:
      env:
        $ref: "#/components/parameters/env"
    messages:
      placeOrder:
        $ref: "#/components/messages/PlaceOrderCommand"
  cancelOrder:
    address: bookworm.{env}.finance.cancel-order
    description: Finance publishes order cancellation work; Notification consumes it to send a canceled-order email.
    parameters:
      env:
        $ref: "#/components/parameters/env"
    messages:
      cancelOrder:
        $ref: "#/components/messages/CancelOrderCommand"
  completeOrder:
    address: bookworm.{env}.finance.complete-order
    description: Finance publishes order completion work; Notification consumes it to send a completed-order email.
    parameters:
      env:
        $ref: "#/components/parameters/env"
    messages:
      completeOrder:
        $ref: "#/components/messages/CompleteOrderCommand"
operations:
  receivePlaceOrder:
    action: receive
    channel:
      $ref: "#/channels/placeOrder"
    summary: Send a new-order notification
    description: |
      PlaceOrderCommandHandler maps the command to Status.New and renders the
      order email. BasketId is part of the shared command but is not used by
      Notification. A null fullName becomes Customer. Rendering, persistence,
      and sender failures propagate; a blank email skips all email work.
    messages:
      - $ref: "#/channels/placeOrder/messages/placeOrder"
  receiveCancelOrder:
    action: receive
    channel:
      $ref: "#/channels/cancelOrder"
    summary: Send a canceled-order notification
    description: |
      CancelOrderCommandHandler maps the command to Status.Canceled and renders
      the order email. A null fullName becomes Customer. Rendering, persistence,
      and sender failures propagate; a blank email skips all email work.
    messages:
      - $ref: "#/channels/cancelOrder/messages/cancelOrder"
  receiveCompleteOrder:
    action: receive
    channel:
      $ref: "#/channels/completeOrder"
    summary: Send a completed-order notification
    description: |
      CompleteOrderCommandHandler maps the command to Status.Completed and renders
      the order email. A null fullName becomes Customer. Rendering, persistence,
      and sender failures propagate; a blank email skips all email work.
    messages:
      - $ref: "#/channels/completeOrder/messages/completeOrder"
components:
  parameters:
    env:
      description: BookWorm deployment environment transformed to kebab case by KafkaTopicRouter.
      enum:
        - development
        - staging
        - production
      default: development
  messages:
    PlaceOrderCommand:
      name: PlaceOrderCommand
      title: Place order
      summary: Shared Finance command consumed by Notification for a new-order email.
      description: "Wolverine message identity: BookWorm.Contracts.PlaceOrderCommand."
      contentType: application/json
      headers:
        $ref: "#/components/schemas/KafkaHeaders"
      payload:
        $ref: "#/components/schemas/PlaceOrderPayload"
      examples:
        - name: newOrder
          payload:
            id: "019a1c00-0000-7000-8000-000000000001"
            creationDate: "2026-11-01T14:00:00Z"
            basketId: "019a1c00-0000-7000-8000-000000000010"
            orderId: "019a1c00-0000-7000-8000-000000000020"
            fullName: Example Customer
            email: customer@example.com
            totalMoney: 49.95
    CancelOrderCommand:
      name: CancelOrderCommand
      title: Cancel order
      summary: Shared Finance command consumed by Notification for a canceled-order email.
      description: "Wolverine message identity: BookWorm.Contracts.CancelOrderCommand."
      contentType: application/json
      headers:
        $ref: "#/components/schemas/KafkaHeaders"
      payload:
        $ref: "#/components/schemas/OrderStatusPayload"
      examples:
        - name: canceledOrder
          payload:
            id: "019a1c00-0000-7000-8000-000000000002"
            creationDate: "2026-11-01T14:01:00Z"
            orderId: "019a1c00-0000-7000-8000-000000000020"
            fullName: null
            email: customer@example.com
            totalMoney: 49.95
    CompleteOrderCommand:
      name: CompleteOrderCommand
      title: Complete order
      summary: Shared Finance command consumed by Notification for a completed-order email.
      description: "Wolverine message identity: BookWorm.Contracts.CompleteOrderCommand."
      contentType: application/json
      headers:
        $ref: "#/components/schemas/KafkaHeaders"
      payload:
        $ref: "#/components/schemas/OrderStatusPayload"
      examples:
        - name: completedOrder
          payload:
            id: "019a1c00-0000-7000-8000-000000000003"
            creationDate: "2026-11-01T14:02:00Z"
            orderId: "019a1c00-0000-7000-8000-000000000020"
            fullName: Example Customer
            email: customer@example.com
            totalMoney: 49.95
        - name: skippedRecipient
          summary: A null email is accepted by the contract but skips notification work.
          payload:
            id: "019a1c00-0000-7000-8000-000000000004"
            creationDate: "2026-11-01T14:02:00Z"
            orderId: "019a1c00-0000-7000-8000-000000000020"
            fullName: null
            email: null
            totalMoney: 49.95
  schemas:
    PlaceOrderPayload:
      type: object
      additionalProperties: false
      required:
        - id
        - creationDate
        - basketId
        - orderId
        - totalMoney
      properties:
        id:
          $ref: "#/components/schemas/EventId"
        creationDate:
          $ref: "#/components/schemas/CreationDate"
        basketId:
          type: string
          format: uuid
          description: Basket identifier in the shared command; unused by Notification.
        orderId:
          $ref: "#/components/schemas/OrderId"
        fullName:
          $ref: "#/components/schemas/FullName"
        email:
          $ref: "#/components/schemas/Email"
        totalMoney:
          $ref: "#/components/schemas/TotalMoney"
    OrderStatusPayload:
      type: object
      additionalProperties: false
      required:
        - id
        - creationDate
        - orderId
        - totalMoney
      properties:
        id:
          $ref: "#/components/schemas/EventId"
        creationDate:
          $ref: "#/components/schemas/CreationDate"
        orderId:
          $ref: "#/components/schemas/OrderId"
        fullName:
          $ref: "#/components/schemas/FullName"
        email:
          $ref: "#/components/schemas/Email"
        totalMoney:
          $ref: "#/components/schemas/TotalMoney"
    EventId:
      type: string
      format: uuid
      description: UUID v7 generated when the integration event is constructed.
    CreationDate:
      type: string
      format: date-time
      description: UTC timestamp when the integration event is constructed.
    OrderId:
      type: string
      format: uuid
      description: Order identifier used by Finance for Kafka message partitioning.
    FullName:
      type:
        - string
        - "null"
      description: Recipient display name; null maps to Customer.
    Email:
      type:
        - string
        - "null"
      description: |
        Recipient address. Null, empty, and whitespace-only values skip email
        work. The command handler does not validate email syntax; mailbox
        construction or SMTP submission can fail for invalid nonblank values.
    TotalMoney:
      type: number
      description: C# decimal order amount rendered in the email; the contract specifies no currency or nonnegative constraint.
    KafkaHeaders:
      type: object
      properties:
        traceparent:
          type: string
          description: Optional trace context propagated by CloudEventsOnlyKafkaMapper.
